传递给函数时,参数从字典中消失

时间:2010-07-09 17:34:32

标签: python django session dictionary

在我的函数中,我从会话中读取用户的数据并将它们存储在字典中。接下来我将它从registration.backend发送到'register'函数,但函数以某种方式得到它为空并且抛出了KeyError。我的数据在哪里?函数调用'register'函数的代码:

data = request.session['temp_data']
email = data['email']

logging.debug(email)

password1 = data['password1']
userdata = {'email': email, 'password1': password1}

logging.debug(userdata)

backend = request.session['backend']

logging.debug(backend)

user = backend.register(userdata)

寄存器功能(整个来源:http://bitbucket.org/ubernostrum/django-registration/src/tip/registration/backends/default/init.py):

class DefaultBackend(object):
    def register(self, request, **kwargs):
        logging.debug("backend.register")
        logging.debug(kwargs)

        username, email, password = kwargs['email'], kwargs['email'], kwargs['password1']

调用它们后调试:

2010-07-09 19:24:35,020 DEBUG my@email.com
2010-07-09 19:24:35,020 DEBUG {'password1': u'a', 'email': u'my@email.com'}
2010-07-09 19:24:35,020 DEBUG <registration.backends.default.DefaultBackend object at 0x15c6090>
2010-07-09 19:24:35,021 DEBUG backend.register
2010-07-09 19:24:35,021 DEBUG {}

为什么数据可能丢失?我做错了吗?

@edit for Silent-Ghost

 register() takes exactly 2 arguments (3 given)

 112.  backend = request.session['backend']
 113. logging.debug(backend)
 114. user = backend.register(request, userdata) 

3 个答案:

答案 0 :(得分:3)

根据方法的签名判断:

  1. 您需要解压缩字典
  2. 您需要传递相关的request变量
  3. 这样的事情:

    backend.register(request, **userdata)
    

    假设registerbackend实例上的方法。

答案 1 :(得分:3)

无需在**方法中混淆register。你想要做的只是将字典传递给register方法:

user = backend.register( request, userdata ) # you need to pass request as definition says

def register( self, request, userdata ): # note lack of **
    logging.debug("backend.register")
    logging.debug( userdata ) # should work as expected

    username, email, password = userdata['email'], userdata['email'], userdata['password1']

答案 2 :(得分:0)

这完美的工作

class Logging():
    def debug(self,f):
        print f
class DefaultBackend(object):
    def register(self, request, **kwargs):
        logging.debug("backend.register")
        logging.debug(kwargs)

        username, email, password = kwargs['email'], kwargs['email'], kwargs['password1']

class Request:
    def __init__(self):
        self.session = {}
request = Request()
logging=Logging()
request.session['temp_data']={'password1': u'a', 'email': u'my@email.com'}
request.session['backend']=DefaultBackend()



data = request.session['temp_data']
email = data['email']

logging.debug(email)

password1 = data['password1']
userdata = {'email': email, 'password1': password1}

logging.debug(userdata)

backend = request.session['backend']

logging.debug(backend)

user = backend.register(request,**userdata)