Bootstrap FreeKB - Flask - Importing your own modules
Flask - Importing your own modules

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask app has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

For example, let's say your view (views.py in this example) has the following, where you have from flask import <modules>. The modules are simply files that are part of the Python Standard Library included with the Python installation being used by Flask. For example, the Blueprint module is simply the Blueprint.py file found somewhere in sys.path.

from flask import Blueprint, render_template

views = Blueprint('views', __name__)

@views.route('/')
def home():
    return render_template('base.html')

 

Modules can also be imported using TBD. For example, in your controller (__init__.py), let's say you have from .models import users

This could also be from app.modelsimport users since the name of the application is "app". 

In this example, the "users" class or function in models.py will be imported into the controller (__init__.py).

from flask import Flask

def app():
    app = Flask(__name__)
    from .models import users
    return app

 

However, there will ineviatabley be situations where you'll want to create your own module. A module is simply a Python file with the .py extension that does something. For example, let's say you have a file named greeting.py that contains the following.

def hello():
  return "Hello World"

 

In your view, for local testing on your laptop, you could save greeting.py to a directory on your laptop, such as C:\Users\john\greeting.py, and then use the sys module to append C:\Users\john to your sys.path (systems paths).

import sys
from flask import Blueprint, render_template, request

views = Blueprint('views', __name__)

sys.path.append(r"C:\Users\john")
from greeting import hello

@views.route('/')
def home():
    print(hello())
    return render_template('base.html', headers=request.headers)

 

Since the hello function is being printed in the / route, when you navigate to /, Hello World should be printed to your terminal console.

Hello World

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 331969 in the box below so that we can be sure you are a human.