• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python webservice.Query类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中musicbrainz2.webservice.Query的典型用法代码示例。如果您正苦于以下问题:Python Query类的具体用法?Python Query怎么用?Python Query使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Query类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: FetchTrackListByArtistRelease

    def FetchTrackListByArtistRelease(self, string_artist_name, string_release_name):
      musicbrainz_query = Query()
      try:
        # Search for all releases matching the given name. Limit the results
        # to the first best matches.

        string_release_id = ""
        string_release_title = ""

        musicbrainz_release_filter = ReleaseFilter(title=string_release_name, artistName=string_artist_name, limit=1)
        musicbrainz_release_results = musicbrainz_query.getReleases(musicbrainz_release_filter)
        if musicbrainz_release_results is not None:
          if len(musicbrainz_release_results) > 0:
            string_release_id = musicbrainz_release_results[0].getRelease().getId()
            string_release_title = musicbrainz_release_results[0].getRelease().getTitle()
            include_info = ReleaseIncludes(artist=True, tracks=True)
            release = self.__musicbrainz_query__.getReleaseById(string_release_id, include_info)

            track_list = []

            for track in release.getTracks():
                track_title = track.getTitle()
                for escape_char in self.__escape_list__:
                    track_title = track_title.replace(escape_char, "")
                track_list.append(track_title)

        return string_release_title, track_list

      except WebServiceError, e:
          # print 'Error:', e
          return []
开发者ID:aish9r,项目名称:ytpls,代码行数:31,代码来源:VideoProviders.py


示例2: getReleases

    def getReleases(self, artistResult):
        q = Query()

        offset = 0
        limit = 100
        releaseResults = set()
        while True:
            try:
                f = ReleaseFilter(artistId = 
                        artistResult.getKey(MusicbrainzSource._sourceName),
                        offset = offset, limit = limit)
                results = q.getReleases(f)
            except WebServiceError, e:
                raise SourceError

            count = len(results)

            results = filter(lambda res: res.getScore() == 100, results)

            for r in results:
                rr = ReleaseResult(title = r.getRelease().getTitle(),
                        date = r.getRelease().getEarliestReleaseDate(),
                        tracksCount = r.getRelease().getTracksCount())
                rr.setKey(MusicbrainzSource._sourceName, r.getRelease().getId())
                releaseResults.add(rr)

            if count < limit:
                break
            offset += count
开发者ID:xffox,项目名称:relcol,代码行数:29,代码来源:musicbrainz_source.py


示例3: __init__

	def __init__(self,wait=1) :
		if not os.path.isdir(CACHE_DIR) :
			os.mkdir(CACHE_DIR)
			os.mkdir(os.path.join(CACHE_DIR,'artist_q'))
			os.mkdir(os.path.join(CACHE_DIR,'release_q'))
			os.mkdir(os.path.join(CACHE_DIR,'track_q'))
		self.wait = wait
		self.last_called = time.time()
		Query.__init__(self)
开发者ID:apassant,项目名称:motools,代码行数:9,代码来源:CachedMBZQuery.py


