我是 Python 初学者。我想知道为什么它会抛出错误。 我收到一条错误消息说 TypeError: client_session() takes exactly 2 arguments (1 given) 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)
最佳答案
通常,这意味着您正在调用 client_session
作为一种未绑定(bind)的方法,只给它一个参数。你应该反省一下,看看 request
到底是什么你在 application()
中使用方法,也许它不是您期望的那样。
要确定它是什么,您可以随时添加调试打印输出点:
print "type: ", type(request)
print "methods: ", dir(request)
我希望您会看到请求是原始的 Request
werkzeug 给你的类(class)......
在这里,您要扩展 BaseRequest
werkzeug,并在 application()
你希望 werkzeug 知道你自己对 BaseRequest
的实现神奇地上课。但是如果你读过 python 的禅宗,你就会知道“显式优于隐式”,所以 python 永远不会神奇地做事,你必须告诉你的图书馆你做了某种改变。
所以看了werkzeug的文档后,可以发现其实是这样的:
The request object is created with the WSGI environment as first argument and will add itself to the WSGI environment as 'werkzeug.request' unless it’s created with populate_request set to False.
对于不知道werkzeug是什么,背后的设计逻辑是什么的人来说,可能不是很清楚。
但是一个简单的谷歌查找,显示了 BaseRequest 的用法示例:
- > http://werkzeug.pocoo.org/docs/exceptions/
- > https://github.com/mitsuhiko/werkzeug/blob/master/examples/i18nurls/application.py或
- > expand werkzeug useragent class
我只用谷歌搜索 from werkzeug.wrappers import BaseRequest`
现在,您应该能够猜出您的应用程序中要更改的内容。由于您只提供了应用程序的几个部分,因此我无法确切地告诉您更改的位置/内容。
关于python - Python2.7 中的错误正好需要 2 个参数(给定 1 个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16945074/