Python3 Http Web Server: Virtual Hosts

I am writing a fairly simple http web server in python3. The web server should be simple - only basic reading from configuration files, etc. I use only standard libraries, and at the moment it works pretty fine.

There is only one requirement for this project that I cannot implement on my own - virtual hosts. I need to have at least two virtual hosts defined in the configuration files. The problem is that I cannot find a way how to implement them in python. Does anyone have manuals, articles, maybe a simple implementation, how can this be done?

I would be grateful for any help.

+3
source share
2 answers

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...")

    # Respond to requests until process is killed
    httpd.serve_forever()
+5
source

, Host: HTTP-.

, Host:

+10

Source: https://habr.com/ru/post/1706962/


All Articles