我正在按照此处的说明如何使用tastepie 登录到django以创建可用于登录到我的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)),
)