[Python] Flask step by step tutorial

2018-04-03

Installation and creating the environment

For Max OS users, the first thing you need to do is to install virtualenv

1
sudo pip install virtualenv

Once we have finished installing virtualenv, we can create our own environment. For example:

1
2
3
mkdir flaskPlayground
cd flaskPlayground
virtualenv flaskPlayground

To active the corresponding environment,

1
. /flaskPlayground/bin/active

To deactive the environment,

1
deactivate

If you are not using other OS, take a look at the flask documentation. http://flask.pocoo.org/docs/0.12/installation/#installation

pip freeze

requirement.txt is commonly used in Flask to list all the dependent packages. It can be generated by pip freeze > requirement.txt and to install all the packages, you only need to run pip install -r requirements.txt

Note: When you freeze or install the packages, make sure you are in the correct virtual environment.

pip install flask-script

Flask-Script extension provides support for writing external script in Flask. This includes running a development server, a customised python shell, scripts to set up your database, cronjobs, and other command-line tasks that belong outside the web application itself.

Flask-Script works in a similar way to Flask itself. You define and add commands that can be called from the command line to a Manager instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# manage.py
from flask_script import Manager
from myapp import app
manager = Manager(app)
@manager.command
def hello():
print "hello"
if __name__ == "__main__":
manager.run()

Once you define your script commands, you can then run them on the command line:

1
python manage.py hello

The second argument hello is same as the function name.

Quickstart

Save the following content as “Hello.py” inside the flaskPlayground folder.

1
2
3
4
5
6
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'

Then run the following command in the terminal:

1
2
export FLASK_APP=hello.py
python -m flask run

Now, we start our first flask server. :P

Error Handling for 404

If the user type the wrong url, we should tell him that it is not found, but in another case, for example:

1
2
3
4
5
6
@app.route('/author/<authors_last>')
def author(authors_last):
html = """
{authors_last}
"""
return html.format(authors_last=authors_last)

If the user type /author/123, even if the author does not exist…. It should also render that page. Here is the solution: we can pre-define a list to store all the available author names, and then

1
2
3
4
5
6
7
8
@app.route('/author/<authors_last>')
def author(authors_last):
if(authors_last not in AUTHORS_INTO):
abort(404)
html = """
{authors_last}
"""
return html.format(authors_last=authors_last)

And it will force to redirect to 404 Not found page.

Also, we can check the input type for example: change /author/<authors_last> to /author/<string: authors_last>

The following code is how to handle the 404 not found exception:

1
2
3
4
5
6
@app.errorhandler(404)
def not_found(error):
html = """
QAQ... Not found....
"""
return html

Render a html file

Note that the default path is /templates/. So make sure that all the files are stored in that directory, or you need to edit the default path.

1
2
3
4
@app.route('/loadhtml')
def load_html():
test_name="Test"
return render_template('index.html', test_name=test_name), 404

Comments: