wayfare wayfare - 11 months ago 354
Python Question

How to serve a static webpage from falcon application?

I am new to python and hence falcon. I started developing a RESTful API and falcon so far is great for it. There is some other requirement to serve a static web page and I dont want to write an app or spawn a server for that.

Is it possible from the falcon app to serve the static web page?

Answer Source

First and most important, I have to say that you don't want to do that. What you should do is have a nginx server on top of your Falcon app, and serve any static file directly from nginx (and redirect the API calls to Falcon).

This being said, you can serve static files easily from Falcon. This is the code you are looking for:

import falcon

class StaticResource(object):
    def on_get(self, req, resp):
        resp.status = falcon.HTTP_200
        resp.content_type = 'text/html'
        with open('index.html', 'r') as f:
            resp.body = f.read()

app = falcon.API()
app.add_route('/', StaticResource())

You may want to set the file name as a parameter in the url, and get it in your resource, so your static resource can serve any requested file from a directory.