Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Flask Framework Cookbook

You're reading from   Flask Framework Cookbook Over 80 hands-on recipes to help you create small-to-large web applications using Flask

Arrow left icon
Product type Paperback
Published in Nov 2014
Publisher
ISBN-13 9781783983407
Length 258 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Shalabh Aggarwal Shalabh Aggarwal
Author Profile Icon Shalabh Aggarwal
Shalabh Aggarwal
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Flask Configurations FREE CHAPTER 2. Templating with Jinja2 3. Data Modeling in Flask 4. Working with Views 5. Webforms with WTForms 6. Authenticating in Flask 7. RESTful API Building 8. Admin Interface for Flask Apps 9. Internationalization and Localization 10. Debugging, Error Handling, and Testing 11. Deployment and Post Deployment 12. Other Tips and Tricks Index

Composition of views and models

As we go big, we might want to structure our application in a modular manner. We will do this by restructuring our Hello World application.

How to do it…

  1. First, create a new folder in our application and move all our files inside this new folder.
  2. Then, create __init__.py in our folders, which are to be used as modules.
  3. After that, create a new file called run.py in the topmost folder. As the name implies, this file will be used to run the application.
  4. Finally, create separate folders to act as modules.

Refer to the following file structure for a better understanding:

flask_app/
    - run.py
    - my_app/
        – __init__.py
        - hello/
            - __init__.py
            - models.py
            - views.py

First, the flask_app/run.py file will look something like the following lines of code:

from my_app import app
app.run(debug=True)

Then, the flask_app/my_app/__init__.py file will look something like the following lines of code:

from flask import Flask
app = Flask(__name__)

import my_app.hello.views

Then, we will have an empty file just to make the enclosing folder a Python package, flask_app/my_app/hello/__init__.py:

# No content.
# We need this file just to make this folder a python module.

The models file, flask_app/my_app/hello/models.py, has a non-persistent key-value store:

MESSAGES = {
    'default': 'Hello to the World of Flask!',
}

Finally, the following is the views file, flask_app/my_app/hello/views.py. Here, we fetch the message corresponding to the key that is asked for and also have a provision to create or update a message:

from my_app import app
from my_app.hello.models import MESSAGES

@app.route('/')
@app.route('/hello')
def hello_world():
    return MESSAGES['default']


@app.route('/show/<key>')
def get_message(key):
    return MESSAGES.get(key) or "%s not found!" % key


@app.route('/add/<key>/<message>')
def add_or_update_message(key, message):
    MESSAGES[key] = message
    return "%s Added/Updated" % key

Note

Remember that the preceding code is nowhere near production-ready. It is just for demonstration and to make things understandable for new users of Flask.

How it works…

We can see that we have a circular import between my_app/__init__.py and my_app/hello/views.py, where, in the former, we import views from the latter, and in the latter, we import the app from the former. So, this actually makes the two modules depend on each other, but here, it is actually fine as we won't be using views in my_app/__init__.py. We do the import of views at the bottom of the file so that they are not used anyway.

We have used a very simple non-persistent in-memory key-value store for the demonstration of the model layout structure. It is true that we could have written the dictionary for the MESSAGES hash map in views.py itself, but it's best practice to keep the model and view layers separate.

So, we can run this app using just run.py:

$ python run.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader

Note

The reloader indicates that the application is being run in the debug mode, and the application will reload whenever a change is made in the code.

Now, we can see that we have already defined a default message in MESSAGES. We can view this message by opening http://127.0.0.1:5000/show/default. To add a new message, we can type http://127.0.0.1:5000/add/great/Flask%20is%20greatgreat!!. This will update the MESSAGES key-value store to look like the following:

MESSAGES = {
    'default': 'Hello to the World of Flask!',
    'great': 'Flask is great!!',
}

Now, if we open the link http://127.0.0.1:5000/show/great in a browser, we will see our message, which, otherwise, would have appeared as a not-found message.

See also

  • The next recipe, Creating a modular web app with blueprints, provides a much better way of organizing your Flask applications and is a readymade solution to circular imports.
You have been reading a chapter from
Flask Framework Cookbook
Published in: Nov 2014
Publisher:
ISBN-13: 9781783983407
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime