我一直在使用版本Django
的{{1}}和Tastypie
处理API,而在测试用例中,当我希望{400}获得django-tastypie==0.9.13-beta
响应时,它总会返回bad request
200回复。什么可能导致这个问题?
http ok
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'])
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
感谢。
答案 0 :(得分:1)
我认为最好的方法是首先。
创建异常类:
class HTTPError(Exception):
def __init__(self, code, msg):
Exception.__init__(self, msg)
self.code = code
self.msg = msg
创建一个自定义页面“error.html”,如果需要,只显示err_code err_msg和request或raison。 “{{err_code}} {{err_msg}} {{request}}”
不要错过在模板的settings.py中添加模板
创建一个中间件 实施例:
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))
实施例: 当你需要提出错误时,在你的代码中
提出HTTPError(404,'未找到。该页面对用户%s'无效'% request.user)