简体   繁体   English

使用django-piston时出现400 Bad Request错误

[英]I get a 400 Bad Request error while using django-piston

I am trying to use Piston to provide REST support to Django. 我正在尝试使用Piston为Django提供REST支持。 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. 每次我点击相关的api我得到400 Bad request Error。

I have extended the Resource class for csrf by using this commonly available code snippet: 我已经使用这个常用的代码片段扩展了csrf的Resource类:

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

Please let me know how can i get the create method to work using the POST operation? 请让我知道如何使用POST操作使create方法工作?

This is happening because Piston doesn't like the fact that ExtJS is putting "charset=UTF-8" in the content-type of the header. 这种情况正在发生,因为Piston不喜欢ExtJS在标题的内容类型中放置“charset = UTF-8”这一事实。

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

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

Then simply include this middleware in your settings.py: 然后只需在settings.py中包含此中间件:

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

Proposed solutions still did not work for me (django 1.2.3/piston 0.2.2) so I've tweaked joekrell solution and this finally works (I'm only using POST and PUT, but presumably you can add other verbs to the list): 建议的解决方案仍然不适合我(django 1.2.3 /活塞0.2.2)所以我调整了joekrell解决方案,这最终工作(我只使用POST和PUT,但可能你可以添加其他动词到列表):

class ContentTypeMiddleware(object):

def process_request(self, request):

    if request.method in ('POST', 'PUT'):
        # dont break the multi-part headers !
        if not 'boundary=' in request.META['CONTENT_TYPE']:
            del request.META['CONTENT_TYPE']

with: 有:

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

I haven't noticed any side-effect, but I can't promise it's bullet-proof. 我没有注意到任何副作用,但我不能保证它是防弹的。

I have combined some of what other people have said, and added support for any content type, json for instance... 我结合了其他人所说的一些内容,并添加了对任何内容类型的支持,例如json ......

class ContentTypeMiddleware(object):
    def process_request(self, request):
        if request.method in ('POST', 'PUT') and request.META['CONTENT_TYPE'].count(";") > 0:
            request.META['CONTENT_TYPE'] = [c.strip() for c in request.META['CONTENT_TYPE'].split(";") ][0]
        return None

I thought Eric's solution worked the best but then ran into problems when saving things in admin. 我认为Eric的解决方案效果最好,但在管理员中保存时会遇到问题。 This tweak seems to fix it if anyone else comes across it: 如果有其他人遇到它,这个调整似乎解决了它:

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if request.method in ('POST') and not 'boundary=' in request.META['CONTENT_TYPE']:
            request.META['CONTENT_TYPE'] = [c.strip() for c in request.META['CONTENT_TYPE'].split(";") ][0]
        return None

This is solution which worked for me, after a tweak: 经过调整后,这个解决方案对我有用:

class ContentTypeMiddleware(object):

    def process_request(self, request):
        if 'charset=UTF-8' in request.META['CONTENT_TYPE']:
            request.META['CONTENT_TYPE'] = request.META['CONTENT_TYPE'].replace('; charset=UTF-8','')
        return None

In utils.py, change this. 在utils.py中,更改此设置。

def content_type(self):
    """
    Returns the content type of the request in all cases where it is
    different than a submitted form - application/x-www-form-urlencoded
    """
    type_formencoded = "application/x-www-form-urlencoded"

    ctype = self.request.META.get('CONTENT_TYPE', type_formencoded)

    if ctype.strip().lower().find(type_formencoded) >= 0:
        return None

    return ctype

https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type https://bitbucket.org/jespern/django-piston/issue/87/split-charset-encoding-form-content-type

We had a resource that was simply updating a timestamp based on the request credentials and PUT. 我们有一个资源只是根据请求凭据和PUT更新时间戳。 It turns out that Piston does not like PUT without a payload. 事实证明,活塞不喜欢没有有效载荷的PUT。 Adding an empty string payload '' fixed it. 添加空字符串有效负载''修复它。

A quick Google search indicates that other systems like Apache may not like PUT without a payload, as well. 一个快速的谷歌搜索表明,像Apache这样的其他系统也可能不喜欢没有有效载荷的PUT。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM