15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flask SQLAlchemyを使ってMySQLに接続

Posted at

ファイル構成

├── 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__)

  # DB設定を読み込む
  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)

参考

Flask + SQLAlchemyプロジェクトを始める手順
VS CodeとFlask-SQLAlchemyでデータベース操作

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?