示例4: populate_album_set

 def populate_album_set(self):
     """
     Find and create models for all albums released by this artist.
     Only albums with an Amazon ASIN are imported, to try and stop the
     database getting clogged up with b-sides, remixes, and bonus
     material.
     """
     # We can't do anything without the MusicBrainz and Last.fm libraries.
     try:
         ReleaseFilter
     except NameError:
         return False
     # Find any official album release held by MusicBrainz for this artist.
     filter = ReleaseFilter(artistName=self.name, releaseTypes=(Release.TYPE_ALBUM,
         Release.TYPE_OFFICIAL))
     query = Query()
     releases = query.getReleases(filter)
     for release in releases:
         album = release.release
         # Only import albums with an Amazon ASIN.  That allows for some
         # quality-control as Music Brainz lists every B-side and bonus
         # material you can think of.
         if album.asin:
             # First try and find an already-existing album with this ASIN
             # As an ASIN is unique it means we'll find it even if the fields
             # have been changed since creation.
             try:
                 db_album = Album.objects.get(asin=album.asin)
             except Album.DoesNotExist:
                 db_album = Album(artist=self, title=album.title,
                     asin=album.asin, mbid=album.id.rsplit("/", 1)[1])
                 # MusicBrainz stores releases dates for as many countries as
                 # it can.  I'm only interested in Britain though, so look
                 # for that first.  As a fallback, us the world wide release
                 # date (XE) or the US release date.
                 release_dates = dict((r.country, r.date)
                     for r in album.releaseEvents)
                 if release_dates:
                     # GB = United Kingdom, XE = world, US = United States.
                     for country in ('GB', 'XE', 'US'):
                         if release_dates.has_key(country):
                             db_album.released_in = country
                             # The release date can be in the format "2010",
                             # "2010-02", or "2010-02-18", so make up the
                             # missing month and/or day so a proper release
                             # date object can be created.
                             release_date = release_dates[country]
                             date_list = map(int, release_date.split('-'))
                             try:
                                 db_album.release_date = datetime.date(
                                     *date_list + [1] * (3 - len(date_list)))
                             except ValueError:
                                 pass  # Date couldn't be parsed.
                             break
                 db_album.save()
开发者ID:flother,项目名称:gigs,代码行数:55,代码来源:models.py


示例5: lookup_puid

	def lookup_puid(self,_puid):
		q = Query()
		f = TrackFilter(puid=_puid)
		try :
			r = q.getTracks(f)
			track = r[0].track
			return track
		except:
			print 'MusicBrainz::lookup_puid: Error finding track metadata.'
			# raise AssertionError('MusicBrainz::lookup_puid: Error finding track metadata.')
			return None
开发者ID:alonbee,项目名称:sawa,代码行数:11,代码来源:sawebapp.py


示例6: testRemoveFromUserCollection

	def testRemoveFromUserCollection(self):
		ws = FakeWebService()
		q = Query(ws)

		r1 = "9e186398-9ae2-45bf-a9f6-d26bc350221e"
		r2 = "http://musicbrainz.org/release/6b050dcf-7ab1-456d-9e1b-c3c41c18eed2"
		r3 = Release("d3cc336e-1010-4252-9091-7923f0429824")

		q.removeFromUserCollection([r1, r2, r3])
		self.assertEquals(len(ws.data), 1)
		res = ws.data[0]
		self.assertEquals(res[0], "collection")
		self.assertEquals(res[2], "remove=9e186398-9ae2-45bf-a9f6-d26bc350221e%2C6b050dcf-7ab1-456d-9e1b-c3c41c18eed2%2Cd3cc336e-1010-4252-9091-7923f0429824")
开发者ID:apotapov,项目名称:musicproject,代码行数:13,代码来源:test_ws_query.py


示例7: testSubmitPuid

	def testSubmitPuid(self):
		tracks2puids = {
					    '6a47088b-d9e0-4088-868a-394ee3c6cd33':'c2a2cee5-a8ca-4f89-a092-c3e1e65ab7e6', 
					    'b547acbc-58c6-4a31-9806-e2348db3a167':'c2a2cee5-a8ca-4f89-a092-c3e1e65ab7e6'
		}
		ws = FakeWebService()
		q = Query(ws, clientId='test-1')
		
		q.submitPuids(tracks2puids)
		
		self.assertEquals(len(ws.data), 1)
		req = ws.data[0]
		qstring = 'client=test-1&puid=6a47088b-d9e0-4088-868a-394ee3c6cd33+c2a2cee5-a8ca-4f89-a092-c3e1e65ab7e6&puid=b547acbc-58c6-4a31-9806-e2348db3a167+c2a2cee5-a8ca-4f89-a092-c3e1e65ab7e6'
		self.assertEquals(req[0], 'track')
		self.assertEquals(req[2], qstring)
开发者ID:apotapov,项目名称:musicproject,代码行数:15,代码来源:test_ws_query.py


示例8: testSubmitIsrc

	def testSubmitIsrc(self):
		tracks2isrcs = {
					    '6a47088b-d9e0-4088-868a-394ee3c6cd33':'NZABC0800001', 
					    'b547acbc-58c6-4a31-9806-e2348db3a167':'NZABC0800002'
		}
		ws = FakeWebService()
		q = Query(ws)
		
		q.submitISRCs(tracks2isrcs)
		
		self.assertEquals(len(ws.data), 1)
		req = ws.data[0]
		qstring = 'isrc=6a47088b-d9e0-4088-868a-394ee3c6cd33+NZABC0800001&isrc=b547acbc-58c6-4a31-9806-e2348db3a167+NZABC0800002'
		self.assertEquals(req[0], 'track')
		self.assertEquals(req[2], qstring)
开发者ID:apotapov,项目名称:musicproject,代码行数:15,代码来源:test_ws_query.py


示例9: find_releases

def find_releases(puid):
    """Given a track's puid, return a list of
      (track-no, track, release)
    for each release that the song appeared on on."""
    query = Query()
    trackfilter = TrackFilter(puid=puid)
    results = query.getTracks(trackfilter)

    out = []
    for result in results:
        track = result.track
        rels = track.getReleases()
        assert len(rels) == 1
        rel = rels[0]
        out.append((rel.getTracksOffset()+1, track, rel))
    return out
开发者ID:emnh,项目名称:namingmuse,代码行数:16,代码来源:mbrainz2.py


示例10: find_releases

def find_releases(puid):
    """
	Given a track's puid, return a list of
	(track-no, track, release)
	for each release that the song appeared on on.
	"""
    service = get_service()
    q = Query(service)
    f = TrackFilter(puid=puid)
    results = None
    while results == None:
        try:
            results = q.getTracks(f)
        except WebServiceError, e:
            print "!! WebServiceError: ", e
            print "!! Retry in 5 seconds..."
            time.sleep(5)
开发者ID:rain0r,项目名称:brainwash,代码行数:17,代码来源:brainwash.py


示例11: print_release

def print_release(mbid):
	q = Query()
	i = ReleaseIncludes(
		artist=True,
		tracks=True,
		urlRelations=True
	)

	rel = q.getReleaseById(mbid, i)
	if not rel:
		print 'Not found :/'
		return

	print 'Title:  %s' % rel.title
	print 'Artist: %s' % rel.artist.name
	print ''
	for no, trk in enumerate(rel.tracks):
		print '	  %d. %s' % ((no+1), trk.title)
开发者ID:rain0r,项目名称:brainwash,代码行数:18,代码来源:mb_showrel.py


示例12: guess_release

def guess_release(folder, files):
	nfiles = []
	cache = musicdns.cache.MusicDNSCache()
	print "Fingerprinting..."
	for fn in files:
		try:
			puid, _ = cache.getpuid(fn, MUSICDNS_KEY)
		except IOError:
			puid = None
		track = filename_track_number(fn)
		nfiles += [(track, fn, puid)]
	nfiles.sort()

	matchrel = defaultdict(int)
	for i, (no, fn, puid) in enumerate(nfiles):
		print 'Asking MusicBrainz about ' + basename(fn)
		if puid is None:
			continue
		for tno, track, release in find_releases(puid):
			included = 0
			if no == tno:
				matchrel[release.id] += 1
				included = 1
			print u'	%d - %s - %s %s' % (tno, track.title, release.title, ' <=' if included else '')

	q = Query()
	i = ReleaseIncludes(
		artist=True,
		tracks=True,
		urlRelations=True
	)
	releaseids = sorted(matchrel.iteritems(), key=itemgetter(1), reverse=1)

	if not releaseids:
		return None

	releases = None
	while not releases:
		try:
			releases = [(q.getReleaseById(rid, i), freq) for rid, freq in releaseids]
		except WebServiceError, e:
			print '!! WebServiceError: ', e
			print '!! Retry in 5 seconds...'
			time.sleep(5)
