Flask db

De Memo
Aller à : navigation, rechercher

sqlite

https://sqlite.org/download.html

db

$ pip install flask_sqlalchemy

config.py

import os

...

basedir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')

models.py

from flask_sqlalchemy import SQLAlchemy

from .views import app

# Create database connection object
db = SQLAlchemy(app)

class Content(db.Model):
   id = db.Column(db.Integer, primary_key=True)
   description = db.Column(db.String(200), nullable=False)
   gender = db.Column(db.Integer(), nullable=False)

   def __init__(self, description, gender):
       self.description = description
       self.gender = gender

db.create_all()

fbapp/__init__.py

from flask import Flask

from .views import app
from . import models

# Connect sqlalchemy to app
models.db.init_app(app)

@app.cli.command()
def init_db():
   models.init_db()


Interaction BD

FLASK_APP=run.py flask shell
FLASK_APP=run.py flask init_db