For a simple HTTP server, you can start with help on WSGI :
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 managing WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications , ...
Having modified the server example to check the header HTTP_HOST, here is a simple application that responds, depending on the virtual host, with different text. (The extension of the example of using the configuration file remains as an exercise).
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...")
httpd.serve_forever()
source
share