gpt4 book ai didi

python - 发布 django 时过滤 csrfmiddlewaretoken

转载 作者:太空宇宙 更新时间:2023-11-04 10:55:04 26 4
gpt4 key购买 nike

我打算使用 django-piston 制作通用的 CRUD。我的示例代码之一如下

class TaskHandler(BaseHandler):
allowed_methods = ('GET','POST',)
model = Task

def read(self, name=None):
return self.model.objects.all()

def create(self, request, *args, **kwargs):
if not self.has_model():
return rc.NOT_IMPLEMENTED

attrs = self.flatten_dict(request.POST)
if attrs.has_key('data'):
# rest.POST.get('data') has csrfmiddlewaretoken as a hiddenfield
# i need to exclude it from post as my ORM is giving error message
ext_posted_data = simplejson.loads(request.POST.get('data'))
attrs = self.flatten_dict(ext_posted_data)

try:
inst = self.model.objects.get(**attrs)
return rc.DUPLICATE_ENTRY
except self.model.DoesNotExist:
inst = self.model(**attrs)
inst.save()
return inst
except self.model.MultipleObjectsReturned:
return rc.DUPLICATE_ENTRY

错误日志如下

Piston/0.2.2 (Django 1.4) crash report:
Traceback (most recent call last):
File "C:\Python27\Lib\site-packages\django\bin\sumit\sumit\handler.py", line 27,
in create inst = self.model.objects.get(**attrs)
File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 131,
in get return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 358,
in get clone = self.filter(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 621,
in filter return self._filter_or_exclude(False, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 639,
in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs))
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1250,
in add_q can_reuse=used_aliases, force_having=force_having)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1122,
in add_filter process_extras=process_extras)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 1316,
in setup_joins "Choices are: %s" % (name, ", ".join(names)))

FieldError: **Cannot resolve keyword 'csrfmiddlewaretoken' into field.
Choices are: complete, id, name**

最佳答案

简而言之:不要那样做。

任何用户都可以发送他们想要的任何 POST 参数。您根本无法保证他们不会添加任何随机 POST 参数,即使您的表单不包含它也是如此。

与其尝试从您的参数中过滤出 csrfmiddlewaretoken,不如尝试将您想要包含的参数列入白名单。这意味着,只选择那些与您的模型字段相对应的字段并且您希望用户能够对其进行过滤。

更新:
好吧,那么,怎么过滤掉呢,正好满足一下你的好奇心。 flatten_dict 返回一个常规的 Python 字典,这意味着您可以简单地 del attrs['csrfmiddlewaretoken'] 将其从字典中删除。

更新(2):
要列入白名单,类似以下的内容应该可以工作:

allowed_keys = ['complete', 'id', 'name']
attrs = dict((key, value) for key, value in ext_posted_data if key in allowed_keys)

关于python - 发布 django 时过滤 csrfmiddlewaretoken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10512419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com