Python 处理来自用户的错误API请求
当用户在url中输入错误时区时,我试图显示自定义错误消息。 在这种情况下,假设用户输入EST获取该特定时区,但如果他输入的时区不存在,我希望处理该错误。我该怎么做? 这是我的密码:Python 处理来自用户的错误API请求,python,rest,flask,Python,Rest,Flask,当用户在url中输入错误时区时,我试图显示自定义错误消息。 在这种情况下,假设用户输入EST获取该特定时区,但如果他输入的时区不存在,我希望处理该错误。我该怎么做? 这是我的密码: ''' http://127.0.0.1:5000/get_time?time_zone=est eastern http://127.0.0.1:5000/get_time?time_zone=pst for pacific etc http://127.0.0.1:5000/get_time?time_zone=
'''
http://127.0.0.1:5000/get_time?time_zone=est eastern
http://127.0.0.1:5000/get_time?time_zone=pst for pacific etc
http://127.0.0.1:5000/get_time?time_zone=mdt wrong time zone
returns:
TypeError
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
'''
import requests
import json
import jsonpath
from flask import Flask, render_template, request
from flask import jsonify
app = Flask(__name__, template_folder="templates")
@app.route('/get_time', methods=['GET'])
def get_timec():
time_zone = request.args.get('time_zone')
url = "http://worldclockapi.com/api/json/" + time_zone + "/now"
response = requests.get(url)
json_response = json.loads(response.text)
if response.status_code != 200:
print("Error on response")
return response.status_code
print("Here is your time in the East Coast of the US: ")
return json_response['currentDateTime']
if __name__ == '__main__':
app.run(debug=True)
通常,您会在响应中返回一个和其他信息,以帮助调用方理解其请求被拒绝的原因。使用烧瓶执行此操作的最简单方法是返回一个
烧瓶。响应如下所示:
@app.route('/get_time', methods=['GET'])
def get_timec():
time_zone = request.args.get('time_zone')
if not is_valid_time_zone(time_zone):
return flask.Response(
status=400, content_type='application/json', response=json.dumps({
'reason': 'Invalid timezone: "{}"'.format(time_zone),
'code': 1 # Many APIs implement a more specific code system to help callers debug things like this.
}))
# Continue handling the request...
如果您更愿意使用异常,Flask提供了定制如何将引发的异常传播到调用方的方法。你可以阅读更多关于这方面的内容
希望这有帮助 最简单的方法:
try:
time_zone = request.args.get('time_zone')
url = "http://worldclockapi.com/api/json/" + time_zone + "/now"
r = requests.get(url)
except Exception:
return make_response(jsonify({"Error": "Some error message"}), 400)
return jsonify({"Success": r.json()})
根据用户可能导致的错误选择正确的
您还需要从flask import jsonify获得,并做出响应
400可能是任何其他代码。。。可能他们发送了一些缺少的表单字段,或者在POST请求中没有包含JSON正文。。。也许他们没有输入正确的用户名和密码,需要401密码等等
作为旁注,returnsuccess消息没有使用make_响应,因为如果我没有记错的话,它将默认返回200 ok
另外,如果您要将JSON返回给用户,r.JSON()
可能是比r.text
更好的选择。您是在问“如何验证时区?”还是“如果客户端提供了无效时区,我应该如何响应客户端?”不确定您具体要求什么帮助,如果客户提供无效时区,我如何回应他们。