簡體   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