sqlalchemy tornado




#-*- 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值