我的网络服务应该接收以下两种格式的电话: application / x-www-form-urlencoded 和内容类型的应用/ json 。
以下代码适用于表单。但是,它对json的工作并不起作用。显然我需要使用request.args.get
。
有没有办法修改代码,以便同一方法可以接收这两种格式的调用?
@app.route("/api/<projectTitle>/<path:urlSuffix>", methods=['POST'])
def projectTitlePage(projectTitle, urlSuffix):
apiKey = request.form.get('apikey')
userId = databaseFunctions.getApiKeyUserId(apiKey)
userInfo = databaseFunctions.getUserInfo(userId)
projectId = databaseFunctions.getTitleProjectId(projectTitle)
projectInfo = databaseFunctions.getProjectInfo(projectId)
databaseFunctions.addUserHit(userId, projectId)
databaseFunctions.addProjectHit(userId)
print request.form.to_dict(flat=False)
try:
r = requests.post(projectInfo['secretUrl'], data=request.form.to_dict(flat=False))
except Exception, e:
return '/error=Error'
return r.text
答案 0 :(得分:4)
尝试使用Request.get_json()
获取JSON;如果失败则会引发异常,之后您可以回退到使用request.form
:
from flask import request
from werkzeug.exceptions import BadRequest
try:
data = request.get_json()
apiKey = data['apikey']
except (TypeError, BadRequest, KeyError):
apiKey = request.form['apikey']
如果mimetype不是application/json
,则request.get_json()
会返回None
;尝试使用data['apikey']
会产生TypeError
。 mimetype是正确的但是JSON数据无效会给你BadRequest
,而所有其他无效的返回值要么导致KeyError
(没有这样的键)或TypeError
(对象没有' t支持按名称索引)。
另一种选择是测试request.mimetype
attribute:
if request.mimetype == 'application/json':
data = request.get_json()
apiKey = data['apiKey']
else:
apiKey = request.form['apikey']
无论哪种方式,如果没有有效的JSON数据或表单数据已发布但没有apikey
条目或发布了不相关的mimetype,则会引发BadRequest
异常并且400响应为回到了客户端。
答案 1 :(得分:0)
我对Flask并不是特别熟悉,但根据他们的文档,您应该可以做类似的事情
content = request.headers['CONTENT-TYPE']
if content[:16] == 'application/json':
# Process json
else:
# Process as form-encoded
答案 2 :(得分:0)
无论标题如何,我提取json
和form-data
的方法都是
data = request.get_json() or request.form
key = data.get('key')