django-piston:正确格式化客户端应用的POST数据
我有一个Django应用,这次第一次使用django-piston。
我为一个模型配置了一个处理器,它可以处理GET和POST请求。
GET请求运行得很好,没问题。
但是POST请求就不太行了。当我向它发送数据时,出现了这个错误
Responded: Piston/0.2.3rc1 (Django 1.2.4) crash report:
Method signature does not match.
Resource does not expect any parameters.
Exception was: cannot concatenate 'str' and 'dict' objects
我对Python不是很专业,但简单搜索一下发现,这似乎是一个比较常见的Python类型错误(TypeError)。
下面是一些代码。
urls.py(相关部分)
auth = DjangoAuthentication()
ad = { 'authentication': auth }
word_handler = Resource(handler = WordHandler, **ad)
urlpatterns = patterns(
url(r'^word/(?P<word_id>[^/]+)/', word_handler),
url(r'^words/', word_handler),
)
handlers.py(相关部分)
class WordHandler(BaseHandler):
allowed_methods = ('GET','POST',)
model = Word
fields = ('string', 'id', 'sort_order', ('owner', ('id',)),)
def read(self, request, word_id = None):
"""
Read code goes here
"""
def create(self, request):
if request.content_type:
data = request.data
print("Words Data: " + data)
existing_words = Word.objects.filter(owner = request.user)
for word in data['words']:
word_already_exists = False
for existing_word in existing_words:
if word["string"] == existing_word.string:
word_already_exists = True
break
if not word_already_exists:
Word(string = word["string"], owner = request.user).save()
return rc.CREATED
基本上,它根本没有进入create()这个函数,或者至少看起来是这样的。它就直接报错了,所以我甚至无法看到它是如何接收数据的。
顺便说一下,这是我尝试POST的数据
{"words":[{"owner":{"id":1,"tags":null,"password":null,"words":null,"email":null,"firstname":null,"lastname":null,"username":null},"id":1,"sort_order":0,"tags":null,"string":"Another Test"},{"owner":{"id":1,"tags":null,"password":null,"words":null,"email":null,"firstname":null,"lastname":null,"username":null},"id":2,"sort_order":0,"tags":null,"string":"Here's a test"},{"owner":null,"id":0,"sort_order":0,"tags":null,"string":"Tampa"}]}
任何信息都会非常有帮助。
1 个回答
0
我自己解决了这个问题。
导致错误的原因在于创建方法中的这一行
if request.content_type:
这行代码并没有像我想的那样被判断为True
,我觉得django-piston文档的作者可能是这么想的。即使这个值是一个有内容的字符串。
把这一行去掉就解决了这个问题。我相信你也可以直接做个字符串的判断。
我真的不太明白他们当时在想什么。