0

I am following instructions from here How can I login to django using tastypie to create a UserResource that can be used to login to my django user.

However, I am running into HTTP 500 error when I run the code. I tried to debug it myself, but could not figure it out. I am not sure how I can troubleshoot the 500 error. Any thought you can give is appreciated.

Thanks!!

My code is as below:

#####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)),
     )
Community
  • 1
  • 1
Neo_32
  • 225
  • 4
  • 13
  • nothing in the logs on your host? – KevinDTimm Jul 11 '13 at 21:58
  • Well, -1. First reformat your code sample - in Python indents _do_ matter. – Tadeck Jul 11 '13 at 22:05
  • @Tadeck I was manually formatting the code here as the cut-paste messed it up each time. Now, it should be fine – Neo_32 Jul 11 '13 at 23:24
  • @KevinDTimm my Apache log folder /private/var/log/apache2/ is empty. I am quite new to this, so apologies if I am looking at the incorrect place – Neo_32 Jul 11 '13 at 23:26
  • does it work if u comment all print statements? – vikingosegundo Jul 11 '13 at 23:33
  • @vikingosegundo I removed the print statement and tried. Same problem... Previously I have used the print statement in development environment though without problems. Thanks! – Neo_32 Jul 11 '13 at 23:39
  • as the development server does not use WSGI it is not a problem there. after removing the prints did u restart apache? – vikingosegundo Jul 11 '13 at 23:40
  • @vikingosegundo I meant I am still on development server. Still same error : [11/Jul/2013 18:43:34] "POST /api/user/login HTTP/1.1" 500 62391 – Neo_32 Jul 11 '13 at 23:44
  • So why are you looking for error in apache's logs?? – vikingosegundo Jul 11 '13 at 23:44
  • you are aware, that there is data send back to you? 62391 bytes. Probably a django error page. what does that say? – vikingosegundo Jul 11 '13 at 23:55
  • @vikingosegundo I've seen discussions that ask me to look into apache log for Internal Server error . For ex, https://groups.google.com/forum/#!topic/django-users/Zj9AO6YQrg4 – Neo_32 Jul 11 '13 at 23:57
  • That makes only sense, if you are deploying with apache. – vikingosegundo Jul 11 '13 at 23:58
  • and mod_python is quite uncommon today. usually mod_wsgi is recommend. – vikingosegundo Jul 11 '13 at 23:59
  • 1
    @vikingosegundo Thanks, that helped to fix it. I was just printing the response object, and not the content You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/api/user/login/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings – Neo_32 Jul 12 '13 at 00:04
  • @vikingosegundo Thanks for all the additional feedback. I am new to this, so appreciate it. – Neo_32 Jul 12 '13 at 00:07
  • sure, the slash, i just saw it. – vikingosegundo Jul 12 '13 at 00:08

1 Answers1

2

When deploying via WSGI using print statement can raise IOErrors. Try to comment them out or redirect the output.

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


Append a slash

url = 'http://127.0.0.1:8000/api/user/login/'
Community
  • 1
  • 1
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • Well, instead of using `print` statement/function, OP should rather rely on `logging` module. More about `print` vs. `logging` is here: http://stackoverflow.com/a/17553247/548696 – Tadeck Jul 12 '13 at 00:22