I get a 400 Bad Request error while using django-p

2019-03-15 19:50发布

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.

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

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

7条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-15 20:34

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
查看更多
登录 后发表回答