from flask import Flask, jsonify, request
from flask_restful import Api, Resource
import jsonpickle
app = Flask(__name__)
api = Api(app)
# creating an empty dictionary and initializing user id to 0.. will increment everytime a person makes a POST request
user_dict = {}
user_id = 0
# Define a class and pass it a Resource. These methods require an ID
class User(Resource):
@staticmethod
def get(path_user_id):
return jsonify(jsonpickle.encode(user_dict.get(path_user_id, "This user does not exist")))
当我启动服务器时,我去访问/ users / 1端点。由于字典为空,因此不存在。我得到一个KeyError,所以我的临时解决方案是将我的字典访问器从user_dict[path_user_id]
更改为.get(path_user_id, "This user does not exist")
。有没有更好的方法来处理这个?
我不确定这是否有用,但是我的字典由整数键组成,这些键映射到“Person”类,其中包含有关该人的信息(姓名,年龄,地址等)
404状态代码表示“未找到资源”,完全适合您的用例
from flask import abort
...
def get(path_user_id):
if path_user_id not in user_dict:
abort(404)
...