Posted by : at

Category : web-development   python   flask

This tutorial is the second part of tutorial series for creating a web application using Flask.

  1. Part 1 - Set up Python 3.6 Development Environment

  2. Part 2 - Setting up Flask App - This tutorial

  3. Part 3 - Setting up Database using SqlAlchemy

  4. Part 4 - Setting up Flask App Configurations

  5. Part 5 - Setting up Flask Migrations

Part - 2 Setting Up Flask App

So first you need to setup the virtualenv for your project. For this project we will be using python3.6. We need to install virtualenv first. If you dont have virtualenv installed follow the below instructions:

$ sudo apt-get install python-virtualenv`

Virtualenv is installed. Now to use it for my project:

$ cd flask-boilerplate
$ virtualenv -p python3.6 venv --no-site-packages

This will create a venv folder and activate python3.6 for my project. To check:

$ python -V Python 3.6.3
$ pip -V pip 9.0.1

Next I will be setting up flask for my project

$ pip install flask This will setup flask for my project

Quickly setting up a route to check if everything works fine

Create a app.py

from flask import Flask
app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__'
   app.run(host="0.0.0.0",port=3000,debug=True)

Run the script in the project directory :

$ python app.py

Opening up http://localhost:3000 , It displays Hello, World!

Now I want to change the structure of the project, so that it can be bit modular

/flask-boilerplate /myapp -__init__.py /templates /layouts /forms /pages -home.html -about.html /venv run.py

Lets create about.html and home.html for our routes inside the templates/pages folder

home.html

<!doctype html>
<html>
   <body>

      <h1>Hello, World ! </h1>

   </body>
</html>

Similarly, about.html

<!doctype html>
<html>
   <body>

      <h1>About Flask Boilerplate </h1>

   </body>
</html>

We need to initialize myapp package using “init.py” inside myapp folder

inside init.py

from flask import Flask, render_template
app = Flask(__name__)


@app.route('/')
def hello_world():
    return render_template('/pages/home.html')


@app.route('/about')
def about():
    return render_template('/pages/about.html')

inside run.py

from myapp import app

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=3000, debug=True)

Now I can run the app using

$ python run.py

You can also add a FLASK configuration variable to run the app using flask command

$ export FLASK_APP = run.py

Now you can run the app using the below command :

$ flask run 

In the next part we will be setting up Flask SQLalchemy for setting up our models and sqlite database to save our data.