开发者ID:rain0r,项目名称:brainwash,代码行数:44,代码来源:mb_guess.py


示例13: main

def main(argv=None):
	if argv==None:
		argv=sys.argv
	
	q = Query()
	
	conn = sqlite3.connect('db/mu_trumps.sqlite3')
	c = conn.cursor()
	insert_cursor = conn.cursor()
	c.execute('select * from artists')
	
	for artist_id, created, modified, artist_name, artist_url in c:
		try:
			# Search for all artists matching the given name. Limit the results
			# to the best match. 
			f = ArtistFilter(name=artist_name, limit=5)
			artistResults = q.getArtists(f)
		except WebServiceError, e:
			print 'Error:', e
			if "HTTP Error 503" in str(e):
				print "taking a rest..."
				sleep(SLEEP_TIME*10)
			continue
		try:
			mbz_id = artistResults[0].artist.id
		except IndexError:
			print "Could not find a musicbrainz id for the artist", artist_name, "moving on..."
			continue
		if VERBOSE:
			print "For artist", artist_name, "found id", artist_id
		try:
			# The result should include all official albums.
			#
			inc = ws.ArtistIncludes(
				releases=(m.Release.TYPE_OFFICIAL, m.Release.TYPE_ALBUM),
				tags=True, releaseGroups=True)
			artist = q.getArtistById(mbz_id, inc)
		except ws.WebServiceError, e:
			print 'Error:', e
			if "HTTP Error 503" in str(e):
				print "taking a rest..."
				sleep(SLEEP_TIME*10)
			continue
开发者ID:jcoglan,项目名称:mu_trumps,代码行数:43,代码来源:populate_release_data.py


示例14: show_release

def show_release():
    from musicbrainz2.webservice import Query, ArtistFilter, WebServiceError

    import string
    import musicbrainz2.webservice as ws
    import musicbrainz2.model as m
    import musicbrainz2.utils as u
	
    q = Query()
    inc = ws.ReleaseIncludes(artist=True, releaseEvents=True, labels=True,
                                 discs=True, tracks=True)
    rid = u'http://musicbrainz.org/release/52ec1af7-28a1-42e3-896a-0eddc8e338d5.html'
    release = q.getReleaseById(rid, inc)
    tracks = release.tracks
    
    for t in tracks:
        #print dir(t)
        minutes,seconds = divmod(t.duration/1000,60)
        print t.title, '-', string.join([str(minutes),':',str(seconds)],'')
开发者ID:bh0085,项目名称:programming,代码行数:19,代码来源:show_release.py


示例15: find_album_name

def find_album_name( track_details ):
    """Find album name via Musicbrainz API

    Arguments:

    track_details -- dict containing 'Title' and 'Artist'

    Returns album name, empty string if unsuccessful.

    """

    album = ""

    # Musicbrainz limits API calls to one per second from a specific IP
    time.sleep(1.1)

    query = Query()

    # Loop through at most 9 times as the webservice is occasionally busy.
    # Results will not be None if is successful
    i = 1
    results = None
    while (results == None) and (i < 10):
        try:
            tracks = TrackFilter(title=track_details['Title'], 
                                 artistName=track_details['Artist'])
            results = query.getTracks(tracks)
        except (AuthenticationError,
                ConnectionError,
                RequestError,
                ResponseError,
                ResourceNotFoundError,
                WebServiceError) as error:
            print('Error:', error, 'waiting', i*10, 'seconds')
            time.sleep(i*10)
            i += 1
            results = None

    if (results != None) and (len(results) != 0):
        album = find_preferred_album( results )

    return album
开发者ID:alexjh,项目名称:whatson,代码行数:42,代码来源:whats_on_find_album.py


示例16: get_puid_tags

