我有这个:
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方法正在运行。是错误,还是我的代码错了?
答案 0 :(得分:1)
即使你没有在你的问题中包含这个代码,我在你给你的github中找到了它的评论......
您正在映射到不允许POST请求的处理程序
urls.py :: snip ::
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
被路由到'/api/chat/'
。我觉得你期望它去聊天处理程序。这意味着您需要将javascript请求网址更改为Meta
,或将代码移至您预期的处理程序。
此外,您在处理程序中设置错误的模型。它不需要class PostHandler(BaseHandler):
model = Post
class ChatHandler(BaseHandler):
model = ChatMsg
嵌套类。它应该是:
{{1}}