i have existing database has lot of tables , lot of data in mysql
. intend create flask
app , use sqlalchemy along it. asked out on irc , looked around on google , tried following ideas:
first used sqlacodegen generate models db
. confused little , looked more. , found this.
this looked elegant solution.
so second, rewrote models.py
according solution there , more confused. looking best approach build flask app along existing db.
i looked flask documentation didnt project existing db. there lot of stuff creating scratch, creating db , all. confused.
please note first day flask
, have experience django
, basic concepts not hurdle. need guidance in choosing best approach usecase. detailed explanation appreciated. detailed not expect write code , spoon feed me on this, enough me started, integrate db seamlessly flask
via sqlalchemy
. note db in mysql
.
i'd question has nothing flask @ all. example, don't have problem templates, routes, views or logon decorators.
where struggle @ at sqlalchemy.
so suggestion ignore flask while , used sqlalchemy first. need used existing database , how access sqlalchemy. use mysql documentation tool find way around this. start (note has nothing flask ask ... yet):
#!/usr/bin/python # -*- mode: python -*- sqlalchemy import create_engine sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///webmgmt.db', convert_unicode=true, echo=false) base = declarative_base() base.metadata.reflect(engine) sqlalchemy.orm import relationship, backref class users(base): __table__ = base.metadata.tables['users'] if __name__ == '__main__': sqlalchemy.orm import scoped_session, sessionmaker, query db_session = scoped_session(sessionmaker(bind=engine)) item in db_session.query(users.id, users.name): print item
in line "engine =
" need provide path mysql database, sqlalchemy finds it. in case used pre-existing sqlite3 database.
in line "class users(base)
" need use 1 of existing tables in mysql database. knew sqlite3 database had table named "users".
after point, sqlalchemy knows how connect mysql database , knows 1 of tables. need add other tables care for. finally, need specify relationships sqlalchemy. here mean things one-to-one, one-to-many, many-to-many, parent-chip , on. sqlalchemy web site contains rather lenghty section this.
after line "if __name__ == '__main__'
" comes test code. executed if don't import python script, run. here see create db session , query.
my suggestion first read important parts of sqlalchemy's documentation, example descriptive table definition, relationship model , how query. once know this, can change last part of example controller (e.g. using python's yield
method) , write view uses controller.
Comments
Post a Comment