【问题标题】:django-piston: properly formatting POST data from a client applicationdjango-piston:正确格式化来自客户端应用程序的 POST 数据
【发布时间】:2011-06-21 03:13:06
【问题描述】:

我有一个第一次运行 django-piston 的 Django 应用程序。

我已经为模型配置了一个处理程序,它被操纵用于 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

基本上,它甚至根本无法创建(),或者至少似乎没有。它只是因上述错误而崩溃,所以我什至看不到它是如何接收数据的。

这就是我要发布的数据

{"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"}]}

任何信息都会非常有帮助。

【问题讨论】:

    标签: python django json rest django-piston


    【解决方案1】:

    我自己解决了这个问题。

    错误的相关原因是create方法中的这一行

    if request.content_type:
    

    这并不像我认为 django-piston 文档的创建者所期望的那样评估为 True。即使值是一个带值的字符串。

    删除此行解决了它。而且我敢肯定你可以只做一个字符串评估。

    不太确定他们在想什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2022-09-24
      • 2021-07-11
      • 2015-09-07
      相关资源
      最近更新 更多