所以我有以下app.py文件,我试图处理一个帖子请求,它基本上会读取名字,姓氏,用户名和密码,然后将它存储在mongodb中,但这是为了以后。截至目前,我无法收到发布/获取请求。
当我尝试使用postman将数据提交到localhost:5000 / register时,即使是我尝试运行的小片段也会给我一个错误的请求错误。
任何帮助将不胜感激。
from flask import *
#from pymongo import MongoClient
#import json
app = Flask(__name__)
# main interface
@app.route("/")
def main():
return render_template('index.html')
# Register Interface
@app.route('/register/', methods = ['GET'])
def register():
#collection = db['userdb']
firstname = request.form['firstname']
lastname = request.form['lastname']
username = request.form['username']
password = request.form['password']
#postData = { 'firstname': firstname, 'lastname': lastname,'username':username,'password':password}
#json = json.dumps(postData)
#try:
#status = db.userdb.insert_one(postData).insert_id
#except:
#status = 'This user is already registerd'
return 'This data works'
if __name__ == "__main__":
app.run()
答案 0 :(得分:4)
你需要添加" POST'路径装饰器的方法,但还需要一个步骤。使用if语句使视图忽略request.form赋值:
from flask import *
#from pymongo import MongoClient
#import json
app = Flask(__name__)
# main interface
@app.route("/")
def main():
return 'go to <a href="/register/">register</a>'
# Register Interface
@app.route('/register/', methods = ['GET','POST'])
def register():
#collection = db['userdb']
if request.method == 'POST':
firstname = request.form['firstname']
lastname = request.form['lastname']
username = request.form['username']
password = request.form['password']
#postData = { 'firstname': firstname, 'lastname': lastname,'username':username,'password':password}
return 'This data works'
if __name__ == "__main__":
app.run(debug=True)
这是使用GET和POST的视图中的常见模式。另请注意,我已将debug = True添加为app.run的参数。这将使调试代码变得更加容易。
答案 1 :(得分:3)
@app.route('/register/', methods = ['GET'])
上面的装饰器意味着处理程序只会映射到GET请求。
@app.route('/register/', methods = ['GET', 'POST'])
尝试一下,你应该好好去。