[英]Why I don't need to pass the required 2 positional arguments in WSGI-compliant apps?
這是我的班級:
class App(object):
def __init__(self, environ, start_response):
self.environ = environ
self.start_response = start_response
self.html = \
b"""
<html>
<head>
<title>Example App</title>
</head>
<body>
<h1>Example App is working!</h1>
</body>
</html>
"""
def __call__(self):
self.start_response("200 OK", [("Content-type", "text/html"),
('Content-Length', str(len(self.html)))])
return [self.html]
然后我運行它:
app = App()
我在Apache錯誤日志中得到了一個Type Error(顯然):
TypeError: __init__() missing 2 required positional arguments: 'environ' and 'start_response'\r
問題在於我看到的每個例子,他們只是沒有傳遞這些參數...... 例如 :
class Hello(object):
def __call__(self, environ, start_response):
start_response('200 OK', [('Content-type','text/plain')])
return ['Hello World!']
hello = Hello() # ?????????????
如果每個例子省略它們,我應該如何傳遞這些參數並避免類型錯誤?
你誤解了api doc。 你的__init__
方法可以采用你想要的任何參數(在你的App
示例中,除了self之外你可能不需要任何其他參數)。 然后你的__call__
方法是需要有environ和start_response參數的方法,而你不直接調用__call__
,WSGI服務器就是這樣。
這樣的東西就是你想要的......
class App(object):
def __init__(self, name):
self.name = name
self.html = \
b"""
<html>
<head>
<title>{name}</title>
</head>
<body>
<h1>{name} is working!</h1>
</body>
</html>
""".format(name=self.name)
def __call__(self, environ, start_response):
start_response("200 OK", [("Content-type", "text/html"),
('Content-Length', str(len(self.html)))])
return [self.html]
app = App('Example App')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.