4

我是 Python 的初学者。我想知道为什么它会引发错误。我收到一条错误消息,提示 TypeError:client_session() 恰好需要 2 个参数(给定 1 个) client_session 方法返回 SecureCookie 对象。

我这里有这段代码

from werkzeug.utils import cached_property
from werkzeug.contrib.securecookie import SecureCookie
from werkzeug.wrappers import BaseRequest, AcceptMixin, ETagRequestMixin,

class Request(BaseRequest):

 def client_session(self,SECRET_KEY1):
  data = self.cookies.get('session_data')
  print " SECRET_KEY " ,  SECRET_KEY1 
  if not data: 
   print "inside if data" 
   cookie = SecureCookie({"SECRET_KEY":    SECRET_KEY1},secret_key=SECRET_KEY1)
   cookie.serialize() 
   return cookie 
  print 'self.form[login.name] ', self.form['login.name'] 
  print 'data new' , data
  return SecureCookie.unserialize(data, SECRET_KEY1)


#and another 
class Application(object):
 def __init__(self):
  self.SECRET_KEY = os.urandom(20)

 def dispatch_request(self, request):
  return self.application(request)

 def application(self,request): 
  return request.client_session(self.SECRET_KEY).serialize() 


 # This is our externally-callable WSGI entry point
 def __call__(self, environ, start_response):
  """Invoke our WSGI application callable object""" 
  return self.wsgi_app(environ, start_response)
4

1 回答 1

2

通常,这意味着您将 调用client_session为未绑定的方法,只给它一个参数。你应该反省一下,看看request你在application()方法中使用的到底是什么,也许它不是你期望的那样。

要确定它是什么,您可以随时添加调试打印输出点:

print "type: ", type(request)
print "methods: ", dir(request)

我希望你会看到这个请求是Requestwerkzeug 给你的原始类......

在这里,您正在扩展BaseRequestwerkzeug,并且您期望 werkzeug神奇地application()知道您自己的类的实现。BaseRequest但是如果你读过python的禅宗,你就会知道“显式比隐式好”,所以python从不神奇地做东西,你必须告诉你的库你以某种方式做出了改变。

所以在阅读了werkzeug的文档之后,你会发现其实是这样的:

请求对象是使用 WSGI 环境作为第一个参数创建的,并且会将自身添加到 WSGI 环境中作为“werkzeug.request”,除非它是在 populate_request 设置为 False 的情况下创建的。

这对于不知道 werkzeug 是什么以及背后的设计逻辑是什么的人来说可能并不完全清楚。

但是一个简单的谷歌查找,显示了 BaseRequest 的使用示例:

我只搜索了 from werkzeug.wrappers import BaseRequest`

所以现在,您应该能够猜出您的应用程序中要更改的内容。由于您只提供了应用程序的几个部分,因此我无法确切地建议您在哪里/更改什么。

于 2013-06-05T16:29:20.010 回答