[PYTHON] Connect to MySQL using Flask SQLAlchemy

file organization

├── api
|   ├── __init__.py
|   ├── database.py
|   ├── views
|   |   └── user.py
│   ├── models
|       └── user.py
├── app.py
└── config.py

File creation

__init__.py


from flask import Flask
from api.database import db
from .views.user import user
import config

def create_app():
  
  app = Flask(__name__)

  #Read DB settings
  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

Creating a model

/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()

Routing creation

/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)

reference

Procedure to start Flask + SQLAlchemy project Database operation with VS Code and Flask-SQLAlchemy

Recommended Posts

Connect to MySQL using Flask SQLAlchemy
Connect to mysql
Connect to Docker's MySQL container from Flask
Connect python to mysql
Try using SQLAlchemy + MySQL (Part 2)
Connect to multiple databases with SQLAlchemy
Connect to MySQL with Python within Docker
Scraping using lxml and saving to MySQL
How to use SQLAlchemy / Connect with aiomysql
A story about trying to connect to MySQL using Heroku and giving up
Try to separate Controllers using Blueprint in Flask
Connect your Raspberry Pi to your smartphone using Blynk
Connect to the Bitcoin network using pybitcoin tools
Connect to MySQL with Python on Raspberry Pi
How to read dynamically generated table definitions using SQLAlchemy
Easy to use Flask
Try to make RESTful API with MVC using Flask 1.0.2
I get [Error 2055] when trying to connect to MySQL on Heroku
Connect to the Bitcoin network using pycoin (Python Cryptocoin Utili)
Connect to KUINS-III (Kyoto University VPN) from Linux using PPTP
Generate SQLAlchemy table definition from existing MySQL server using sqlacodegen
How to search by string to use mysql json_contains in SQLAlchemy
Connect to KUINS-III (Kyoto University VPN) from Linux using IKEv2
Until API made with Flask + MySQL is converted to Docker
Connect to BigQuery with Python
Connect to Wikipedia with Python
Connect to Postgresql with GO
Introduction to RDB with sqlalchemy Ⅰ
Post to Twitter using Python
Start to Selenium using python
How to update with SQLAlchemy?
Connect Vagrant's MySQL with MySQL Workbench
Connect to sqlite from python
React and Flask to GCP
Connect to s3 tokyo region
Introduction to discord.py (3) Using voice
How to Delete with SQLAlchemy?
Python: Introduction to Flask: Creating a number identification app using MNIST
When you want to send an object with requests using flask