我按照How can I login to django using tastypie的说明创建了一个可用于登录我的django用户的UserResource。
但是,运行代码时遇到HTTP 500错误。我自己尝试调试它,但无法弄明白。我不确定如何解决500错误。您可以给予任何想法。
谢谢!
我的代码如下:
#####api.py
from registration.views import register
from tastypie.resources import ModelResource
from tastypie.constants import ALL
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from tastypie.http import HttpUnauthorized, HttpForbidden
from django.conf.urls.defaults import url
from tastypie.utils import trailing_slash
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
fields = ['first_name', 'last_name', 'email']
allowed_methods = ['get', 'post']
resource_name = 'user'
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/login%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('login'), name="api_login"),
url(r'^(?P<resource_name>%s)/logout%s$' %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('logout'), name='api_logout'),
]
def login(self, request, **kwargs):
self.method_check(request, allowed=['post'])
print "reached login auth"
data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
print "reached login auth"
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpForbidden )
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized )
def logout(self, request, **kwargs):
self.method_check(request, allowed=['get'])
if request.user and request.user.is_authenticated():
logout(request)
return self.create_response(request, { 'success': True })
else:
return self.create_response(request, { 'success': False }, HttpUnauthorized)
########test_login.py
import requests
import json
from urllib2 import urlopen
import datetime
import simplejson
url = 'http://127.0.0.1:8000/api/user/login'
data = {'username' :'sv3@gmail.com', 'password' : 'pass'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
print json.dumps(data)
r = requests.post(url, data=json.dumps(data), headers=headers)
print r
#####urls.py
from userdetails.api import UserResource
user_resource = UserResource()
urlpatterns = patterns('',
......
(r'^api/', include(user_resource.urls)),
)
答案 0 :(得分:2)
使用print语句通过WSGI进行部署时可能会引发IOErrors。尝试将它们注释掉或重定向输出。
In Django, how do I allow print statements to work with Apache WSGI?
http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html
附加斜杠
url = 'http://127.0.0.1:8000/api/user/login/'