2013-06-05 64 views
3

我是Python的初學者。我想知道它爲什麼會拋出一個錯誤。 我得到一個錯誤,指出TypeError:client_session()只需要2個參數(給出1) client_session方法返回SecureCookie對象。Python2.7中的錯誤只需要2個參數(1給出)

我這裏有

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

我認爲'application()'方法中的'request'應該大寫?此外,這看起來不像python n00b代碼(做得好)。無論我看到這個錯誤,我看到它只有1關閉(需要2,1給出),我通常會發現它與'自我' – TehTris

+0

我曾嘗試使用請求更改r大寫,但它仍然給出相同錯誤 – user2456373

回答

1

這個代碼通常情況下,這意味着你調用client_session爲不受約束的方法,給它只有一個參數。你應該反思一下,看看你在application()方法中使用的是什麼,也許這不是你期望的。

要知道它是什麼,你可以隨時添加調試打印點:

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

,我希望你會看到該請求是原始Request類WERKZEUG給你...

在這裏,你擴展了werkzeug的BaseRequest,並且在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的用法示例:

我只能從werkzeug.wrappers一派進口BaseRequest`

S o現在,您應該能夠猜出您的應用程序中要更改什麼。由於您只給出了應用程序的幾個部分,因此我無法告知您具體在哪裏/要更改哪些內容。

+0

我曾嘗試使用Request將r更改爲大寫,但它仍然給出了與我的意思相同的錯誤 – user2456373

+0

。更改變量的名稱不會改變行爲。嘗試添加'print type(request)'和'print dir(request)',這樣你就可以獲得'request'參數的類型名稱和所有方法列表。 – zmo

+0

閱讀[documentation](http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.BaseRequest)它看起來應該給Request對象以wsgi應用程序調用。我從來沒有使用過werkzeug,所以我不知道如何/在哪裏...... – zmo

相關問題