mysql - python开发web service 中数据库链接和释放应该怎么处理?
ringa_lee
ringa_lee 2017-04-18 10:20:17
0
4
742

用tornado开发web service服务。服务端根据接收到的json数据对mysql数据库进行查询,并把结果反馈给用户。采用sqlalchemy对数据库进行操作,以下对数据库链接的创建,释放是否合理呢?

class db:

    def __init__(self,db_ip='',db_name='',db_user='',db_pass='',db_charset=''):
        self.db_str = 'mysql+pymysql://'+db_user+':'+db_pass+'@'+db_ip+':3306/'+db_name+'?'+'charset='+db_charset
        self.engine = create_engine(self.db_str, encoding='utf-8', echo=False)
        self.dbsession = sessionmaker(bind=self.engine)
        
    def return_dbsession(self):
        return self.dbsession
        
    def close_session(self):
        self.session.close()
database = db(db_ip='127.0.0.1', db_name='data_utf', db_user='root', db_pass='root', db_charset='utf8')

处理post请求代码如下

class rcvRequest(tornado.web.Request):
    session = scoped_session(database.return_dbsession())()
    response = []
    for ctt in session.query(table).filter(table.ID == id):
        response.append(ctt)
    self.write(str(response))
    session.close()
ringa_lee
ringa_lee

ringa_lee

reply all(4)
小葫芦

It’s unreasonable. Isn’t it wasteful to establish a connection for every request?
sqlalchemy can help you manage the connection pool very well. If you want to find information, use the connection pool.

阿神

Is it reasonable to adjust the code to the following method?

def db(db_ip='',db_name='',db_user='',db_pass='',db_charset=''):
        db_str = 'mysql+pymysql://'+db_user+':'+db_pass+'@'+db_ip+':3306/'+db_name+'?'+'charset='+db_charset
        engine = create_engine(self.db_str, encoding='utf-8', echo=False)
        dbsession = sessionmaker(bind=self.engine)
        return dbsession

database =db(db_ip='127.0.0.1', db_name='data_utf', db_user='root', db_pass='root', db_charset='utf8')
        
class rcvRequest(tornado.web.Request):

    def initialize(self):
        self.session = scoped_session(database)()
        
    @tornado.gen.coroutine
    def post(self):
        response = []
        for ctt in self.session.query(table).filter(table.ID == id):
            response.append(ctt)
        self.write(str(response))
    
    def on_finish(self):
        self.session.close()
阿神

It is still recommended to find an ORM. If you request a link like this once, the data service may hang up.

阿神

Please refer to
https://github.com/PyMySQL/To...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template