当用户在网址中输入错误的时区时,我试图显示自定义错误消息。在这种情况下,用户应该输入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=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)
通常,您将在响应中返回status code of 400和其他信息,这些信息可以帮助呼叫者理解为什么他们的请求被拒绝。使用flask进行此操作的最简单方法是返回flask.Response
,如下所示:
@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提供了一些方法来定制如何将引发的异常传播到调用方。您可以阅读有关此here的更多信息。
希望这会有所帮助!
最简单的方法:
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()})
根据用户可能引起的错误选择正确的status code ...
您还需要from flask import jsonify, make_response
400可能是任何其他代码...也许他们发送了一些缺少的表单字段,或者在POST请求中未包含JSON正文...也许他们没有输入正确的用户名和密码,并且需要401未经授权等
作为旁注,成功返回消息不使用make_response,因为如果我没记错的话,默认情况下它将返回200-ok。
此外,如果您要将JSON返回给用户,请不要理会r.text
。使用r.json()
,因为它已经为您序列化。