我对Flask和Postgres有一个问题。下面我将链接我的app.py,models.py和views.py。每当我尝试定义新用户并将其添加到数据库时,就会出现400错误。我检查了我的服务器在postgres中运行,并且我已连接到数据库。我的所有表都已正确创建,并且我能够在python shell中传递新用户。有什么想法吗?
app.py
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:pass@localhost/mydb'
db = SQLAlchemy(app)
from views import *
from models import *
if __name__=='__main__':
db.create_all()
app.run(debug=True)
views.py
from app import app
from app import db
from models import User
from flask import Flask, render_template, redirect, url_for, request
@app.route('/')
def home():
#this will look different for logged in and logged out users
return render_template('home.html')
@app.route('/about')
def about():
#notes
return render_template('about.html')
@app.route('/contact')
def contact():
#notes
return render_template('contact.html')
@app.route('/blog')
def blog():
#notes
return render_template('blog.html')
@app.route('/podcast')
def podcast():
#notes
return render_template('podcast.html')
@app.route('/shop')
def shop():
#notes
return render_template('shop.html')
@app.route('/add_user', methods=['GET', 'POST'])
def add_user():
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
return render_template('add_user.html')
models.py
from app import db
from flask_sqlalchemy import SQLAlchemy
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
add_user.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Add User</title>
</head>
<body>
<form action="/add_user" method="post">
<label>username:</label>
<input type="text" id="username" name="username">
<label>email:</label>
<input type="text" id="email" name="email">
<input type="submit">
</form>
</body>
</html>
答案 0 :(得分:0)
在view.py而不是
def add_user():
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
return render_template('add_user.html')
试试这段代码
def add_user():
if request.method == 'POST':
user = User(request.form['username'], request.form['email'])
db.session.add(user)
db.session.commit()
return render_template('add_user.html')
http://flask.pocoo.org/docs/0.12/quickstart/#the-request-object
如果你将get请求发送到/ add_user,那么看不到表单变量用户名和密码,request.form只能从post发送并放入requsest。
来自文档: &#34;如果表单属性中不存在键,会发生什么?在这种情况下,会引发一个特殊的KeyError。您可以像标准KeyError一样捕获它,但如果不这样做,则会显示HTTP 400错误请求错误页面。因此,对于许多情况,您不必处理该问题。 &#34;