python flask board-为什么我不能写?

时间:2019-10-16 08:22:25

标签: python flask sqlalchemy

我要制作的是一个“烧瓶”。我认为这将非常简单。 我安装了服务器,然后可以“注册”和“登录”。 我正在尝试以相同的方式“编写”,但无法正常工作。 根据错误消息,问题是“标题”,但是我已经定义了它。有什么问题? 请帮我:( :(我等你的答案。

烧瓶1.0.2, Python 3.7.3, Flask-SQLAlchemy,“注册”和“登录”:正在工作,“写入”:400错误

class User(db.Model):
    __table_name__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)`

class post(db.Model):
    __table_name__ = 'post'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    content = db.Column(db.Text, nullable=False)
    #date_posted = db.Column(db.DateTime, default=datetime.utcnow())
    #user_id = db.Column(db.Integer, db.ForeignKey('user_id'))`

def __init__(self, username, password, title, content):
    self.username = username
    self.password = password
    self.title = title
    self.content = content

@app.route('/register/', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        new_user = User(username=request.form['username'],password=request.form['password'])
        db.session.add(new_user)
        db.session.commit()
        return render_template('login.html')
    return render_template('register.html')`

@app.route('/write', methods = ['GET', 'POST'])
def write():
    if request.method == 'POST':
      if not request.form['title'] or not request.form['content']:
        return "<script>alert('Please enter all the fields'); location.href='/write';</script>"
      else:
        post = post(title=request.form['title'], content=request.form['content'])         

        db.session.add(post)
        db.session.commit()
        return "<script>alert('Success!'); location.href='/'; </script>"
    return render_template('write.html')

write.html

<form action = "/write" method = "post">
     <label for = "title">Title</label><br>
     <input type = "text" name = "title" placeholder = "title" /><br>
     <label for = "content">content</label><br>
     <textarea name = "content" placeholder = "content"></textarea><br>
     <input type = "submit" value = "Submit" />
</form>

错误消息

werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'title'

Traceback (most recent call last)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Python27\app.py", line 103, in write
if not request.form['title'] or not request.form['content']:
File "C:\Users\nGle\AppData\Local\Programs\Python\Python37-32\lib\site-packages\werkzeug\datastructures.py", line 442, in __getitem__
raise exceptions.BadRequestKeyError(key)
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'title'

1 个答案:

答案 0 :(得分:0)

使用

if not request.form.get('title') or not request.form.get('content'):

代替

if not request.form['title'] or not request.form['content']:

如果密钥不存在,则使用request.form.get('title')会将“ None”替换为“ 400 Bad Request”。