我在python3中编写了一个相当简单的http Web服务器. Web服务器需要很简单 – 只能从配置文件等基本读取.我只使用标准库,现在它工作得相当好.
这个项目只有一个要求,我无法自己实现 – 虚拟主机.我需要至少有两个虚拟主机,在配置文件中定义.问题是,我找不到如何在python中实现它们的方法.有没有人有任何指南,文章,也许一些简单的实现如何做到这一点?
我将不胜感激任何帮助.
解决方法:
对于简单的HTTP Web服务器,您可以从WSGI reference implementation开始:
wsgiref is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications,…
修改示例服务器以检查HTTP_HOST标头,这是一个简单的应用程序,它根据虚拟主机使用不同的文本进行响应. (扩展示例以使用配置文件留作练习).
import wsgiref
from wsgiref.simple_server import make_server
def my_app(environ,start_response):
from io import StringIO
stdout = StringIO()
host = environ["HTTP_HOST"].split(":")[0]
if host == "127.0.0.1":
print("This is virtual host 1", file=stdout)
elif host == "localhost":
print("This is virtual host 2", file=stdout)
else:
print("Unknown virtual host", file=stdout)
print("Hello world!", file=stdout)
print(file=stdout)
start_response(b"200 OK", [(b'Content-Type',b'text/plain; charset=utf-8')])
return [stdout.getvalue().encode("utf-8")]
def test1():
httpd = make_server('', 8000, my_app)
print("Serving HTTP on port 8000...")
# Respond to requests until process is killed
httpd.serve_forever()