views:

695

answers:

2

Hello,

I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok.

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

I would be grateful for any help.

+8  A: 

Virtual hosts work by obeying the Host: header in the HTTP request.

Just read the headers of the request, and take action based on the value of the Host: header

elzapp
+4  A: 

For a simple HTTP web server, you can start with the 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,...

Modifying the example server to check the HTTP_HOST header, here is a simple app that responds, depending on the virtual host, with a different text. (Extending the example to use a configuration file is left 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()
gimel
You can't use the so called WSGI reference implementation for Python 3.0 as there is no such thing as WSGI for Python 3.0. The WSGI 1.0 specification only supports Python 2.X. As such, use anything which claims to satisfy WSGI specification and which works with Python 3.0 with extreme suspicion and understand that if a WSGI specification is ever released for Python 3.0, that any code you have that works with anything from before that point will possibly not work.
Graham Dumpleton