├── api
| ├── __init__.py
| ├── database.py
| ├── views
| | └── user.py
│ ├── models
| └── user.py
├── app.py
└── config.py
__init__.py
from flask import Flask
from api.database import db
from .views.user import user
import config
def create_app():
app = Flask(__name__)
#Lire les paramètres de la base de données
app.config.from_object('config.Config')
db.init_app(app)
app.register_blueprint(user, url_prefix='/user')
return app
app = create_app()
database.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db(app):
db.init_app(app)
app.py
from api import app
if __name__ == '__main__':
app.run()
config.py
class SystemConfig:
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{password}@{host}/{db-name}?charset=utf8'.format(**{
'user': 'user',
'password': 'password',
'host': 'localhost',
'db_name': 'sample'
})
Config = SystemConfig
/api/models/user.py
from api.database import db
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
def searchBy(id):
return db.session.query(User)\
.filter(User.id == id)\
.one()
/api/views/user.py
from flask import Blueprint
from api.models.user import User
# set route
user = Blueprint('user_router', __name__)
@job.route('/<int:id>', methods=['GET'])
def getUser(id):
user = User.searchBy(id)
print(user)
Procédure de démarrage du projet Flask + SQL Alchemy Fonctionnement de la base de données avec VS Code et Flask-SQL Alchemy
Recommended Posts