[PYTHON] Use Flask as the next step for SimpleHTTPServer

If you just want to statically deliver HTML, CSS, JS, etc. when you want to make a small prototype of a web application for experimentation at hand

python -mSimpleHTTPServer

It seems that the name recognition has risen considerably because it was fun, but when I thought "Oh, I want to save a little data", static distribution alone is not enough. (Excluding the power technique of stacking on the GET parameter and leaving it in the log)

So, because it became such a situation, I implemented it with Flask in about 1 pomodoro (25 minutes), but when I saw Facebook, there was a person who said that I would use Socket in a similar situation, so this is on the blog I thought it should be written.

I overestimate the time it takes to learn the framework. Why don't you do Quickstart for 25 minutes for the time being? Compared to implementing a server with Socket, the time taken for learning pays immediately. http://flask.pocoo.org/docs/quickstart/

Here's what I actually implemented in 25 minutes: https://gist.github.com/nishio/be5b5071a8c8fb94836b

I started by copying Hello world, so there are traces in the function name, and I haven't erased the print, but this is a dirty prototype that has just been made.

It is these three lines that statically deliver under a specific directory

    @app.route('/collecting/<path:filename>')
    def send_foo(filename):
        return send_from_directory('../collecting', filename)

These 4 lines save the POST to a specific URL. By the way, since I use it only infrequently by myself, I save it in a file because I don't need a database.

    @app.route('/api/save/<filename>', methods=['POST'])
    def save(filename):
        file(filename, 'w').write(request.form['data'])
        return 'ok'

Also, Hello world doesn't have a debug option, but if you add it, you can see the stack trace at 500, and you can execute the code interactively at each frame of the stack trace, so you can investigate the cause. Convenient.

    app.run(debug=True)

For prototypers, investing 25 minutes in Flask learning is a great bet.

Postscript: Oh, I forgot to write it, but the client side uses jQuery, and sending data to this API looks like this:

    $.post('/api/save/hoge', {'data': 'datadatadata'})

Recommended Posts

Use Flask as the next step for SimpleHTTPServer
Next, use Python (Flask) for Heroku!
Use BMFont as the font for pyglet
How to use MkDocs for the first time
Use logger with Python for the time being
Use the e-paper module as a to-do list
Use get as much as possible for dictionary-type references
Specify MinGW as the compiler to use with Python
Next to Excel, for the time being, jupyter notebook
Use the company name recognition dictionary "JCLdic" for MeCab