为了教育目的,我使用HTTPServer和来自http.server的BaseHTTPRequestHandler实现了一个简单的类似于烧瓶的框架。
我已经发现,我可以用来自HTTPServer的WSGIServer替换wsgiref.simple_server,代码无需任何其他修改就可以运行。
我的实现的run方法工作如下:
def run(self, host: str, port: int):
web_server = WSGIServer((host, port), Request)
try:
print("Server is running at port", port)
web_server.serve_forever()
except KeyboardInterrupt:
web_server.server_close()
print("Server stopped")当我读到古尼科恩的文档时,我发现古尼科恩希望有这样的功能:
def app(environ, start_response):
"""Simplest possible application object"""
data = b'Hello, World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])wsgiref.simple_server.make_server接受上述函数并实例化一个WSGIServer并调用serve_forever()方法,就像我在实现中所做的那样。
我尝试过从thr WSGIServer中从WSGIServer.get_app()方法返回应用程序,但它没有返回。
我想知道如何使用终端的WSGIServer类运行。
发布于 2022-05-21 17:35:43
如果您有一个类似框架的应用程序,那么最好的服务方法是将框架入口点包装为一个可调用的类,并将其作为一个整体传递给gunicorn。
以下是服务员web服务器和Gunicorn web服务器的示例,如何使其服务于相同的WSGI应用程序
# Router.__call__() is the entry point for the request processing
def setup_app() -> Router:
context.init_console_logging()
app = create_app(production=True, oracle_context=context)
check_oracle_db()
check_web_db()
from tradingstrategy import __version__
from .api import version as api_version
logger.info("Server version is %s, client library version %s", api_version, __version__)
return app
# Waitress main entry point
def main():
app = setup_app()
port = int(os.environ.get("BACKEND_PORT", 3456))
scheme = os.environ.get("WSGI_SCHEME", "http")
logger.info("Matilda backend server starting at port %d", port)
serve(app,
host='127.0.0.1',
trusted_proxy="127.0.0.1",
threads=32,
port=port,
trusted_proxy_headers="forwarded",
url_scheme=scheme,
url_prefix='/api')
def gunicorn_entry_point() -> Router:
"""Gunicorn calls this function for every worker process.
To run::
gunicorn --bind 127.0.0.1:3456 --workers 1 --threads 1 "backend.server.server:gunicorn_entry_point()"
"""
app = setup_app()
return app见WSGI应用程序的金字塔路由器实现。如果您不确定如何处理WSGI框架,这是一个很好的例子。
class Router:
# ...
def __call__(self, environ, start_response):
"""
Accept ``environ`` and ``start_response``; create a
:term:`request` and route the request to a :app:`Pyramid`
view based on introspection of :term:`view configuration`
within the application registry; call ``start_response`` and
return an iterable.
"""
response = self.execution_policy(environ, self)
return response(environ, start_response)https://stackoverflow.com/questions/72331463
复制相似问题