使用django-piston时,我收到了400错误请求错误 [英] I get a 400 Bad Request error while using django-piston

查看:344
本文介绍了使用django-piston时,我收到了400错误请求错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用活塞向Django提供REST支持。
我已经按照提供的文档实现了我的处理程序。
问题是我可以阅读和删除我的资源,但我不能创建或更新。
每次我打相关的api我得到一个400错误请求错误。

I am trying to use Piston to provide REST support to Django. I have implemented my handlers as per the documentation provided . The problem is that i can "read" and "delete" my resource but i cannot "create" or "update". Each time i hit the relevant api i get a 400 Bad request Error.

我已经使用这个常用的代码片段扩展了csrf的资源类:

I have extended the Resource class for csrf by using this commonly available code snippet:

class CsrfExemptResource(Resource):
    """A Custom Resource that is csrf exempt"""
    def __init__(self, handler, authentication=None):
        super(CsrfExemptResource, self).__init__(handler, authentication)
        self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)

我的课程(代码片段)如下所示:

My class (code snippet) looks like this:

user_resource = CsrfExemptResource(User)

class User(BaseHandler):
    allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')

    @require_extended
    def create(self, request):
        email = request.GET['email']
        password = request.GET['password']
        phoneNumber = request.GET['phoneNumber']
        firstName = request.GET['firstName']
        lastName = request.GET['lastName']
        self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
        return rc.CREATED

请让我知道如何使用POST操作获得创建方法的工作? / p>

Please let me know how can i get the create method to work using the POST operation?

推荐答案

这是因为活塞不喜欢ExtJS将charset = UTF-8

This is happening because Piston doesn't like the fact that ExtJS is putting "charset=UTF-8" in the content-type of the header.

通过添加一些中间件来使内容类型更加活塞友好,轻松修复,在您的应用程序基础目录中创建一个名为middleware.py的文件:

Easily fixed by adding some middleware to make the content-type a bit more Piston friendly, create a file called middleware.py in your application base directory:

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if request.META['CONTENT_TYPE'] == 'application/x-www-form-urlencoded; charset=UTF-8':
            request.META['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        return None

然后只需在您的settings.py中包含此中间件:

Then simply include this middleware in your settings.py:

MIDDLEWARE_CLASSES = (
    'appname.middleware.ContentTypeMiddleware',
)

这篇关于使用django-piston时,我收到了400错误请求错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