sqlalchemy tornado
编程技术  /  houtizong 发布于 3年前   134
#-*- encoding: utf-8 -*-'''Created on 2014-12-3@author: cooler'''import tornado.ioloopimport tornado.web# sqlalchemy 使用 from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy import Columnfrom sqlalchemy.types import CHAR, Integer, Stringfrom sqlalchemy.ext.declarative import declarative_basefrom 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()
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接