0

models.py

#!/usr/bin/env python
from django.db import models
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
import json
import sys
import tempfile
import traceback
import re
import psycopg2

SUCCESS               =   1 
ERR_BAD_CREDENTIALS   =  -1  
ERR_USER_EXISTS       =  -2  
ERR_BAD_USERNAME      =  -3  
ERR_BAD_PASSWORD      =  -4

class UsersModel(models.Model):
    user = models.CharField(primary_key=True, max_length=128)
    password = models.CharField(max_length=128)
    count = models.IntegerField()       

    def login(user1, password1):
        try:
            con = psycopg2.connect(database='test', user='jeffrey') 
            cur = con.cursor()
            cur.execute('SELECT user FROM UsersModel WHERE user1=user AND password1=password;')
            rows = cur.fetchall()
            print rows
            if len(rows) == 1:
                #on success update the count and return the count
                cur.execute('UPDATE UsersModel SET count=count+1 WHERE user1=user AND password1=password;')
                cur.execute('SELECT count FROM UsersModel WHERE user1=user AND password1=password;')
                return cur.fetchone()[0]
            else:
                return ERR_BAD_CREDENTIALS

        except psycopg2.DatabaseError, e:
            print 'Error %s' % e    
        sys.exit(1)


    def add(user1, password1):
        try:
            if user1=='' or len(user1)>128:
                return ERR_BAD_USERNAME
            elif len(password1)>128:
                return ERR_BAD_PASSWORD 

            con = psycopg2.connect(database='test', user='jeffrey') 
            cur = con.cursor()
            cur.execute('SELECT user FROM login_UsersModel WHERE user1=user;')
            rows = cur.fetchall()
            if len(row) == 1:
                return ERR_USER_EXIST
            else:
                cur.execute('INSERT INTO login_UsersModel VALUES (user1, password1, 1);')
                cur.execute('SELECT count FROM login_UsersModel WHERE user1=user AND password1=password;')
                return cur.fetchone()[0]

        except psycopg2.DatabaseError, e:
            print 'Error %s' % e    
        sys.exit(1)

def TESTAPI_resetFixture(request):
        con = psycopg2.connect(database='test', user='jeffrey') 
        cur = con.cursor()
        cur.execute('DELETE FROM login_UsersModel')
        return SUCCESS

views.py

from django.shortcuts import render
from django.http import HttpResponse
from login.models import UsersModel
from django.utils import simplejson
import os
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def loginx(request):
    data = simplejson.loads(request.body)
    name = data['user']
    pw = data['password']
    x = UsersModel()
    code = x.login(name, pw)
    if code > 0:
        response_data = {'errCode':1, 'count':code}
        return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
    else:
        response_data = {'errCode':code}
        return HttpResponse(simplejson.dumps(response_data), content_type="application/json")


@csrf_exempt
def addx(request):
    data = simplejson.loads(request.body)
    name = data['user']
    pw = data['password']
    x = UsersModel()
    code = x.add(name, pw)
    if code > 0:
        response_data = {'errCode':1, 'count':code}
        return HttpResponse(simplejson.dumps(response_data), content_type="application/json")
    else:
        response_data = {'errCode':code}
        return HttpResponse(simplejson.dumps(response_data), content_type="application/json")

@csrf_exempt
def TESTAPI_resetFixturex(request):
    x = UsersModel()
    code = x.TESTAPI_resetFixture()
    response_data = {'errCode': code}
    return HttpResponse(simplejson.dumps(response_data), content_type="application/json")

@csrf_exempt    
def unitTests(request):
os.system("make func_tests TEST_SERVER=localhost:8000")
return

url.py

from django.conf.urls import patterns, include, url
from django.contrib import admin
from login.views import loginx
from login.views import addx
from login.views import TESTAPI_resetFixturex

admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    #url(r'^admin/', include(admin.site.urls)),rs
    url(r'^users/login', loginx),
    url(r'^users/add', addx),
    url(r'^TESTAPI/resetFixture', TESTAPI_resetFixturex)
    #url(r'^TESTAPI/unitTests', unitTests) 
)

ive seen similar questions been asked before on stackoverflow, but their solutions were not able to help me and lead me to other errors. so yea i dont understand how 3 arguments can be given to add when i only put users and password as my argument in view. can someone help me. btw i am only testing the add function right now in view using:

curl -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"user":"test", "password":"test"}' localhost:8000/users/add -o test.html

LemonPie
  • 806
  • 1
  • 11
  • 23
  • 1
    You might want to fix the indentation of your code samples. It looks like you lost a level at a few points. – Ned Batchelder Feb 17 '13 at 22:59
  • right if there is an indentation problem here ignore it please. i copy and pasted the code here and im new to putting code on stackoverflow so it might look bad here. but the indentation on my actual code is fine. ive had indentation errors before and i fixed them, now its this. – LemonPie Feb 18 '13 at 00:10
  • if your code is indented poorly, how are we supposed to know what it's supposed to look like? – Ned Batchelder Feb 18 '13 at 01:12
  • alite i believe i have fixed the indentation – LemonPie Feb 18 '13 at 05:05

1 Answers1

2

The instance (conventionally referenced by self) is passed to each instance method of a class. This question explains some more about what self is and repreesnts. In addition there are a great number of high quality oop python tutorials.

I am assuming add is method of UsersModel (if it is please correct indentation, as it matters immensely`)

in which case your function definition should look like:

def add(self, user1, password1):

Additionally, i think it would be a great help to do the django tutorial. Django has created an ORM to allow you to interact with a database without writing any sql!:) It is extremely easy to use. Also django has a built in User model that provides authentication and user creation out of the box

Community
  • 1
  • 1
dm03514
  • 54,664
  • 18
  • 108
  • 145
  • yes sorry about about that, its my first time posting code here. so formating it is kinda wierd when i manually post it in. i have seen the self solution posted before. i tried that. when i run that test, i get "A server error occurred. Please contact the administrator." so yea it didnt help much. – LemonPie Feb 17 '13 at 23:05
  • @Jeff is `debug=True` in your settings.py? If it is it will give you a nice traceback instead of general error message – dm03514 Feb 17 '13 at 23:06
  • debug=True. it used to give trace backs. you know the problem with add taking 2 arguments but was given 3. it had a traceback via the html file it outputed. but the problem is once i did self, an error occured. – LemonPie Feb 17 '13 at 23:15