analitics

Pages

Monday, August 5, 2019

Python 3.7.3 : Using the flask - part 009.

In this tutorial, I will show you how to use blueprints with a new type of flask project using multiple python files.
I show you just how to create the A.P.I. not the REACT front end.
Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications. A Blueprint object works similarly to a Flask application object, but it is not actually an application. Rather it is a blueprint of how to construct or extend an application., see the official webpage.
In my my_flask folder, I create a blue_test folder with three python files: __init__.py, views.py, and models.py.
The __init__.py file has this source code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# create path for SQLAlchemy
import os
basedir = os.path.abspath(os.path.dirname(__file__))

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    # instantiate config for SQLAlchemy
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'texts.sqlite')
    # init db 
    db.init_app(app)
    # avoid circular importing of circular dependency 
    from .views import main
    app.register_blueprint(main)
    return app
The views.py come with this source code:
from flask import Blueprint
from flask import jsonify, request
from . import db
from .models import Texts

main = Blueprint('main', __name__)
@main.route('/add_text', methods = ['POST'])
def add_text():
    txt_data = request.get_json()
    new_txt = Texts(title=txt_data['title'], txt_content=txt_data['txt_content'])
    db.session(new_txt)
    db.session.commit()
    # 201 status code for create successfully
    return 'Done', 201
@main.route('/texts/')
def texts():
    txt_list=Texts.query.all()
    texts=[]
    for txt in txt_list:
        texts.append({'title': txt.title, 'txt_content':txt.txt_content})
    return jsonify ({'texts':texts})
The models.py has this source code:
# import db from base folder, see dot
from . import db 

class Texts(db.Model):
    # primary key 
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    txt_content = db.Column(db.String(1000))
Use the base folder of the blue_test folder to instantiate the database named texts.sqlite with a table texts.
C:\Python373>cd my_flask

C:\Python373\my_flask>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from blue_test.models import Texts
>>> from blue_test import db, create_app
>>> db.create_all(app=create_app())
>>> exit()
If not run into the base folder then you get this error:
    from . import db
ImportError: attempted relative import with no known parent package
Now you will have a texts.sqlite file for the database.
Use this command to set FLASK_APP:
C:\Python373\my_flask>set FLASK_APP=blue_test
C:\Python373\my_flask>flask run
Now, using the postman you can test it by running the python script and call these methods.