使用Tastypie更新(PUT)在Python中启用CORS

时间:2014-09-22 16:20:10

标签: python django cors tastypie

关于此主题的SO有几个问题,但我见过的没有一个问题可以解决我的问题。

我的Django / Tastypie API中有一个端点,它接受PUT以更新数据库。这在localhost:8000中进行测试时效果很好,但是,我的生产数据库位于不同的域中,因此我需要启用CORS来调用此PUT来更新数据库。

我发现教程here提供了一个如何执行此操作的示例,但是,当我执行cURL命令时:

curl -X PUT --dump-header - -H "Content-Type: application/json" -H "Authorization: ApiKey api:MYAPIKEY" -d "{\"mykey\": \"my_value\", \"resource_uri\": \"/api/v1/mytable/362/\"}" my.domain.com/api/v1/mytable/362/

我仍在接收 401 UNAUTHORIZED 我的电话(下方的标题转储):

HTTP/1.1 401 UNAUTHORIZED
Date: Mon, 22 Sep 2014 16:08:34 GMT
Server: Apache/2.4.7 (Ubuntu)
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,Authorization
X-Frame-Options: SAMEORIGIN
Content-Length: 0
Content-Type: text/html; charset=utf-8

My CoresResource超类代码:

class CorsResource(ModelResource):
    """ adds CORS headers for cross-domain requests """
    def patch_response(self, response):

        allowed_headers = ['Content-Type', 'Authorization']

        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Headers'] = ','.join(allowed_headers)
        return response

    def dispatch(self, *args, **kwargs):
        """ calls super and patches resonse headers
            or
            catches ImmediateHttpResponse, patches headers and re-raises
        """

        try:
            response = super(CorsResource, self).dispatch(*args, **kwargs)
            return self.patch_response(response)
        except ImmediateHttpResponse, e:
            response = self.patch_response(e.response)
            # re-raise - we could return a response but then anthing wrapping
            # this and expecting an exception would be confused
            raise ImmediateHttpResponse(response)

    def method_check(self, request, allowed=None):
        """ Handle OPTIONS requests """
        if request.method.upper() == 'OPTIONS':

            if allowed is None:
                allowed = []

            allows = ','.join([s.upper() for s in allowed])

            response = HttpResponse(allows)
            response['Allow'] = allows
            raise ImmediateHttpResponse(response=response)

        return super(CorsResource, self).method_check(request, allowed)

我的终端代码:

class DataModelResource(CorsResource):

    data = fields.OneToOneField(DataModelResource, "data", full=True)

    class Meta:
        allowed_methods = ['get', 'put']
        authentication = ApiKeyAuthentication()
        authorization = Authorization()
        queryset = Data.objects.all()
        resource_name = 'mytable'

有没有人看到为什么从跨域提出PUT应该使用此代码失败的原因??? 我在这里完全失败了。

0 个答案:

没有答案