- 论坛徽章:
- 0
|
在一个flask应用中,我需要用sqlalchemy动态的连接某几个库,而且有时会做新建数据库操作,每次请求都可能是不同的数据库。
每次请求都会reload模块db.py,这样做会不会影响服务器性能?还有其它用sqlalchemy的解决办法么?
main.py- from flask import Flask, render_template, request, session, g, redirect, url_for
- from sqlalchemy import create_engine
- from sqlalchemy.orm import scoped_session, sessionmaker
- from sqlalchemy.ext.declarative import declarative_base
- app = Flask(__name__)
- app.secret_key = '\x80\xeeW~\x17\x00@\xab\xd41\xe1]\x00I\x92 \xae\x8c\x00\xf6\xc4\xc1F\xdf'
- @app.before_request
- def before_request():
- if not hasattr(g,'db'):
- g.db = dict()
- if session.has_key('login'):
- db_str = 'mysql://root:qeephp@localhost:3306/%s?charset=utf8' % session['login']
- engine = create_engine(db_str)
- db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine))
- g.db[session['login']] = (engine, db_session)
- else:
- db_str = 'mysql://root:qeephp@localhost:3306/maindb?charset=utf8'
- engine = create_engine(db_str)
- db_session = scoped_session(sessionmaker(autocommit=False,autoflush=False,bind=engine))
- g.db['default'] = (engine, db_session)
- import db
- db = reload(db)
-
- @app.route('/')
- def index():
- return 'abc'
- @app.route('/create')
- def create():
- import db
- db = reload(db)
- print db.engine
- db.Base.metadata.drop_all(db.engine)
- db.Base.metadata.create_all(db.engine)
- if session.has_key('login'):
- return 'login'
- else:
- return 'no login'
- @app.route('/login')
- def login():
- session['login']='abcde'
- return redirect(url_for('create'))
- @app.route('/logout')
- def logout():
- session.pop('login', None)
- return 'logout'
- if __name__ == '__main__':
- app.run(debug=True)
复制代码 db.py- #coding:utf-8
- from flask import session, g
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy import Column, Integer, String, Text, ForeignKey, Table, func
- from sqlalchemy.orm import relationship, backref
- from sqlalchemy.orm.collections import attribute_mapped_collection
- import hashlib,time
- if session.has_key('login'):
- engine, db_session = g.db[session['login']]
- else:
- engine, db_session = g.db['default']
- Base = declarative_base()
- print db_session
- Base.query = db_session.query_property()
- class User(Base):
- __tablename__ = 'users' #职员表
-
- id = Column(Integer, primary_key=True)
- name = Column(String(50), unique=True)
- created_at = Column(String(20), default = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
-
- def __init__(self, name):
- self.name = name
复制代码 |
|