• sqlalchemy
    • 问题
    • 方案
      • models.py

    sqlalchemy

    问题

    如何在web.py中使用sqlalchemy

    方案

    创建一个钩子并使用sqlalchemy的scoped session(http://www.sqlalchemy.org/docs/05/session.html#unitofwork_contextual)

    1. import string
    2. import random
    3. import web
    4. from sqlalchemy.orm import scoped_session, sessionmaker
    5. from models import *
    6. urls = (
    7. "/", "add",
    8. "/view", "view"
    9. )
    10. def load_sqla(handler):
    11. web.ctx.orm = scoped_session(sessionmaker(bind=engine))
    12. try:
    13. return handler()
    14. except web.HTTPError:
    15. web.ctx.orm.commit()
    16. raise
    17. except:
    18. web.ctx.orm.rollback()
    19. raise
    20. finally:
    21. web.ctx.orm.commit()
    22. app = web.application(urls, locals())
    23. app.add_processor(load_sqla)
    24. class add:
    25. def GET(self):
    26. web.header('Content-type', 'text/html')
    27. fname = "".join(random.choice(string.letters) for i in range(4))
    28. lname = "".join(random.choice(string.letters) for i in range(7))
    29. u = User(name=fname
    30. ,fullname=fname + ' ' + lname
    31. ,password =542)
    32. web.ctx.orm.add(u)
    33. return "added:" + web.websafe(str(u)) \
    34. + "<br/>" \
    35. + '<a href="/view">view all</a>'
    36. class view:
    37. def GET(self):
    38. web.header('Content-type', 'text/plain')
    39. return "\n".join(map(str, web.ctx.orm.query(User).all()))
    40. if __name__ == "__main__":
    41. app.run()

    models.py

    1. from sqlalchemy import create_engine
    2. from sqlalchemy import Column, Integer, String
    3. engine = create_engine('sqlite:///mydatabase.db', echo=True)
    4. from sqlalchemy.ext.declarative import declarative_base
    5. Base = declarative_base()
    6. class User(Base):
    7. __tablename__ = 'users'
    8. id = Column(Integer, primary_key=True)
    9. name = Column(String)
    10. fullname = Column(String)
    11. password = Column(String)
    12. def __init__(self, name, fullname, password):
    13. self.name = name
    14. self.fullname = fullname
    15. self.password = password
    16. def __repr__(self):
    17. return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)
    18. users_table = User.__table__
    19. metadata = Base.metadata
    20. if __name__ == "__main__":
    21. metadata.create_all(engine)

    在跑程序之前,运行’python models.py’来初始化一次数据库.