Creating a Lightweight Application Server Using Werkzeug

When it came time to put up the second phase of the Python tutorial I realized that Werkzeug does not support any kind of hostname binding. I've also mentioned that running these applications on port 80 is problematic due to the fact that root privileges are required to access those ports. Werkzeug is WSGI compatible so installing Apache would be the smartest choice in a production environment but for the sake of a learning exercise I wanted to explore other possibilities. I had already done some research on how to use port 80 so that's where I started.

Running an Application on Port 80

After running a few searches there were three most recommended solutions.

More recent versions of Linux have a method for giving an executable the CAP_NET_BIND_SERVICE capability which allows an application to open a lower port using setcap.

Use Python's os.setuid which allows the application to switch to a user with lower privileges after opening the port.

Unfortunately the first suggestion doesn't work with scripts. From my limited research there appears to be a way to convert Python scripts to executables but I didn't feel like going that route for now. I did give some consideration to the second choice but I was concerned that I wouldn't be able to implement it properly without a deeper understanding of the Linux OS. The third solution however seemed to fit my needs perfectly. There are some concerns with this approach since it allows any application to intercept this traffic but since I won't be running any other applications on this server it isn't a huge concern. The command to reroute the port traffic was relatively simple.

This also turned out to be an answer for another problem I had when I thought I would open up multiple ports using Werkzeug but the run_simple method blocks and I wasn't too keen on getting into multithreading just yet. I decided to just have the server run on a single port and assume that any traffic it was intended to receive had already been configured to reroute to it's single port.

Hostname Binding

Before I dove into how I wanted the server to function I started off with designing a configuration file. As you may have guessed by now I'm pretty fond of JSON and unsurprisingly I decided to use it for the syntax.

As I mentioned earlier, the server will be running on a single port that's specified at provider.port. The 8000 port seemed like a good choice so I stuck with that. The configuration file supports multiple applications and rather than using a file system location simply specifies the Python module and class to be used. There is also an optional settings value which allows us to provide application specific information. I opted to set the database connection string here in order to isolate my configuration to a single file. Each binding has a port and hostname property. I only allowed for full wildcard bindings because at this point I don't need partial wildcards. However a few tweaks of the server code would easily resolve this. Speaking of which, let's take a look at the server.

/server.py

These are all the imports we'll need. The json class will allow us to easily parse our configuration file and the Werkzeug Request object will allow us to parse the hostname and port number of the request. We'll also need the Response object in case the request doesn't resolve to anything and we need to toss the client an error message. In order to load our application using the module and class names we'll be using the importlib class.

defloadApplication(application):ifnot'name'in application:print'Name must be specified for all applications'return None

The application parameter will simply be the resulting dict from the parsed configuration JSON. We have a few lines of code that ensure we have the required properties name, moduleName and className defined and finally we default our settings to an empty dictionary.

Once we have all the necessary information we can attempt to import the module and then grab the application class. Passing the appropriate error messages back to the console should any steps in this process fail. The final steps are to pass the settings value to the class constructor and return the instance.

Our loadConfig method will be responsible for opening the configuration file and returning a dictionary that's easier to work with. Should any of this fail the method will return our empty configuration result.

Once we've parsed the file it's time to iterate through all the applications entries. We first make a call to our previously defined loadApplication method and determine if the application loaded successfully. If not our continue statement will skipp the rest of the loop and move on to the next application.

We now can start iterating through our application's bindings and creating a list of them in our result. Each port will have a single binding with multiple host entries underneath making it easy to detect duplicate bindings. If all goes well we can add the hostname entry populated with our application dictionary and use it's name as a key for our applications property in the result.

if 'provider' in config:
result['provider'] = config['provider']

return result

Finally all we have to do is set the provider and return our result. We're almost done!

This class serves as a proxy for our applications by accepting all requests and then mapping them to the appropriate binding. If no binding is found we respond to the client with an error message otherwise we make a call to the app the same way Werkzeug would.

Conclusion

While this certainly isn't intended to replace a web server it is a simpler approach for development and light production environments that don't require SSL, cache control or a number of other features offered by a typical web server. Using the changes to the Passport project I explained in the previous article I was able to install the two phases of the Passport application to a new virtual environment and serve them both using the configuration file mentioned at the beginning of this article.