better database alias object

This commit is contained in:
dave 2019-06-22 16:45:32 -07:00
parent 5a830e41d3
commit bcb60111b2
2 changed files with 22 additions and 11 deletions

View File

@ -25,7 +25,7 @@ class PhotosApiV1(object):
@cherrypy.expose
def index(self):
yield f"<plaintext>hello, this is the api. my database is: {db()}\n"
yield f"<plaintext>hello, this is the api. my database is: {db}\n"
@cherrypy.expose
def upload(self, files, meta):
@ -34,7 +34,7 @@ class PhotosApiV1(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def byhash(self, sha):
f = db().query(Photo).filter(Photo.hash == sha).first()
f = db.query(Photo).filter(Photo.hash == sha).first()
if not f:
raise cherrypy.HTTPError(404)
return f.to_json()
@ -42,14 +42,14 @@ class PhotosApiV1(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def set(self, uuid):
s = db().query(PhotoSet).filter(PhotoSet.uuid == uuid).first()
s = db.query(PhotoSet).filter(PhotoSet.uuid == uuid).first()
if not s:
raise cherrypy.HTTPError(404)
return s.to_json()
@cherrypy.expose
def download(self, uuid):
f = db().query(Photo).filter(Photo.uuid == uuid).first()
f = db.query(Photo).filter(Photo.uuid == uuid).first()
if not f:
raise cherrypy.HTTPError(404)
return cherrypy.lib.static.serve_file(os.path.abspath(os.path.join("./library", f.path)),
@ -59,16 +59,16 @@ class PhotosApiV1(object):
@cherrypy.tools.json_out()
def user(self, username=None, password_hash=None):
if username is None: # list all users
return [u.to_json() for u in db().query(User).all()]
return [u.to_json() for u in db.query(User).all()]
elif username and cherrypy.request.method == "DELETE": # delete user
u = db().query(User).filter(User.name == username).first()
u = db.query(User).filter(User.name == username).first()
if not u:
raise cherrypy.HTTPError(404)
db().delete(u)
db.delete(u)
elif username and password_hash: # create/update user
u = db().query(User).filter(User.name == username).first()
u = db.query(User).filter(User.name == username).first()
if u:
u.password = password_hash
else:
db().add(User(name=username, password=password_hash))
db.add(User(name=username, password=password_hash))
return "ok"

View File

@ -7,8 +7,19 @@ from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def db():
return cherrypy.request.db
class DbAlias(object):
"""
This provides a shorter alias for the cherrypy.request.db object, which is a database session created bound to the
current request. Since the `db` attribute doesn't exist until a request is received, we cannot simply reference it
with another variable.
And instance of this class acts as an object proxy to the database object in cherrypy.request.db.
"""
def __getattr__(self, attr):
return getattr(cherrypy.request.db, attr)
db = DbAlias()
class SAEnginePlugin(plugins.SimplePlugin):