【问题标题】:Best way to handle KeyError in dictionary when working with Python RESTful API使用 Python RESTful API 时处理字典中 KeyError 的最佳方法
【发布时间】:2019-05-01 17:09:30
【问题描述】:
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”类,其中包含有关人的信息(姓名、年龄、地址等)

【问题讨论】:

  • 当被问及一个不存在的用户时,我认为服务器本身应该返回一个400: Bad Request: The request was invalid.
  • 根据 HTTP 状态码定义,400 代表The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. ,因此不应用于语法正确的请求

标签: python-3.x dictionary flask flask-restful keyerror


【解决方案1】:

404 状态代码表示“找不到资源”,非常适合您的用例

from flask import abort

...

def get(path_user_id):
    if path_user_id not in user_dict:
        abort(404)
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    相关资源
    最近更新 更多