GAE中关键字参数的多个值

时间:2013-01-10 03:40:00

标签: python google-app-engine

我遇到了Google App Engine上的Python错误(localhost) 我试图使用Model.get_by_id()函数,但我遇到了一个多关键字参数错误,正如我在下面的代码中的注释中指出的那样。从底部开始的第3行

我确定这是一个简单的错误,我只是看不到它。

提前致谢!

'''
Created on 09/01/2013

@author: jonathan
'''
import webapp2_extras.security as security
from google.appengine.ext import db
import hashlib
import datetime

class User(db.Model):
    username = db.StringProperty(required=True)
    passhash = db.StringProperty(required=True)
    email = db.EmailProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    authtoken = db.StringProperty(required=True)

    def __init__(self, username, password, email=None):
        authtoken = security.generate_random_string(entropy=256)
        passhash = security.generate_password_hash(password)
        super(User, self).__init__(username=username,
                                   passhash=passhash,
                                   email=email,
                                   authtoken=authtoken)

    def __str__(self):
        return self.username

    def check_password(self, password):
        return security.check_password_hash(password, self.passhash)

    @classmethod
    def check_unique_user(cls, username):
        return not bool(cls.all().filter('username =', username).count())

    def get_session_token(self, dt=None):
        ID = self.key().id()
        if not dt:
            dt = datetime.datetime.now().strftime("%d%m%y%H%M%S")
        hashstring = "{0}${1}${2}".format(ID, dt, self.authtoken)
        return '{0}${1}${2}'.format(ID, dt, hashlib.sha256(hashstring).hexdigest())

    @classmethod
    def check_session_token(cls, session_token):
        if session_token:
            ID, dt = session_token.split("$")[:2]
            if ID.isdigit():
                user = cls.get_by_id(ids=int(ID))  # Raises TypeError: __init__() got multiple values for keyword argument 'username'
                if user and user.check_session_token(session_token, dt):
                    return user

我的其余代码:

common.py#这个还在进行中......

'''
Created on 06/01/2013

@author: jonathan
'''
import os
import webapp2
import jinja2

template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
                               autoescape=True)

class Handler(webapp2.RedirectHandler):
    def write(self, *args, **kwargs):
        self.response.out.write(*args, **kwargs)

    def render_str(self, template, **params):
        templated_html = jinja_env.get_template(template)
        return templated_html.render(params)

    def render(self, template, **kwargs):
        self.write(self.render_str(template, **kwargs))

if os.environ['SERVER_SOFTWARE'].startswith('Development'):
    app_scheme = 'http'
else:
    app_scheme = 'https'

registration.py

'''
Created on 07/01/2013

@author: jonathan
'''
import common
from webapp2_extras.routes import RedirectRoute
import re
from models.user import User

def getroutes():
    return [RedirectRoute(r'/signup', handler=SignupPage, name='signup', schemes=common.app_scheme, strict_slash=True),
            (RedirectRoute(r'/welcome', handler=WelcomePage, name='welcome', strict_slash=True)),
            (RedirectRoute(r"/login", handler=LoginPage, name="login", schemes=common.app_scheme, strict_slash=True)),
            (RedirectRoute(r'/logout', handler=LogoutPage, name="logout", strict_slash=True))]

username_pattern = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
password_pattern = re.compile(r"^.{3,20}$")
email_pattern = re.compile("^[\S]+@[\S]+\.[\S]+$")
def valid_username(username):
    return username_pattern.match(username)

def valid_password(password):
    return password_pattern.match(password)

def verify_password(password, verify):
    return password == verify

def valid_email(email):
    return email_pattern.match(email)


class SignupPage(common.Handler):
    def render(self, **kwargs):
        super(SignupPage, self).render("signup.html", **kwargs)

    def get(self):
        session_token = self.request.cookies.get("session")
        if User.check_session_token(session_token):
            self.redirect_to("welcome")
        self.render()

    def post(self):
        v_username = v_password = v_email = False
        username = self.request.get("username")
        password = self.request.get("password")
        verify = self.request.get("verify")
        email = self.request.get("email")
        params = {'username_error':'',
                  'password_error':'',
                  'verify_error':'',
                  'email_error':'',
                  'username':username,
                  'email':email}

        if valid_username(username):
            if User.check_unique_user(username):
                v_username = True
            else:
                params['username_error'] = "Username taken"
        else:
            params['username_error'] = "Invalid username"


        if valid_password(password):
            if verify_password(password, verify):
                v_password = True
            else:
                params['verify_error'] = "Passwords do not match"
        else:
            params['password_error'] = "Invalid password"

        if valid_email(email):
            v_email = True
        else:
            params['email_error'] = "Invalid email"

        if v_username and v_password:
            if v_email:
                user = User(username=username,
                            password=password,
                            email=email)
            else:
                user = User(username=username,
                            password=password)
            user.put()
            session_token = user.get_session_token()
            self.response.set_cookie("session", session_token)
            self.redirect(r'/welcome')
        else:
            self.render(**params)


class WelcomePage(common.Handler):
    def get(self):
        session_token = self.request.cookies.get("session")
        user = User.check_session_token(session_token)
        if not user:
            self.response.delete_cookie('session')
            self.redirect_to("signup")
        else:
            self.render("welcome.html", {'user':user})



class LoginPage(common.Handler):
    def get(self):
        session_token = self.request.cookies.get("session")
        user = User.check_session_token(session_token)
        if not user:
            self.response.delete_cookie('session')
            self.redirect_to("signup")
        else:
            self.render("login.html")

    def post(self):
        username = self.request.get('username')
        password = self.request.get('password')
        remember = self.request.get('remember')
        params = {}
        user = None

        if valid_username(username):
            user = User.all().filter('username =', username).get()
            if not user:
                params['username_error'] = "Can't find username"
        else:
            params['username_error'] = "Invalid username"

        if user and user.check_password(password):
            self.redirect_to('welcome')
        else:
            params['password_error'] = "Mismatched password"
            self.render('login.html', params)


class LogoutPage(common.Handler):
    def get(self):
        self.response.delete_cookie("session")
        self.redirect(r'/signup')

1 个答案:

答案 0 :(得分:1)

您的数据存储区中可能有一个User用户,其中“username”不是StringProperty,而是列表。当db库获取实体并对其进行解析时,它无法将列表转换为StringProperty

我建议使用数据存储区查看器并检查您的实体实际上是否具有用户名的有效字符串。

编辑:再次查看代码。覆盖 init 是一个非常糟糕的主意。 User类不是典型的类,而是它是用于生成User实例的元类。即,您的用户实例实际上不是您的用户类的实例。我怀疑你在那里遇到了一个问题。