Search code examples
pythonhostingpyramid

Hosting Pyramid webapps under subpaths


We have a hosting setup where we have one top level domain, and we host web applications under subpaths. For instance:

  /projects -> Plone
  /interal -> Tomcat
  etc

In this scenario we need a way to tell the web application at the back end what its base path is, so that it can correctly generate links to its views and static content. For the examples above this is fine.

We have just started using Pyramid, served by Waitress, but so far we've not figure out how to do this. Is there a clean way to configure this base path in Waitress, or is there a more flexible application server that we can use that will support Pyramid?


Solution

  • Everything in WSGI is relative to the current request. You just have to have your environ setup properly (usually by your WSGI server).

    For example your web application will know it is mounted at subpath /projects if request.environ['SCRIPT_NAME'] == '/projects'. If you want your application to be agnostic to its mount point, you can simply code it up as if it serves a view at /foo/bar. Then you mount your application on /projects via some middleware which can mutate the environ properly (mod_wsgi and some other servers should be able to do this for you automatically). Now when the incoming URL is /projects/foo/bar the environ['SCRIPT_NAME'] == '/projects' and environ['PATH_INFO'] == '/foo/bar', and your app can focus on the relative path.

    In Pyramid this would boil down to an extra step in your ini where you add the prefix middleware to your WSGI stack. The middleware handles mutating the PATH_INFO and SCRIPT_NAME keys in the environ for you.

    [app:myapp]
    use = egg:myapp
    
    # ...
    
    [filter:proxy-prefix]
    use = egg:PasteDeploy#prefix
    prefix = /projects
    
    [pipeline:main]
    pipeline =
        proxy-prefix
        myapp