以下是我的Flask应用代码,非常基本:
from models import Base, User
from flask import Flask, jsonify, request, url_for, abort
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from flask import Flask
engine = create_engine('sqlite:///users.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
app = Flask(__name__)
@app.route('/api/users', methods = ['POST'])
def new_user():
username = request.json.get('username')
password = request.json.get('password')
print username
print password
if __name__ == '__main__':
app.debug = True
app.run(host='127.0.0.1', port=5000)
并使用curl
在命令行中发送HTTP POST请求,如下所示:
curl -i -X POST -H "Content-Type: application/json" -d '{"username":"abc","password":"123"}' http://localhost:5000/api/users
但得到400 BAD REQUEST
顺便说一下,我在windows cmd中运行这个应用程序。
提前感谢,欢迎任何帮助。编辑:
调试后,问题来自
username = request.json.get('username')
password = request.json.get('password')
这两个命令。如果注释掉以上两行,则curl请求可以成功。但仍然不知道原因
答案 0 :(得分:1)
之前我也遇到过这个问题。如果在windows cmd中使用curl,则可能需要使用双引号,并在JSON中转义这些引号。
1tontech.angular-material
4tron.angular-material-snippets
Angular.ng-template
AngularDoc.angulardoc-vscode
EditorConfig.EditorConfig
GregorBiswanger.json2ts
HookyQR.beautify
MarinhoBrandao.Angular2Tests
NG-42.ng-fortytwo-vscode-extension
SimonTest.simontest
UVBrain.Angular2
abusaidm.html-snippets
anweber.vscode-tidyhtml
christian-kohler.npm-intellisense
christian-kohler.path-intellisense
dbaeumer.vscode-eslint
eg2.tslint
eg2.vscode-npm-script
esbenp.prettier-vscode
felixfbecker.php-debug
felixfbecker.php-intellisense
felixfbecker.php-pack
formulahendry.auto-close-tag
formulahendry.auto-rename-tag
jasonnutter.search-node-modules
johnpapa.Angular2
loiane.angular-extension-pack
ms-vscode.autorest
ms-vscode.cpptools
ms-vscode.typescript-javascript-grammar
msjsdiag.debugger-for-chrome
pkosta2006.rxjs-snippets
robertohuertasm.vscode-icons
steoates.autoimport
vuhrmeister.vscode-meteor
waderyan.nodejs-extension-pack
xabikos.JavaScriptSnippets
答案 1 :(得分:0)
您的视图功能需要返回响应。如果要返回空响应正文,请添加以下内容:
return ('',201)
到new_user()