def get_puid_tags(puid):
    """Returns a list of `TagGroup` elements, matching the song's puid"""
    
    global _lastServerCall
    # wait at least a second
    while True:
        currentTime = time.time()
        if currentTime >= _lastServerCall+1:
            _lastServerCall = currentTime
            break
        time.sleep(0.05)

    q = Query()
    res = []
    try:
        f = TrackFilter(puid=puid)
        results = q.getTracks(f)
    except WebServiceError, e:
        print e
        return None
开发者ID:konne88,项目名称:MediaCMN,代码行数:20,代码来源:musicbrainz.py


示例17: sanitize_with_musicBrainz

 def sanitize_with_musicBrainz(self):
     titleName = self['title']
     artistName = self['artist']
     albumName = self['album']
     q = Query()
     try:
         logging.debug("Querying with title:{},artist:{},album:{}"
         .format(titleName, artistName, albumName))
         f = TrackFilter(title=titleName, artistName=artistName,
         releaseTitle=albumName, limit=2)
         results = q.getTracks(f)
         logging.debug("results are " + str(results))
     except WebServiceError as e:
         logging.error("Failed to contact musicbrainz server.")
         if str(e)[:15]=="HTTP Error 503:":
             logging.info("Pausing for a moment, \
             the musicbrainz server doesn't handle too much request")
             sleep(60)
         return self.sanitize_with_musicBrainz()
     self.treat_musicbrainz_result(results)
开发者ID:gcmalloc,项目名称:MusicSorter,代码行数:20,代码来源:musicfile.py


示例18: __init__

class mbzAPI:
    def __init__(self):
        self.q = Query()

    def findArtists(self, artist, limit = 20):
        try:
            aFilter = ArtistFilter(artist, limit)
            return self.q.getArtists(aFilter)
        except WebServiceError, e:
            # Logging Need
            return None
开发者ID:masterx2,项目名称:VKD,代码行数:11,代码来源:mbrainzApi.py


示例19: get_musicbrainz_id

 def get_musicbrainz_id(self):
     """
     Retrieve the MusicBrainz id for this artist and save it on the
     model.
     """
     # Make sure the useful bits of the musicbrainz2 package have been
     # imported.
     try:
         Query, ArtistFilter
     except NameError:
         return False
     # Query MusicBrainz.
     artist_filter = ArtistFilter(name=self.name)
     query = Query()
     try:
         artist = query.getArtists(artist_filter)[0].artist
         self.mbid = artist.id.rsplit("/", 1)[1]
         self.save()
     except (IndexError, AttributeError):
         return False
开发者ID:flother,项目名称:gigs,代码行数:20,代码来源:models.py


示例20: getArtists

    def getArtists(self, name, date = None, disambiguation = None):
        q = Query()

        if disambiguation:
            disPattern = re.compile(disambiguation, re.I)
        else:
            disPattern = None

        offset = 0
        limit = 100
        artistResults = set()
        while True:
            try:
                f = ArtistFilter(name = name, offset = offset, limit = limit)
                results = q.getArtists(f)
            except WebServiceError, e:
                raise SourceError

            results = filter(lambda res: res.getScore() == 100, results)
            # use filtered count because resulsts are score-ordered
            count = len(results)

            results = filter(lambda res: 
                    (not date or res.getArtist().getBeginDate() == date)
                    and ( not disPattern or
                        disPattern.search(res.getArtist().getDisambiguation()) ),
                    results)

            for r in results:
                ar = ArtistResult(name = r.getArtist().getName(),
                        date = r.getArtist().getBeginDate(),
                        disambiguation = disambiguation)
                        # use original disambiguation cause it'll be used in 
                        # artist's comparation

                ar.setKey(MusicbrainzSource._sourceName, r.getArtist().getId())
                artistResults.add(ar)

            if count < limit:
                break
            offset += count
开发者ID:xffox,项目名称:relcol,代码行数:41,代码来源:musicbrainz_source.py



注:本文中的musicbrainz2.webservice.Query类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python wsxml.MbXmlParser类代码示例发布时间:2022-05-27
下一篇:
Python utils.extractUuid函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap