Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Basic Flask Web Server Setup In Python

TODO: Fix the formatting of this post that got busted during the move to nextjs

Code

### Basic Hello, World

``python 
#!/usr/bin/env python 

from flask import Flask
    
app = Flask(__name__)
    
@app.route('/')
def index():
    return "Hello, World"

app.run(port=8000, host='0.0.0.0')
``
            
--------------------------------------------------------------------------------

TODO: Verify this works as expected 

### Using query strings

``python
from flask import Flask
from flask import request


app = Flask(__name__)

@app.route('/')
def index(name="Example"):
    name = request.args.get('name', name)
    return "Hello {}".format(name)

app.run(port=8000, host='0.0.0.0')  
``
    
-- hr


The `from flask import request` sets up a global object that allows for grabbing query strings. 


-- hr

Routes are setup with decorators. For example:

    @app.route('/')
    
Views can have more than one route. And they can be used to create variables. 

    @app.route('/')
    @app.route('/<name>')


-- hr

For cleaned up URLs, this would get us:

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    @app.route('/<name>')
    def index(name="World"):
        return "Hello {}".format(name)
    
    app.run(debug=True, port=8000, host='0.0.0.0')
    

-- hr

Multiple routes with types


    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/multiply')
    @app.route('/multiply/<int:val1>/<int:val2>')
    @app.route('/multiply/<float:val1>/<int:val2>')
    @app.route('/multiply/<float:val1>/<float:val2>')
    @app.route('/multiply/<int:val1>/<float:val2>')    
    def multiply(val1=5, val2=5):
        return str(val1 * val2)