Package and Blueprint

The overall file structure

project\
    weather\
        static\
            style.css
        templates\
            index.html
            ...
        __init__.py
        forms.py
        models.py
        views.py
        ...
    config.py
    README.md
    requirements.txt
    run.py

__init__.py

  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 views functions have be imported in the __init__.py file.
  3. Register blueprints
from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)
# Configuration
app.config.from_object('config')
app.secret_key = 'ae25be573f1b6e19a066fe920685137cb5ea4f76e5924173'

# Define the database object
db = SQLAlchemy(app)


from weather.views import weather
# Register blueprint(s)
app.register_blueprint(weather)


# Build the database:
# This will create the database file using SQLAlchemy
db.create_all()

In views.py

Define blueprint

from flask import Blueprint, render_template, redirect, url_for, flash, request
from weather.forms import WeatherForm, UpdateForm
from weather.models import CurrentModel, HistoryModel, DailyModel


weather = Blueprint('weather', __name__)


@weather.route('/', methods=['POST', 'GET'])
def index():
    form = WeatherForm()
    if form.validate_on_submit():
    ...

@weather.route('/update/<location>', methods=['POST', 'GET'])
def update(location):
    form = UpdateForm()
    if form.validate_on_submit():
    ...

Circular Imports

Here views.py and __init__.py depends on each other. This a a bad idea in general but here it is actually fine. Because in __init__.py, we are not actually using the views in __init__.py, and just ensuring the module is imported and we are doing that at the bottom of the file.

results matching ""

    No results matching ""