繁体   English   中英

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

[英]python flask board - Why Can't I write?

我想做的是一个“烧瓶板”。 我以为这会很简单。 我架起服务器,我可以“注册”和“登录”。 我正在尝试以相同的方式“编写”,但它不起作用。 根据错误消息,问题是“标题”,但我已经定义了它。 有什么问题? 请帮帮我:(:(我会等你的回答。

Flask 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')

写.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'

利用

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'。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM