Folder structure and file organisation for python flask

Two methods to create flask application

Case 1: a module:

/application.py
/templates
    /hello.html

Case 2: a package:

/application
    /__init__.py
    /templates
        /hello.html

For larger applications it’s a good idea to use a package instead of a module.

How to convert module into package

To convert that into a larger one, just create a new folder yourapplication inside the existing one and move everything below it. Then rename yourapplication.py to __init__.py. (Make sure to delete all .pyc files first, otherwise things would most likely break)

 

Now we can restructure the application a bit into multiple modules. The only thing you have to remember is the following quick checklist:

  1. the Flask application object creation has to be in the __init__.py file. That way each module can import it safely and the __name__ variable will resolve to the correct package.
  2. all the view functions (the ones with a route() decorator on top) have to be imported in the __init__.py file. Not the object itself, but the module it is in.

Here is sample folder structure

 


.
└── myproject
├── myapp1
│   ├── __init__.py
│   ├── static
│   ├── templates
│   │   ├── aboutus.html
│   │   ├── base_bkp.html
│   │   ├── base.html
│   │   ├── contactus.html
│   │   └── index.html
│   └── views.py
└── setup.py

Using Blueprint

In above example we have used very simple structure. Now let us look at creating multiple views and grouping them together using blueprint

A Blueprint is a way to organize a group of related views and other code. Rather than registering views and other code directly with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function.

here is sample code for simple flask package with two blueprints


import os

from flask import Flask


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    # app.config.from_mapping(
    #     SECRET_KEY='dev',
    #     DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    # )

    from . import auth
    app.register_blueprint(auth.bp)

    from . import blog
    app.register_blueprint(blog.bp)

    # import myapp1.views

    # a simple page that says hello
    @app.route('/')
    def hello():
        return 'Hello, World!'

    return app

auth.py


import functools

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash


bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/')
def auth_home():
	return "this is auth base page"

@bp.route('/aboutus')
def aboutus():
	return render_template('aboutus.html', name="techtrekking.net")

@bp.route('/contactus')
def contactus():
	return render_template('contactus.html')

blog.py


import functools
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.security import check_password_hash, generate_password_hash
bp = Blueprint('blog', __name__, url_prefix='/blog')
@bp.route('/')
def auth_home():
    return "this is blog base page"
@bp.route('/aboutus')
def aboutus():
    return render_template('aboutus.html', name="techtrekking.net")
@bp.route('/contactus')
def contactus():
    return render_template('contactus.html')

By using blueprint, you can segregate urls based on their functions. This is very usefull method to segregate the different sections of the website.

Using templates in Python Flask framework

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package:

Currently our application is developed as module. We will see the difference between module and package later.

Adding Templates

Now let us add a folder called templates inside application directory and add required html files here. Update application file to use html files

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

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

@app.route('/aboutus')
def aboutus():
	return render_template('aboutus.html', name="techtrekking.net")

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

Please note  following changes to the base file:

  1. we have imported “render_template”
  2. usage of render_template for creating output
  3. Usage of parameter “name” while rendering the html file. This keyword will be accessible in template and will be displayed within {{}}

This is simple example  of using separate template files for each route. Here none of the code is shared across views

Advanced templates

Many times we have few fixed parts of the website, irrespective of the page, such as navigation bar and footer. If you have to keep this code in each html page, making any change in this code will be cumbersome process. Flask has a great feature to make this change once and apply this to all pages. This is achieved by creating base template and extending the base template for individual pages.

Here we will create a base template having navigation bar, footer and different section. When we have to render different pages, we will simple reuse this base template and replace the required section run time.

Here is sample folder structure


├── myapp.py
└── templates
     ├── aboutus.html
     ├── base.html
     ├── contactus.html
     └── index.html

Base file structure


<!doctype html>
<title>{% block title %}{% endblock %}</title>
<a href="/">home</a>
<a href="/aboutus">about us</a>
<a href="/contactus">contact us</a>

<header>
{% block header %}{% endblock %}
</header>
{% block content %}{% endblock %}

About us file is as below


{% extends 'base.html' %}

{% block title %} about us{% endblock %}

{% block header %}
<h1>About us header</h1>
{% endblock %}

{% block content %}
<h4>About us</h4>
<p>lorum ipsum text here</p>
<p>this is {{ name }}</p>
{% endblock %}

Now whenever you want to  change header or footer, you need to change only at one place.

Please note following

  • I have created blocks in base file. More the number of blocks, more the flexibility
  • Blocks will be replaced in the individual templates.
  • Base code outside the blocks gets copied as is.
  • If base block is not placed in individual template, base block will be displayed

“Hello World !” using python flask framework

In this article we will create a simplest application using pything flask. This will display nothing but simple ” hello world on the page.

Here is the code

from flask import Flask
app = Flask(__name__)

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

This is cleanest code for any framework that I have seen.

Now go to terminal and type following commands

conquistador@inspiron-3542:~/code/flask/tutorial$ export FLASK_APP=hello_world.py
conquistador@inspiron-3542:~/code/flask/tutorial$ flask run
* Serving Flask app "hello_world.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 189-606-216

Now go to http://127.0.0.1:5000/ and  you will see following page

Flask Hello world
Flask Hello world

Adding few more pages.

Let us add aboutus and contact us pages. To add routing, you simple need to add 3 line to the same file. You need to add @app.route(‘/contactus’)

Here is updated hello world file

from flask import Flask
app = Flask(__name__)

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

@app.route('/aboutus')
def aboutus():
   return 'This is about us page'

@app.route('/contactus')
def contactus():
   return 'This is contact us page'

Now you can access about us page at http://127.0.0.1:5000/aboutus and contact us page at  http://127.0.0.1:5000/contactus

Flask About us page
Flask About us page

Getting started with flask with Ubuntu 16.04

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions. It is classified as a microframework because it does not require particular tools or libraries.[3] It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. However, Flask supports extensions that can add application features as if they were implemented in Flask itself. Extensions exist for object-relational mappers, form validation, upload handling, various open authentication technologies and several common framework related tools.

“Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible.

Flask Vs django

When I was learning python, I decided to choose one of the python framework for web application development. Obvious question was whether it should be django or flask ? django and flask both have their own use cases and I started with django instead of flask simply because of some of the big websites like instagram, pinterest are using django and I could not find any well known website using flask.

However, upon my further research I found that flask is more pythonic than django (IMHO). django is “batteries included” and very opinionated framework where as flask is un-opinionated framework and this suits many use cases.

Where flask is used.

fask is used as api provideer at pinterest twilio. falsk is also used to create dash

Install flask

Flask can be installed using following command

sudo python3.6 -m pip install Flask

First Python App

Basic application is as below

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
return 'Index Page'

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

Same this file as hello.py and run following commands

export FLASK_APP=hello.py
$flask run
 * Serving Flask app "hello_world.py"
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

and user application will be up and running

Getting started with flask
Getting started with flask

as a project get bigger, it becomes overwhelming to keep all the code in one file. Python projects use packages to organize code into multiple modules that can be imported where needed, and the tutorial will do this as well.

 

Blueprint is a way to organize a group of related views and other code. Rather than registering views and other code directly with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function.

The template files will be stored in the templates directory inside the flaskr package. Templates are files that contain static data as well as placeholders for dynamic data. A template is rendered with specific data to produce a final document. Flask uses the Jinja template library to render templates.

Flask Python Tutorial

Flask is a microframework for Python. “Micro” does not mean that your whole web application has to fit into a single Python file (although it certainly can), nor does it mean that Flask is lacking in functionality. The “micro” in microframework means Flask aims to keep the core simple but extensible.

Configuration vs Conventions

Flask has many configuration values, with sensible defaults, and a few conventions when getting started. By convention, templates and static files are stored in subdirectories within the application’s Python source tree, with the names templatesand static respectively. While this can be changed, you usually don’t have to, especially when getting started.

In this chain or articles we will learn flask. Here is overall flow

  • Getting started with Flask
  • Hello World in Flask
  • Templates
  • Databases
  • MVC in flask
  • Structuring your project