我计划使用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**
答案 0 :(得分:4)
简而言之:不要那样做。
任何用户都可以发送他们想要的任何POST参数。您无法保证即使您的表单不包含任何随机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)