使用 Python eve 创建资源时如何在请求中禁止“_id”?
How to disallow "_id" in the request while creating resources using Python eve?
我正在使用 Python Eve 来实现 REST API。
在使用 POST 创建资源时,我似乎可以在请求正文中为“_id”字段传递一个值,只要该值符合 Mongo 的 ObjectId 格式, Eve 正在使用传入的值作为资源的 ID。
有什么方法可以禁用此行为吗?基本上,我希望后端生成 ID,并且不想让客户端设置它们。我检查了所有可用的配置选项,但没有找到这方面的任何内容。
提前致谢,
拉古
不知道如何禁用,但您可以通过 pre_post 钩子检查 post 正文中的字段来避免,如果找到则中止。像这样:
from flask import abort
def on_post_check__id(resource, request):
# handling bulk inserts
body = request.json if type(request.json) == list else [request.json]
for item in body:
if '_id' in item:
abort(422, '_id not allowed in body.')
app = Eve()
app.on_pre_POST += on_post_check__id
app.run()
我正在使用 Python Eve 来实现 REST API。
在使用 POST 创建资源时,我似乎可以在请求正文中为“_id”字段传递一个值,只要该值符合 Mongo 的 ObjectId 格式, Eve 正在使用传入的值作为资源的 ID。
有什么方法可以禁用此行为吗?基本上,我希望后端生成 ID,并且不想让客户端设置它们。我检查了所有可用的配置选项,但没有找到这方面的任何内容。
提前致谢, 拉古
不知道如何禁用,但您可以通过 pre_post 钩子检查 post 正文中的字段来避免,如果找到则中止。像这样:
from flask import abort
def on_post_check__id(resource, request):
# handling bulk inserts
body = request.json if type(request.json) == list else [request.json]
for item in body:
if '_id' in item:
abort(422, '_id not allowed in body.')
app = Eve()
app.on_pre_POST += on_post_check__id
app.run()