1
0
mirror of https://github.com/spl0k/supysonic.git synced 2024-11-15 06:32:16 +00:00

add flask-sqlalchemy library to handle session management better

rid of those mysql server gone away messages/etc
This commit is contained in:
Emory P 2013-12-14 19:50:12 -05:00
parent ade6dca8fd
commit a1e430c0da
5 changed files with 43 additions and 55 deletions

View File

@ -90,7 +90,7 @@ def show_directory():
if not status: if not status:
return res return res
res.tracks = [t for t in res.tracks if os.path.isfile(t.path)] res.tracks = [t for t in res.tracks if os.path.isfile(t.path)]
directory = { directory = {
'id': str(res.id), 'id': str(res.id),

76
db.py
View File

@ -2,27 +2,29 @@
import config import config
from sqlalchemy import create_engine, Table, Column, ForeignKey, func from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Integer, String, Boolean, DateTime
from sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.types import TypeDecorator, BINARY from sqlalchemy.types import TypeDecorator, BINARY
from sqlalchemy.dialects.postgresql import UUID as pgUUID from sqlalchemy.dialects.postgresql import UUID as pgUUID
import uuid, datetime, time import uuid, datetime, time
import os.path import os.path
Base = declarative_base() database = SQLAlchemy()
if config.get('base', 'debug'): session = database.session
engine = create_engine(config.get('base', 'database_uri'), convert_unicode = True, echo = True)
else: Column = database.Column
engine = create_engine(config.get('base', 'database_uri'), convert_unicode = True) Table = database.Table
String = database.String
ForeignKey = database.ForeignKey
func = database.func
Integer = database.Integer
Boolean = database.Boolean
DateTime = database.DateTime
relationship = database.relationship
backref = database.backref
session = scoped_session(sessionmaker(autoflush = False, bind = engine))
Base.query = session.query_property()
class UUID(TypeDecorator): class UUID(TypeDecorator):
"""Platform-somewhat-independent UUID type """Platform-somewhat-independent UUID type
@ -69,8 +71,7 @@ def now():
return datetime.datetime.now().replace(microsecond = 0) return datetime.datetime.now().replace(microsecond = 0)
class User(Base): class User(database.Model):
__tablename__ = 'user'
id = UUID.gen_id_column() id = UUID.gen_id_column()
name = Column(String(64), unique = True) name = Column(String(64), unique = True)
@ -103,16 +104,14 @@ class User(Base):
'shareRole': False 'shareRole': False
} }
class ClientPrefs(Base): class ClientPrefs(database.Model):
__tablename__ = 'client_prefs'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
client_name = Column(String(32), nullable = False, primary_key = True) client_name = Column(String(32), nullable = False, primary_key = True)
format = Column(String(8), nullable = True) format = Column(String(8), nullable = True)
bitrate = Column(Integer, nullable = True) bitrate = Column(Integer, nullable = True)
class Folder(Base): class Folder(database.Model):
__tablename__ = 'folder'
id = UUID.gen_id_column() id = UUID.gen_id_column()
root = Column(Boolean, default = False) root = Column(Boolean, default = False)
@ -152,8 +151,7 @@ class Folder(Base):
return info return info
class Artist(Base): class Artist(database.Model):
__tablename__ = 'artist'
id = UUID.gen_id_column() id = UUID.gen_id_column()
name = Column(String(255), nullable=False) name = Column(String(255), nullable=False)
@ -173,8 +171,7 @@ class Artist(Base):
return info return info
class Album(Base): class Album(database.Model):
__tablename__ = 'album'
id = UUID.gen_id_column() id = UUID.gen_id_column()
name = Column(String(255)) name = Column(String(255))
@ -204,8 +201,7 @@ class Album(Base):
year = min(map(lambda t: t.year if t.year else 9999, self.tracks)) year = min(map(lambda t: t.year if t.year else 9999, self.tracks))
return '%i%s' % (year, self.name.lower()) return '%i%s' % (year, self.name.lower())
class Track(Base): class Track(database.Model):
__tablename__ = 'track'
id = UUID.gen_id_column() id = UUID.gen_id_column()
disc = Column(Integer) disc = Column(Integer)
@ -289,8 +285,7 @@ class Track(Base):
def sort_key(self): def sort_key(self):
return (self.album.artist.name + self.album.name + ("%02i" % self.disc) + ("%02i" % self.number) + self.title).lower() return (self.album.artist.name + self.album.name + ("%02i" % self.disc) + ("%02i" % self.number) + self.title).lower()
class StarredFolder(Base): class StarredFolder(database.Model):
__tablename__ = 'starred_folder'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
starred_id = Column(UUID, ForeignKey('folder.id'), primary_key = True) starred_id = Column(UUID, ForeignKey('folder.id'), primary_key = True)
@ -299,8 +294,7 @@ class StarredFolder(Base):
user = relationship('User') user = relationship('User')
starred = relationship('Folder') starred = relationship('Folder')
class StarredArtist(Base): class StarredArtist(database.Model):
__tablename__ = 'starred_artist'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
starred_id = Column(UUID, ForeignKey('artist.id'), primary_key = True) starred_id = Column(UUID, ForeignKey('artist.id'), primary_key = True)
@ -309,8 +303,7 @@ class StarredArtist(Base):
user = relationship('User') user = relationship('User')
starred = relationship('Artist') starred = relationship('Artist')
class StarredAlbum(Base): class StarredAlbum(database.Model):
__tablename__ = 'starred_album'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
starred_id = Column(UUID, ForeignKey('album.id'), primary_key = True) starred_id = Column(UUID, ForeignKey('album.id'), primary_key = True)
@ -319,8 +312,7 @@ class StarredAlbum(Base):
user = relationship('User') user = relationship('User')
starred = relationship('Album') starred = relationship('Album')
class StarredTrack(Base): class StarredTrack(database.Model):
__tablename__ = 'starred_track'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
starred_id = Column(UUID, ForeignKey('track.id'), primary_key = True) starred_id = Column(UUID, ForeignKey('track.id'), primary_key = True)
@ -329,8 +321,7 @@ class StarredTrack(Base):
user = relationship('User') user = relationship('User')
starred = relationship('Track') starred = relationship('Track')
class RatingFolder(Base): class RatingFolder(database.Model):
__tablename__ = 'rating_folder'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
rated_id = Column(UUID, ForeignKey('folder.id'), primary_key = True) rated_id = Column(UUID, ForeignKey('folder.id'), primary_key = True)
@ -339,8 +330,7 @@ class RatingFolder(Base):
user = relationship('User') user = relationship('User')
rated = relationship('Folder') rated = relationship('Folder')
class RatingTrack(Base): class RatingTrack(database.Model):
__tablename__ = 'rating_track'
user_id = Column(UUID, ForeignKey('user.id'), primary_key = True) user_id = Column(UUID, ForeignKey('user.id'), primary_key = True)
rated_id = Column(UUID, ForeignKey('track.id'), primary_key = True) rated_id = Column(UUID, ForeignKey('track.id'), primary_key = True)
@ -349,8 +339,7 @@ class RatingTrack(Base):
user = relationship('User') user = relationship('User')
rated = relationship('Track') rated = relationship('Track')
class ChatMessage(Base): class ChatMessage(database.Model):
__tablename__ = 'chat_message'
id = UUID.gen_id_column() id = UUID.gen_id_column()
user_id = Column(UUID, ForeignKey('user.id')) user_id = Column(UUID, ForeignKey('user.id'))
@ -366,13 +355,12 @@ class ChatMessage(Base):
'message': self.message 'message': self.message
} }
playlist_track_assoc = Table('playlist_track', Base.metadata, playlist_track_assoc = Table('playlist_track', database.Model.metadata,
Column('playlist_id', UUID, ForeignKey('playlist.id')), Column('playlist_id', UUID, ForeignKey('playlist.id')),
Column('track_id', UUID, ForeignKey('track.id')) Column('track_id', UUID, ForeignKey('track.id'))
) )
class Playlist(Base): class Playlist(database.Model):
__tablename__ = 'playlist'
id = UUID.gen_id_column() id = UUID.gen_id_column()
user_id = Column(UUID, ForeignKey('user.id')) user_id = Column(UUID, ForeignKey('user.id'))
@ -399,8 +387,8 @@ class Playlist(Base):
return info return info
def init_db(): def init_db():
Base.metadata.create_all(bind = engine) database.create_all()
def recreate_db(): def recreate_db():
Base.metadata.drop_all(bind = engine) database.drop_all()
Base.metadata.create_all(bind = engine) database.create_all()

