本文整理汇总了Python中scatterbrainz.model.meta.Session.begin方法的典型用法代码示例。如果您正苦于以下问题:Python Session.begin方法的具体用法?Python Session.begin怎么用?Python Session.begin使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scatterbrainz.model.meta.Session
的用法示例。
在下文中一共展示了Session.begin方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: savePlaylistAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def savePlaylistAJAX(self):
playlistname = request.params['name']
trackids = simplejson.loads(request.params['trackids'])
trackids = map(lambda x: x.replace('track_',''), trackids)
results = Session.query(Track, MBRecording).join(MBRecording).filter(Track.id.in_(trackids)).all()
results.sort(lambda a,b: cmp(trackids.index(a[0].id), trackids.index(b[0].id)))
recordings = map(itemgetter(1), results)
Session.begin()
user_name = request.environ['repoze.what.credentials']['repoze.what.userid']
user_id = Session.query(User).filter(User.user_name==user_name).one().user_id
playlist = Session.query(Playlist) \
.filter(Playlist.owner_id==user_id) \
.filter(Playlist.name==playlistname) \
.first()
if not trackids:
if playlist is None:
return '{}'
else:
Session.delete(playlist)
else:
if playlist is None:
playlist = Playlist(user_id, playlistname)
Session.add(playlist)
else:
playlist.modified = datetime.now()
playlist.tracks = recordings
Session.commit()
return '{}'
示例2: getLyricsAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def getLyricsAJAX(self):
trackid = request.params['trackid'].split('_')[1]
track = Session.query(Track).filter_by(id=trackid).one()
if not track.lyrics and \
(track.lastHitLyricWiki is None or \
datetime.now() > track.lastHitLyricWiki + timedelta(days=10)):
track.lastHitLyricWiki = datetime.now()
title = track.id3title
artist = track.id3artist
params = {
'artist' : artist,
'song' : title,
'fmt' : 'json',
}
url = 'http://lyrics.wikia.com/api.php?%s' % urllib.urlencode(params)
html = urllib.urlopen(url).read()
if not "'lyrics':'Not found'" in html:
search = re.search("'url':'(?P<url>.*?)'",html)
lyricurl = urllib.unquote(search.group('url'))
lyrichtml = urllib.urlopen(lyricurl).read()
lyrics = re.search("<div class='lyricbox'>.*?</div>(?P<lyrics>.*?)<!-- \n", lyrichtml).group('lyrics')
lyrics = unescape(lyrics)
track.lyrics = lyrics
Session.begin()
Session.commit()
json = {}
if track.lyrics:
json['lyrics'] = track.lyrics
return simplejson.dumps(json)
示例3: saveLyricsFramesAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def saveLyricsFramesAJAX(self):
trackid = request.params['trackid']
recordedFrames = simplejson.loads(request.params['frames']) # list of (time, lyrics line index) pairs
recordedFrames.sort(key = itemgetter(0)) # (sort by time)
Session.begin()
track = Session.query(Track).filter_by(id=trackid).one()
track.lyricsFrames = recordedFrames
Session.commit()
示例4: clearAlbumArt
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def clearAlbumArt(self):
id = request.params['id']
Session.begin()
album = Session.query(Album).filter_by(id=id).one()
album.albumArtFilename = None
album.lastHitAlbumArtExchange = None
Session.commit()
return 'Cleared album art for ' + album.artist.name + ' - ' + album.name
示例5: setAlbumArt
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def setAlbumArt(self):
id = request.params['id']
url = request.params['url']
Session.begin()
album = Session.query(Album).filter_by(id=id).one()
album.albumArtFilename = albumart._fetchAlbumArt(album.artist.name, album.name, url)
Session.commit()
return 'Set album art for ' + album.artist.name + ' - ' + album.name + ' to ' + url + ', saved to ' + album.albumArtFilename
示例6: invite
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def invite(self):
if request.POST:
who = request.params['who']
c.code = ''.join(random.choice(string.letters + string.digits) for i in xrange(32))
invite = Invite(who, c.code)
Session.begin()
Session.add(invite)
Session.commit()
return render('/display-invite.html')
else:
return render('/create-invite.html')
示例7: makeRandom
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def makeRandom(self):
user_name = request.environ['repoze.what.credentials']['repoze.what.userid']
user = Session.query(User).filter(User.user_name==user_name).one()
Session.begin()
for i in range(10):
info = BenKVP(owner = user,
key = 'random_key_{0}'.format(i),
value = 'random_value_{0}'.format(i))
Session.add(info)
Session.commit()
return 'success'
示例8: getLyricsAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def getLyricsAJAX(self):
trackid = request.params['trackid'].split('_')[1]
track = Session.query(Track).filter_by(id=trackid).one()
ip = request.environ['REMOTE_ADDR']
user_name = request.environ['repoze.what.credentials']['repoze.what.userid']
user = Session.query(User).filter(User.user_name==user_name).one()
Session.begin()
play = TrackPlay(track.mbid, user, ip)
Session.add(play)
Session.commit()
lyrics = lyricsservice.get_lyrics(Session, track)
if lyrics:
return simplejson.dumps({'lyrics' : lyrics})
else:
return '{}'
示例9: clearimport
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def clearimport(download):
with importlock:
assert not download.isdone, 'download is already done'
assert download.failedimport, 'import isnt failed'
mbid = download.release_group_mbid
dirpath = mbid[:2] + '/' + mbid
cmd = 'rm -rf ' + Config.MUSIC_PATH + dirpath
log.info('running ' + cmd)
os.system(cmd)
if Config.SCP_SHOP_DOWNLOADS:
cmd = 'rm -rf ' + Config.SCP_FOLDER + '/' + download.infohash
log.info('running ' + cmd)
os.system(cmd)
Session.begin()
download.failedimport = False
download.importtrace = None
Session.commit()
示例10: getAlbumArtAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def getAlbumArtAJAX(self):
trackid = request.params['trackid'].split('_')[1]
track = Session.query(Track).filter_by(id=trackid).one()
if not track.album.albumArtFilename and ( \
track.album.lastHitAlbumArtExchange is None \
or datetime.now() > track.album.lastHitAlbumArtExchange + timedelta(days=10)):
track.album.lastHitAlbumArtExchange = datetime.now()
album = track.album.name
artist = track.album.artist.name
if artist == 'Various Artists':
q = album
else:
q = (artist + ' ' + album)
q = q.replace("'","")
site = 'http://www.albumartexchange.com'
params = {
'grid' : '2x7',
'sort' : 7,
'q' : q,
}
url = site + '/covers.php?%s' % urllib.urlencode(params)
html = urllib.urlopen(url).read()
search = re.search('src="/phputil/scale_image.php\?size=150&src=(?P<src>.*?)"',html)
if search:
image = site + urllib.unquote(search.group('src'))
extension = image.rsplit('.', 1)[1]
delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())
delchars = delchars.translate(None," ()'&!-+_.")
filename = (artist + ' - ' + album).encode('utf-8').translate(None, delchars) + '.' + extension
urllib.urlretrieve(image, 'scatterbrainz/public/art/' + filename)
albumArt = '/art/' + filename
track.album.albumArtFilename = albumArt
Session.begin()
Session.commit()
json = {}
if track.album.albumArtFilename:
json['albumArtURL'] = track.album.albumArtFilename
return simplejson.dumps(json)
示例11: getTrackInfoAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def getTrackInfoAJAX(self):
trackid = request.params['trackid'].split('_')[1]
track = Session.query(Track).filter_by(id=trackid).one()
(artistName, albumName, trackName) = (track.id3artist, track.id3album, track.id3title)
log.info(request.remote_addr + ' playing ' + artistName + ' - ' + trackName)
if (not track.artist.mbid or not track.album.mbid or not track.album.asin) and \
(track.album.lastHitMusicbrainz is None \
or datetime.now() > track.album.lastHitMusicbrainz + timedelta(days=10)):
track.album.lastHitMusicbrainz = datetime.now()
album = track.album
artist = album.artist
release = None
if album.mbid:
release = getRelease(album.mbid)
else:
if artist.name == 'Various Artists':
release = searchRelease(None, album.name)
else:
if artist.name.startswith('The') or artist.name.startswith('the') or artist.name.startswith('THE'):
artistSearch = artist.name[4:]
else:
artistSearch = artist.name
release = searchRelease(artistSearch, album.name)
if release and not album.mbid:
album.mbid = release.id.split('/')[-1]
if release and not artist.mbid:
artist.mbid = release.artist.id.split('/')[-1]
if release:
albumName = release.title
asin = release.getAsin()
if asin:
track.album.asin = asin
if release.artist:
artistName = release.artist.name
Session.begin()
Session.commit()
json = {}
json['artist'] = artistName
json['album'] = albumName
json['track'] = trackName
if track.album.asin:
json['asin'] = track.album.asin
return simplejson.dumps(json)
示例12: run
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def run(self):
# Only let one worker run via pg advisory lock
acquired = Session.execute(select([func.pg_try_advisory_lock(importlockid)])).fetchone()[0]
threadid = 'PID ' + str(os.getpid()) + ' thread ' + str(threading.current_thread())
if acquired:
log.info('[shop worker] %s acquired lock, starting..' % threadid)
else:
return
pendingdownloads = False
while True:
try:
downloads = Session.query(ShopDownload) \
.filter(ShopDownload.isdone==False) \
.filter(ShopDownload.failedimport==False) \
.all()
pendingdownloads = len(downloads) != 0
if pendingdownloads:
rtorrent = xmlrpclib.ServerProxy(Config.SHOP_RPC_URL)
for download in downloads:
try:
infohash = download.infohash
iscomplete = rtorrent.d.get_complete(infohash) == 1
if iscomplete:
shopservice.importDownload(download)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
importtrace = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
log.error('[shop worker] caught exception in loop ' + importtrace)
Session.rollback()
Session.begin()
download.failedimport = True
download.importtrace = importtrace
Session.commit()
except Exception as e:
log.error('[shop worker] caught exception out of loop ' + repr(e))
Session.rollback()
if pendingdownloads:
time.sleep(10)
else:
time.sleep(30)
示例13: create
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def create(self):
usr = request.params['login']
if Session.query(User).filter_by(user_name=usr).count() > 0:
return simplejson.dumps({'success':False,'msg':'That username is already taken, sorry.'})
pwd = request.params['pass']
if len(usr) < 3 or len(pwd) < 3:
return simplejson.dumps({'success':False,'msg':'Your username and password must each be at least 3 characters.'})
code = request.params['code']
invite = Session.query(Invite).filter_by(code=code).first()
if invite is None:
return simplejson.dumps({'success':False,'msg':'Your registration code appears to be invalid.'})
user = User()
user.who = invite.who
user.user_name = usr
user.password = pwd
user.registered = datetime.now()
Session.begin()
user.groups = [Session.query(Group).filter_by(group_name='users').one()]
Session.delete(invite)
Session.add(user)
Session.commit()
return simplejson.dumps({'success':True})
示例14: setup_app
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def setup_app(command, conf, vars):
"""Place any commands to setup scatterbrainz here"""
load_environment(conf.global_conf, conf.local_conf)
# Create the tables if they don't already exist
log.info("Creating tables")
meta.metadata.create_all(bind=meta.engine)
log.info("Tables created")
session = Session()
session.begin()
loginPerm = Permission()
loginPerm.permission_name = u'login'
adminPerm = Permission()
adminPerm.permission_name = u'admin'
adminGroup = Group()
adminGroup.group_name = u'admins'
adminGroup.permissions = [loginPerm, adminPerm]
userGroup = Group()
userGroup.group_name = u'users'
userGroup.permissions = [loginPerm]
admin = User()
admin.user_name = u'admin'
admin.password = u'default'
admin.who = u'admin'
admin.registered = datetime.now()
admin.groups = [adminGroup]
session.add_all([loginPerm, adminPerm, adminGroup, userGroup, admin])
session.commit()
示例15: load
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import begin [as 别名]
def load(self):
commit = 'commit' in request.params and request.params['commit'] == 'true'
s = ''
if commit:
Session.begin()
now = datetime.now()
initialLoad = True #Session.query(AudioFile).count() == 0
if initialLoad:
s = _msg(s, 'Initial track loading!')
else:
s = _msg(s, 'Updating tracks!')
then = now
missing = 0
changed = 0
for track in Session.query(AudioFile):
path = os.path.join(MUSIC, track.filepath)
if os.path.exists(path):
size = os.path.getsize(path)
mtime = datetime.fromtimestamp(os.path.getmtime(path))
if size != track.filesize or mtime != track.filemtime:
changed = changed + 1
s = _msg(s, 'Modified file: ' + path)
if commit:
raise Exception('not implemented!')
else:
s = _msg(s, 'Deleted file: ' + path)
missing = missing + 1
if commit:
Session.delete(track)
s = _msg(s, 'Found ' + str(missing) + ' missing files and ' + str(changed) + ' modified files, took ' + \
str(datetime.now() - then))
then = datetime.now()
filepaths = set(map(lambda t: t.filepath, Session.query(AudioFile)))
s = _msg(s, 'Querying for all filepaths took ' + str(datetime.now() - then))
then = datetime.now()
added = 0
skippedNoMBID = 0
release_groups_added = set()
unknownrelease = set()
unknownrecording = set()
alreadyhaverecordingrelease = set()
alreadyhavereleasegroup = set()
unicodeproblems = set()
fuckedmp3s = set()
for dirname, dirnames, filenames in os.walk(INCOMING, followlinks=True):
for filename in filenames:
if not os.path.splitext(filename)[-1].lower() == '.mp3':
continue
try:
filepath = os.path.join(os.path.relpath(dirname, INCOMING), filename).decode('utf-8')
except UnicodeDecodeError:
log.error('unicode problem ' + os.path.join(os.path.relpath(dirname, INCOMING), filename))
unicodeproblems.add(os.path.join(os.path.relpath(dirname, INCOMING), filename))
continue
if not initialLoad and filepath in filepaths:
continue
if not initialLoad:
s = _msg(s, 'New file: ' + filepath)
if not commit:
continue
# get size, date
fileabspath = os.path.join(dirname,filename)
filesize = os.path.getsize(fileabspath)
filemtime = datetime.fromtimestamp(os.path.getmtime(fileabspath))
# mp3 length, bitrate, etc.
try:
mutagen = MP3(fileabspath)
except:
fuckedmp3s.add(fileabspath)
log.error('fucked mp3 ' + fileabspath)
continue
info = mutagen.info
mp3bitrate = info.bitrate
mp3samplerate = info.sample_rate
mp3length = int(round(info.length))
if info.sketchy:
fuckedmp3s.add(fileabspath)
log.error('sketchy mp3! ' + fileabspath)
continue
# brainz!!
if RECORDING_MBID_KEY not in mutagen:
#.........这里部分代码省略.........