本文整理汇总了Python中scatterbrainz.model.meta.Session.commit方法的典型用法代码示例。如果您正苦于以下问题:Python Session.commit方法的具体用法?Python Session.commit怎么用?Python Session.commit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scatterbrainz.model.meta.Session
的用法示例。
在下文中一共展示了Session.commit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: savePlaylistAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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 commit [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 commit [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 commit [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 commit [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 commit [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 commit [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 commit [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: getAlbumArtAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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)
示例10: clearimport
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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()
示例11: getTrackInfoAJAX
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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 commit [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: currentMembersForTrackArtist
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [as 别名]
def currentMembersForTrackArtist(self):
trackid = request.params["trackid"]
track = Session.query(Track).filter_by(id=trackid).one()
# search for triples with subject matching current artist
db_uri = u""
for triple in Session.query(RDFTriple).filter_by(artistid=track.artistid):
if triple.subject == ":artist":
if triple.predicate == "hasdbpedia":
db_uri = triple.obj
if db_uri == "":
art_mbid = track.artist.mbid
db_uri = sDB.dbpedia_from_MBID(art_mbid)
db_unicode = unicode(db_uri.__str__())
artist = track.artist
triple = RDFTriple(
subject=u":artist", predicate=u"hasdbpedia", obj=db_unicode, artist=artist, track=None, album=None
)
Session.save(triple)
Session.commit()
g = Graph()
g.parse(db_uri)
pmem_re = re.compile("pastmember", re.I)
cmem_re = re.compile("currentmember", re.I)
out = {}
past_members = []
current_members = []
for s, p, o in g.triples((None, None, None)):
if re.search(pmem_re, p):
past_members.append(getURILabel(o))
if re.search(cmem_re, p):
current_members.append(getURILabel(o))
out["past_members"] = past_members
out["current_members"] = current_members
return sjson.dumps(out)
示例14: create
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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})
示例15: setup_app
# 需要导入模块: from scatterbrainz.model.meta import Session [as 别名]
# 或者: from scatterbrainz.model.meta.Session import commit [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()