#-*- encoding: utf-8 -*-
'''
Created on 2014-12-3
@author: cooler
'''
import tornado.ioloop
import tornado.web
# sqlalchemy 使用
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column
from sqlalchemy.types import CHAR, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func, or_, not_
BaseModel = declarative_base()
def init_db():
BaseModel.metadata.create_all(engine)
def drop_db():
BaseModel.metadata.drop_all(engine)
class User(BaseModel):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(CHAR(30)) # or Column(String(30))
#-------------------------------------------------------------------------------------
class MainHandler(tornado.web.RequestHandler):
def get(self):
# self.write('<html><body><form action="/" method="post">'
# '<input type="text" name="message">'
# '<input type="submit" value="Submit">'
# '</form></body></html>')
DB_CONNECT_STRING = 'mysql+mysqldb://cooler:cooler@localhost/testsqlalchemy?charset=utf8'
engine = create_engine(DB_CONNECT_STRING, echo=True)
DB_Session = sessionmaker(bind=engine)
session = DB_Session()
# user = User(name='a')
# session.add(user)
# user = User(name='b')
# session.add(user)
# user = User(name='a')
# session.add(user)
# user = User()
# session.add(user)
# session.commit()
query = session.query(User)
#-------------------------------------------
# print query # 显示SQL 语句
# print query.statement # 同上
# for user in query: # 遍历时查询
# print user.name
#---------------------------------------------
# print query.all()
#---------------------------------------------
# print query.first().name # 记录不存在时,first() 会返回 None
# print query.one().name # 不存在,或有多行记录时会抛出异常
# print query.filter(User.id == 2).first().name
# print query.get(2).name # 以主键获取,等效于上句
# print query.filter('id = 2').first().name # 支持字符串
self.write()
application = tornado.web.Application([
(r"/", MainHandler),
],debug=True)
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
sqlalchemy tornado
最新推荐文章于 2024-08-31 09:30:00 发布