我按照這裏的說明How can I login to django using tastypie創建一個UserResource,可以用來登錄到我的django用戶。POST 500上的HTTP 500錯誤
但是,我運行代碼時遇到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' :'[email protected]', '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)),
)
什麼? – KevinDTimm
恩,-1。首先重新格式化您的代碼示例 - 在Python中縮進_do_問題。 – Tadeck
@Tadeck我在這裏手動設置代碼的格式,因爲每次剪貼都搞砸了。現在,應該沒事了 –