用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()
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?
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...