View File

@ -13,6 +13,5 @@ if __name__ == '__main__':
import db import db
from web import app from web import app
db.init_db()
app.run(host = '0.0.0.0', debug = True) app.run(host = '0.0.0.0', debug = True)

View File

@ -10,8 +10,5 @@ if not config.check():
if not os.path.exists(config.get('base', 'cache_dir')): if not os.path.exists(config.get('base', 'cache_dir')):
os.makedirs(config.get('base', 'cache_dir')) os.makedirs(config.get('base', 'cache_dir'))
import db
db.init_db()
from web import app as application from web import app as application

16
web.py
View File

@ -7,10 +7,11 @@ app = Flask(__name__)
app.secret_key = '?9huDM\\H' app.secret_key = '?9huDM\\H'
if(config.get('base', 'accel-redirect')): if(config.get('base', 'accel-redirect')):
app.use_x_sendfile = True app.use_x_sendfile = True
if config.get('base', 'debug'): if config.get('base', 'debug'):
app.debug = True app.debug = True
app.config['SQLALCHEMY_ECHO'] = True
if config.get('base', 'log_file'): if config.get('base', 'log_file'):
import logging import logging
@ -19,7 +20,14 @@ if config.get('base', 'log_file'):
handler.setLevel(logging.DEBUG) handler.setLevel(logging.DEBUG)
app.logger.addHandler(handler) app.logger.addHandler(handler)
app.config['SQLALCHEMY_DATABASE_URI'] = config.get('base', 'database_uri')
import db import db
db.database.init_app(app)
with app.app_context():
db.init_db()
from managers.user import UserManager from managers.user import UserManager
@app.before_request @app.before_request
@ -39,10 +47,6 @@ def login_check():
flash('Please login') flash('Please login')
return redirect(url_for('login', returnUrl = request.script_root + request.url[len(request.url_root)-1:])) return redirect(url_for('login', returnUrl = request.script_root + request.url[len(request.url_root)-1:]))
@app.teardown_request
def teardown(exception):
db.session.remove()
@app.template_filter('str') @app.template_filter('str')
def to_string(obj): def to_string(obj):
return str(obj) return str(obj)