简体   繁体   English

Django Tastypie 0.9.13-beta:资源始终返回status_code 200

[英]Django Tastypie 0.9.13-beta: resource always return status_code 200

I've been working on API using Django and Tastypie of version django-tastypie==0.9.13-beta and in test cases when I expect bad request response with 400 or 401 and it always returns http ok 200 response. 我一直对使用API DjangoTastypie版本的django-tastypie==0.9.13-beta和测试用例时,我想到bad request 400或401的响应,它总是返回http ok 200响应。 What can cause this problem? 什么会导致此问题?

User resource 用户资源

class UserAuthentication(ApiKeyAuthentication):
    def __init__(self, no_auth, full_auth, require_active=True):
        super(Authentication, self).__init__()
        self.no_auth = no_auth
        self.full_auth = full_auth

    def is_authenticated(self, request, **kwargs):
        if request.method not in self.no_auth:
            return super(UserAuthentication, self).is_authenticated(request, **kwargs)

        return True


class UsersResource(MyModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['post']
        detail_allowed_methods = ['put']
        fields = ['id', 'first_name', 'last_name', 'email']
        validation = UserValidation()
        always_return_data = True
        authorization = UserAuthorization()
        authentication = UserAuthentication(no_auth=['GET', 'POST'], full_auth=['PUT'])

Small part of tests 测试的一小部分

def test_login_unsuccessful_wrong_email(self):
    post_data = {
        "user": {
            "email": 'wrong@email.com',  # so email is wrong
            "password": self.user_password
        }
    }

    response = self.api_client.post('/api/v1/login/', data=post_data)

    self.assertHttpBadRequest(response)    # At this place I expect 400 status code

Test failure traceback 测试失败回溯

FAIL: test_login_unsuccessful_wrong_email (api.v1.tests.UsersLoginResourceTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/sultan/.virtualenvs/myenv/myproject/api/v1/tests.py", line 458, in test_login_unsuccessful_wrong_email
    self.assertHttpBadRequest(response)
  File "/Users/sultan/.virtualenvs/myenv/lib/python2.7/site-packages/django_tastypie-0.9.13_beta-py2.7.egg/tastypie/test.py", line 346, in assertHttpBadRequest
    return self.assertEqual(resp.status_code, 400)
AssertionError: 200 != 400

Thanks. 谢谢。

I think the best way to do that is first. 我认为最好的方法是首先。

create exception class: 创建异常类:

class HTTPError(Exception):
    def __init__(self, code, msg):
        Exception.__init__(self, msg)
        self.code = code
        self.msg = msg

create a custom page "error.html" that show only err_code err_msg and request or raison if you want. 创建一个自定义页面“ error.html”,该页面仅显示err_code err_msg并根据需要进行请求或存在。 "{{err_code}} {{err_msg}} {{request}}" “ {{err_code}} {{err_msg}} {{request}}”

dont miss to add the template in your settings.py in template 不要错过将模板添加到您的settings.py中的模板

create a middleware EXAMPLE: 创建一个中间件示例:

class JobMiddlewareException:
    def process_exception(self, request, e):
       if isinstance(e, HTTPError)
            render_to_response('error.html', {'err_code': e.code, 'err_msg': e.msg, 'request':request}, requestcontext(request))

EXAMPLE: and in your code when you need to raise error you do 示例:在您的代码中,当您需要引发错误时,您可以这样做

Raise HTTPError(404, 'Not Found. the page is not valid for user %s' % request.user) 引发HTTPError(404,“未找到。该页面对用户%s的%request.user无效”)

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

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