'sqlalchemy'에 해당되는 글 1

  1. 2016.03.11 Bottle-Sqlalchemy

Bottle-Sqlalchemy

https://pypi.python.org/pypi/bottle-sqlalchemy/
https://github.com/iurisilvio/bottle-sqlalchemy


> pip install bottle-sqlalchemy
> python -c "import sqlalchemy; print(sqlalchemy.__version__)"
1.0.12


import bottle
from bottle import route, run, debug, install
from bottle.ext import sqlalchemy
from sqlalchemy import create_engine, Column, Integer, Sequence, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///:memory:', echo=True)
plugin = sqlalchemy.Plugin(
    engine
    , Base.metadata
    , keyword='db'
    , create=True
    , commit=True
    , use_kwargs=False
)

#1install(plugin)
app = bottle.Bottle()
app.install(plugin)

class Entity(Base):
    __tablename__ = 'entity'
    id = Column(Integer, Sequence('id_seq'), primary_key=True)
    name = Column(String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return "Entity('%d', '%s')" % (self.id, self.name)

#1@route('/:name')
#2@app.route('/:name')
@app.get('/:name')
def show(name, db):
    print(db)
    entity = db.query(Entity).filter_by(name=name).first()
    if entity:
        return str(entity)
    return "404"

#1@route('/add/:name')
#2@app.route('/add/:name')
@app.get('/add/:name')
def add(name, db):
    entity = Entity(name)
    db.add(entity)
    return "Done"

#1run(debug=True)
app.run()


=-=>초기 데이터는 어떻게 넣나? 초기옵션을 잘 사용하면 될듯

=-=>잘못된 예제

http://www.blog.pythonlibrary.org/2013/07/23/bottle-adding-sqlalchemy-to-the-todo-list-web-app/

https://github.com/mcapielo/Todo-List-Bottle-SQLAlchemy-Bootstrap/blob/master/todo.py