1

私はこれを持っています:

handlers.py

class ChatHandler(BaseHandler):
    model = ChatMsg
    allowed_methods = ('POST','GET')

    def create(self, request, text):
        message = ChatMsg(user = request.user, text = request.POST['text'])
        message.save()
        return message

template.html

    ...
    <script type="text/javascript">
    $(function(){
        $('.chat-btn').click(function(){
            $.ajax({
                url: '/api/post/',
                type: 'POST',
                dataType: 'application/json',
                data: {text: $('.chat').val()}
            })
        })
    })
    </script>
    ...

api/urls.py

chat_handler = Resource(ChatHandler, authentication=HttpBasicAuthentication)
urlpatterns = patterns('',
    ....
    url(r'^chat/$', chat_handler, {'emitter_format': 'json'}),
)

なぜですが、ChatHandler で POST メソッドが許可されているのですか? GET メソッドが機能しています。バグですか、それとも私のコードが間違っていますか?

4

1 に答える 1

1

質問にこのコードを含めていませんでしたが、コメントで提供したgithubで見つけました...

POST リクエストを許可しないハンドラにマッピングしています

urls.py ::中略::

post_handler = Resource(PostHandler, authentication=auth)
chat_handler = Resource(ChatHandler, authentication=auth)
urlpatterns = patterns('',
    url(r'^post/$', post_handler , { 'emitter_format': 'json' }),
    url(r'^chat/$', chat_handler, {'emitter_format': 'json'}),
)

handlers.py

# url: '/api/post'
# This has no `create` method and you are not 
# allowing POST methods, so it will fail if you make a POST
# request to this url
class PostHandler(BaseHandler):
    class Meta:
        model = Post

    # refuses POST requests to '/api/post'
    allowed_methods = ('GET',)


    def read(self, request):
        ...

# ur;: '/api/chat'
# This handler does have both a POST and GET method allowed.
# But your javascript is not sending a request here at all.
class ChatHandler(BaseHandler):
    class Meta:
        model = ChatMsg
    allowed_methods = ('POST', 'GET')

    def create(self, request, text):
        ...

    def read(self, request):
        ...

あなたの JavaScript リクエストは に送信され'/api/post/'、 にルーティングされていPostHandlerます。チャット ハンドラに送られることを期待していたようですね。つまり、javascript リクエストの URL を に変更する'/api/chat/'か、コードを必要なハンドラーに移動する必要があります。

また、ハンドラーでモデルを間違って設定しています。Metaネストされたクラスは必要ありません。そのはず:

class PostHandler(BaseHandler):
    model = Post

class ChatHandler(BaseHandler):
    model = ChatMsg
于 2012-09-19T14:49:46.593 に答える