Using Flask as a quick local Dev Web Server

I was working on a small stateless JavaScript web app for work and trying to get an example from the web to run on my local computer. Unfortunately though, Chrome was validly complaining about my trying to load local js libraries from my file system rather than using http or https.

After discovering what was causing my error I realized that the solution to my error would be to throw my app onto a web-server and access it through http. My initial thought was to create a quick vm or simply throw the script on my own personal web server. My boss though thought up and even quicker solution that I had simply never considered.

He suggested I simply use Flask to serve up the directory. Strangely, I had never actually thought of using Flask like this but Flask is perfect for this because it comes with a simple Python Web Server designed for developing and debugging Flask applications.

After some quick googling, here is the flask script that I was able to throw together:

from flask import Flask, request

app = Flask(__name__, static_url_path='')

@app.route('/')
def root():
    return app.send_static_file('index.html')

The key to getting this to work is to leverage the fact that if you create a folder named static in your apps directory, Flask will server that directory with the above code.

To start the server I simply typed into the console:

$ export FLASK_APP=hello.py
$ flask run

Or if on Windows change export to set.

Now, all I had to do was head over to: http://127.0.0.1:5000/in my browser.

And that is it! Now I have a simple webserver on my local computer serving a static folder and don't need to do anything weighty like installing a desktop dev server or throwing a VM up in the cloud.


Comments

comments powered by Disqus