Flask Day 1
“Hello World” in Flask
Create a folder named microblog (or whatever you want). Then cd into that folder and run following prompt in terminal:
1 | $ python3 -m venv flask |
Now you’ll have a folder named flask inside microblog, containing a private version of Python interpreter.
And you should install flask and extensions by the commands below:
1 | $ flask/bin/pip install flask |
After that, let’s create the basic structure for our application: app app/static app/templates tmp.
app— where the application package isstatic— stores static files like images, javascripts, and css.templates— where templates will go.
Then you can start with __init__.py which should put into app folder (file app/__init__.py):
1 | from flask import Flask |
The views are the handlers that response to requests from web browsers or other clients. Each view function is mapped to one or more request URLs.
Let’s see what a views function looks like (file app/views.py):
1 | from flask import Flask |
Finally we should create a script to starts up the web server with our application(file run.py):
1 | #!flask/bin/python |
To indicating that is an executable file you need to run this in terminal:
1 | $ chmod a+x run.py |
Now the file structure should look like:
1 | microblog\ |
Then start to write the template (file app/templates/index.html):
1 | <html> |
Now let’s write the view function that uses this template (file app/views.py):
1 | from flask import render_template |
render_template function is what we import from Flask framework to render the template. It uses Jinja2 templating engine.
