Skip to content

Instantly share code, notes, and snippets.

@languanghao
Created July 4, 2016 03:35
Show Gist options
  • Save languanghao/a24d74b8ab4232a801312e2a0a107064 to your computer and use it in GitHub Desktop.
Save languanghao/a24d74b8ab4232a801312e2a0a107064 to your computer and use it in GitHub Desktop.
Seperate database model files with flask and sqlalchemy and alembic
from flask import Flask
from services.database import db
app = Flask(module_name)
db.init_app(app)
class Attachment(db.Model):
"""
table attachement
"""
id = db.Column(db.String(50), primary_key=True)
""":type : str"""
name = db.Column(db.String(200))
""":type : str"""
content = db.Column(db.Binary)
""":type : bytearray"""
created = db.Column(db.DateTime, default=datetime.datetime.now)
""":type : datetime"""
content_type = db.Column(db.String(100))
""":type : str"""
def __init__(self, name, content, content_type):
"""
:param content:
:type content: bytearray
:param name:
:type name: str
:param content_type:
:type content_type: str
:return:
:rtype:
"""
self.id = uuid.uuid4().hex
self.name = name
self.content = content
self.content_type = content_type
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# this is alembic env.py file, just edit something like below
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
import sys
import os
sys.path.append(os.getcwd())
from core.configuration import config as sys_config
from services.database import db
# this path is your db_models py files path
path = os.path.join(sys_config.project_root, 'services', 'db_models')
# import all db_models, so the db.metadata will have data
for py in [f[:-3] for f in os.listdir(path) if f.endswith('.py') and f != '__init__.py']:
mod = __import__('.'.join(['services.db_models', py]), fromlist=[py])
classes = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)]
for cls in classes:
if 'flask_sqlalchemy.' in str(type(cls)):
print("auto import db model: {0}".format(cls))
setattr(sys.modules[__name__], cls.__name__, cls)
target_metadata = db.metadata
# sepcial the sqlalchemy.url read form our config file
config.set_main_option('sqlalchemy.url', sys_config.SQLALCHEMY_DATABASE_URI)
class KBInfo(db.Model):
"""
kb info
"""
id = db.Column(db.String(50), primary_key=True)
""":type : str"""
title = db.Column(db.String(200), nullable=False)
""":type : str"""
content = db.Column(db.Text())
""":type : str"""
author = db.Column(db.String(200))
""":type : str"""
created = db.Column(db.DateTime, default=datetime.datetime.now)
""":type : datetime"""
modified = db.Column(db.DateTime, default=datetime.datetime.now)
""":type : datetime"""
is_public = db.Column(db.Boolean)
""":type : bool"""
def __init__(self, title, content, is_public, author):
self.id = uuid.uuid4().hex
self.title = title
self.content = content
self.is_public = is_public
self.author = author
@Biruk-G3
Copy link

what if we need to make a relationship b/n the tables

@dheeraj-gh
Copy link

Excellent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment