django add()只需要2个参数(给出3个)

时间:2013-02-17 22:56:29

标签: django

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) 
)

我曾经在stackoverflow上看过类似的问题,但是他们的解决方案无法帮助我并导致我遇到其他错误。所以我不明白当我只将用户和密码作为我的论据时,如何添加3个参数。有人能帮我吗。顺便说一下,我现在只使用以下方法测试添加功能:

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

1 个答案:

答案 0 :(得分:2)

实例(通常由self引用)被传递给类的每个实例方法。 This question更多地解释了自我和代表的含义。此外还有大量高质量的oop python教程。

我假设addUsersModel的方法(如果请纠正缩进,因为它非常重要)

在这种情况下,您的函数定义应如下所示:

def add(self, user1, password1):

此外,我认为这对django教程有很大的帮助。 Django创建了一个ORM,允许您在不编写任何sql的情况下与数据库进行交互!:)它非常易于使用。此外,django还有一个内置的User模型,可以提供开箱即用的身份验证和用户创建