--- title: Flask Day 1 date: 2016-02-15 01:23:33 --- ### "Hello World" in Flask Create a folder named `microblog` (or whatever you want). Then cd into that folder and run following prompt in terminal: ``` bash $ 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: ``` bash $ flask/bin/pip install flask $ flask/bin/pip install flask-login $ flask/bin/pip install flask-openid $ flask/bin/pip install flask-mail $ flask/bin/pip install flask-sqlalchemy $ flask/bin/pip install sqlalchemy-migrate $ flask/bin/pip install flask-whooshalchemy $ flask/bin/pip install flask-wtf $ flask/bin/pip install flask-babel $ flask/bin/pip install guess_language $ flask/bin/pip install flipflop $ flask/bin/pip install coverage ``` After that, let's create the basic structure for our application: `app` `app/static` `app/templates` `tmp`. 1. `app` — where the application package is 2. `static` — stores static files like images, javascripts, and css. 3. `templates` — where templates will go. Then you can start with ``__init__.py`` which should put into app folder (file `app/__init__.py`): ``` python from flask import Flask app = Flask(__name__) from app import views ``` 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`): ``` python from flask import Flask app = Flask(__name__) from app import views ``` Finally we should create a script to starts up the web server with our application(file `run.py`): ``` python #!flask/bin/python from app import app app.run(debug=True) ``` To indicating that is an executable file you need to run this in terminal: ``` bash $ chmod a+x run.py ``` Now the file structure should look like: ``` microblog\ flask\ app\ static\ templates\ __init__.py views.py tmp\ run.py ``` Then start to write the template (file `app/templates/index.html`): ``` html {{ title }} - microblog

Hello, {{ user.nickname }}!

``` Now let's write the view function that uses this template (file `app/views.py`): ``` python from flask import render_template from app import app @app.route('/') @app.route('/index') def index(): user = {'nickname': 'ching'} # fake user return render_template('index.html', title='Home', user=user) ``` `render_template` function is what we import from Flask framework to render the template. It uses [Jinja2](http://jinja.pocoo.org/) templating engine.