analitics

Pages

Tuesday, August 6, 2019

Python 3.7.3 : Using the flask - part 010.

If you read my last tutorial about flask then you understand how to use the structure flask project with views.py and models.py.
If you run it and open the browser with http://127.0.0.1:5000/texts/ the result will be this:
{"texts":[{"title":"first title","txt_content":"this is first content"},{"title":null,"txt_content":null}]}
Let's create a file .env into the base folder named my_flask and add this source code:
SECRET_KEY='secret key'
DEBUG=True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = sqlite:///texts.sqlite
Let's create a settings.py file into blue_test folder to get these settings:
import os
from os import environ
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI')
My blue_test project comes with the old views.py and a new routes.py file with this source code:
from flask import Blueprint, jsonify, request

api = Blueprint('api', __name__)

@api.route('/')
def home():
    return jsonify({'result' : 'You are in main page!'}) 
I create an extensions.py python script to deal with the database, see the source code:
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
With this new python file will solve the avoid circular importing of circular dependency of importing db.
This changes can be made on models.py and views.py, like this:
# import db from base folder, see dot
from .extensions import db 
This two files views.py and routes.py come with two Blueprint's: main and api.
Into the __init__.py will need to import and register both :
from .extensions import db
from .models import Texts
from .routes import api
from .views import main
...
    app.register_blueprint(main)
    app.register_blueprint(api)
If you run it into my_flask folder with:
C:\Python373\my_flask>set FLASK_APP=blue_test

C:\Python373\my_flask>flask run
 * Serving Flask app "blue_test"
 * Environment: production
...
The result into the browser area with http://127.0.0.1:5000/ for the routes.py blueprint api will be:
{"result":"You are in main page!"}
The result into the browser area with http://127.0.0.1:5000/texts/ for the views.py blueprint main will be:
{"texts":[{"title":"first title","txt_content":"this is first content"},{"title":null,"txt_content":null}]}
This shows you how to link multiple blueprints into one project.
You can see the full project at my GitHub project.