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

Python musicbrainzngs.set_useragent函数代码示例

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

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



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

示例1: get_coverart

    def get_coverart(self, album):
        path = "app/static/media/"
        filename = "%s.jpg" % album.id

        musicbrainzngs.set_useragent("python-musicplayer-flask","0.1","[email protected]")
        covers = cache.get('covers')
        if album.id in covers:
            return

        covers.append(album.id)
        cache.set("covers", covers)


        if not album.musicbrainz_albumid or album.coverimage:
            return
            #raise NameError('musicbrainz_albumid not set')
        try:
            data = musicbrainzngs.get_image_list(album.musicbrainz_albumid)
        except Exception as e:
            return e

        if len(data['images']) == 0:
            raise NameError('No images returned from service')

        urllib.request.urlretrieve(data['images'][0]['image'], "%s%s" % (path, filename))
        ci = open("%s%s" % (path, filename), 'rb')
        album.coverimage.put(ci, content_type = 'image/jpeg')


        return
开发者ID:kaninfod,项目名称:musicplayer,代码行数:30,代码来源:models.py


示例2: lookup_song

def lookup_song(artist, title, format_string, sql):
    musicbrainzngs.set_useragent('Song-Looker-Upper', '0.1', 'http://www.kbarnes3.com')

    query = '"{0}" AND artist:"{1}" AND status:official'.format(title, artist)

    result = musicbrainzngs.search_recordings(query)

    if len(result['recording-list']) < 1:
        print('No songs found for query ' + query, file=sys.stderr)
        return

    recording = result['recording-list'][0]

    try:
        artist = recording['artist-credit'][0]['artist']['name']
        artist = artist.replace(u'\u2019', "'")
        title = recording['title']
        title = title.replace(u'\u2019', "'")

        if sql:
            artist = artist.replace("'", "''")
            title = title.replace("'", "''")

        length = recording['release-list'][0]['medium-list'][1]['track-list'][0]['length']
        duration = int(int(length) / 1000)

        output = format_string.format(artist=artist, title=title, duration=duration)
        print(output, end='')
    except Exception as ex:
        print('Error handling recording: ' + str(recording), file=sys.stderr)
        print(ex.message, file=sys.stderr)
        raise RecordParseException(ex.message)
开发者ID:kbarnes3,项目名称:song-looker-upper,代码行数:32,代码来源:song-looker-upper.py


示例3: load

def load(evt):
    m.set_useragent("steeb", "0.1", "[email protected]")
    mainwin['button_search'].onclick = search_artist
    mainwin['artistslist'].onitemselected = get_albums
    mainwin['albumslist'].onitemselected = get_tracks
    mainwin['button_down'].onclick = clickevt_album
    lv = mainwin['artistslist']
开发者ID:napcae,项目名称:steeb,代码行数:7,代码来源:steeb.py


示例4: __init__

    def __init__(self):
        run = Prop("run")
        if (run) and (time.time() < float(run) + 3):
            return

        Prop("run", str(time.time()))
        Prop("stamp", _stamp)

        self.once = True
        self.abort = False
        self.mesg = None
        self.station = None
        self.stations = None
        self.songs = {}
        self.pithos = mypithos.Pithos()
        self.player = xbmc.Player()
        self.playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
        self.ahead = {}
        self.queue = collections.deque()
        self.prof = Val("prof")
        self.wait = {"auth": 0, "stations": 0, "flush": 0, "scan": 0, "next": 0}
        self.silent = xbmc.translatePath("special://home/addons/%s/resources/media/silent.m4a" % _id)

        musicbrainzngs.set_useragent("kodi.%s" % _id, Val("version"))
        xbmcvfs.mkdirs(xbmc.translatePath(Val("cache")).decode("utf-8"))
        xbmcvfs.mkdirs(xbmc.translatePath(Val("library")).decode("utf-8"))
开发者ID:ClashTheBunny,项目名称:gominoa-xbmc-addons,代码行数:26,代码来源:pandoki.py


示例5: match_tracks_to_release

def match_tracks_to_release(title, tracks, mbid, name):
    '''
       Given a list of tracks, a candidate release mbid and name this function should return
       a score (0.0-1.0) of how well this list of tracks compares to the MB release.
    '''

    try:
        musicbrainzngs.set_useragent(config.USER_AGENT_STRING, config.USER_AGENT_VERSION, config.USER_AGENT_USER)
        rel = musicbrainzngs.get_release_by_id(mbid, includes=['recordings'])
    except musicbrainzngs.WebServiceError as exc:
        print "Something went wrong with the request: %s" % exc 
        return -1

#    print "--- %-40s %s" % (title.encode('utf-8'), name.encode('utf-8'))
    matches = []
    total = 0.0
    print 
    for i, t in enumerate(rel["release"]["medium-list"][0]["track-list"]):
        try:
            d = Levenshtein.ratio(clean_string(t['recording']['title']), tracks[i]['clean'])
            print "%.3f %2d %-40s | %s" % (d, i+1, clean_string(t['recording']['title']), tracks[i]['clean'])
            total += d
        except IndexError:
            return -1

    return total / len(tracks)
开发者ID:mayhem,项目名称:ia_matcher,代码行数:26,代码来源:mb_match.py


示例6: main

def main(argv):
    # load plugins

    from morituri.configure import configure
    pluginsdir = configure.pluginsdir
    homepluginsdir = os.path.join(os.path.expanduser('~'),
        '.morituri', 'plugins')

    distributions, errors = pkg_resources.working_set.find_plugins(
        pkg_resources.Environment([pluginsdir, homepluginsdir]))
    if errors:
        log.warning('errors finding plugins: %r', errors)
    log.debug('mapping distributions %r', distributions)
    map(pkg_resources.working_set.add, distributions)

    # validate dependencies
    from morituri.common import deps
    h = deps.DepsHandler()
    h.validate()

    # set user agent
    import musicbrainzngs
    musicbrainzngs.set_useragent("morituri", configure.version,
        'https://thomas.apestaart.org/morituri/trac')


    c = Rip()
    try:
        ret = c.parse(argv)
    except SystemError, e:
        sys.stderr.write('rip: error: %s\n' % e.args)
        return 255
开发者ID:chadberg,项目名称:whipper,代码行数:32,代码来源:main.py


示例7: run

	def run(self):
		musicbrainzngs.set_useragent("Mary", "Alpha", "[email protected]")
		if self.model is not None:
			for row in self.model.row:
				self.find_mbid(row)
				if self.lock.is_set():
					break
开发者ID:maeln,项目名称:Mary,代码行数:7,代码来源:ModelUpdater.py


示例8: individual_subitem_matches

 def individual_subitem_matches(self, subitem, data):
     musicbrainzngs.set_useragent('geordi', 'discogs-subitem-matches', 'http://geordi.musicbrainz.org')
     (discogs_type, discogs_id) = re.split('-', subitem, 1)
     if discogs_type == 'master':
         try:
             url_data = musicbrainzngs.browse_urls(
                 resource='http://www.discogs.com/master/%s' % discogs_id,
                 includes=['release-group-rels'])
             mbids = [release_group['release-group']['id'] for release_group in url_data['url']['release_group-relation-list']]
             return {'release-group': mbids}
         except:
             return {'unmatch': []}
     elif discogs_type in ['artist', 'label'] and data.get('name', False):
         names = data.get('name', [])
         mbids = []
         for name in names:
             try:
                 url_data = musicbrainzngs.browse_urls(
                     resource='http://www.discogs.com/%s/%s' % (discogs_type, urllib.quote_plus(name.encode('utf-8'), '!\'()*-._~')),
                     includes=['%s-rels' % discogs_type])
                 mbids = mbids + [entity[discogs_type]['id'] for entity in url_data['url']['%s-relation-list' % discogs_type]]
             except: continue
         mbids = uniq(mbids)
         if len(mbids) > 0:
             return {discogs_type: mbids}
         else:
             return {'unmatch': []}
     else:
         return {}
开发者ID:M0rg4n,项目名称:geordi,代码行数:29,代码来源:discogs.py


示例9: handle

 def handle(self, **options):
     musicbrainzngs.set_useragent(settings.MB_APP, settings.MB_VERSION, settings.MB_CONTACT)
     if options['full']:
         albums = Album.objects.filter(image='')
     else:
         albums = Album.objects.filter(is_get_image=False)
     for album in albums:
         print 'ALBUM: ', album
         for release in album.releases.all():
             try:
                 data = musicbrainzngs.get_image_list(release.mbid)
                 url = ''
                 for image in data['images']:
                     if 'Front' in image['types'] and image['approved']:
                         url = image['thumbnails']['large']
                 if url:
                     print '+'
                     album.image = url
                     break
             except musicbrainzngs.musicbrainz.ResponseError:
                 pass
         if not album.image:
             print '-'
         album.is_get_image = True
         album.save()
     print 'FINISHED'
开发者ID:Sinkler,项目名称:music,代码行数:26,代码来源:covers.py


示例10: __init__

    def __init__(self):
        log = logging.getLogger('util.importer.Importer.__init__')

        musicbrainzngs.set_useragent("NRG Processor", "0.01", "http://anorg.net/")
        musicbrainzngs.set_rate_limit(MUSICBRAINZ_RATE_LIMIT)
        
        if MUSICBRAINZ_HOST:
            musicbrainzngs.set_hostname(MUSICBRAINZ_HOST)
开发者ID:hzlf,项目名称:openbroadcast,代码行数:8,代码来源:__old_importer.py


示例11: search_mb

 def search_mb(self):
     musicbrainzngs.set_useragent("mudl", "0.1.3")
     criteria = {"artist": self.user_query.bare_artist(), "recording": self.user_query.bare_title()}
     try:
         recordings = musicbrainzngs.search_recordings(limit=10, **criteria)
         for recording in recordings["recording-list"]:
             yield VKDownloader.get_mb_info(recording)
     except Exception as e:
         print(colored.red(u"Something went wrong with the request: {0}".format(e)))
开发者ID:yenbekbay,项目名称:mudl,代码行数:9,代码来源:vk_downloader.py


示例12: __init__

 def __init__(self, mbz_id):
     self.mbz_id = mbz_id
     musicbrainzngs.set_useragent("gigographics.mdg.io", "0.1", "http://gigographics.mdg.io")
     self.data = {
         'artist' : {
             'name' : musicbrainzngs.get_artist_by_id(self.mbz_id)['artist']['name'],
             'mbz_id' : self.mbz_id
         }
     }
开发者ID:mdgweb,项目名称:gigographics,代码行数:9,代码来源:gigographics.py


示例13: musicbrainz_lookup

def musicbrainz_lookup():
    """
    Scans a folder for music files with metadata. Collects metadata information
    from all music files and assumes they belong to the same album. Produces a
    simple description of the album that it loads into a KLAP form.
    """
    
    # Help the user
    if len(sys.argv) != 2:
        print "Usage: {} Drive".format(sys.argv[0])
        sys.exit(1)

    tracks = []
    musicbrainzngs.set_useragent("KLAP-CDDBAdd", "0.3", "[email protected]")

    disc = discid.read(sys.argv[1])
    try:
        result = musicbrainzngs.get_releases_by_discid(disc.id,
                                                       includes=["artists","recordings","release-groups"])
    except musicbrainzngs.ResponseError:
        print "Couldn't find that disc in the online database, sorry!"
        return None
    else:
        print "Found disc {}".format(disc.id)
        subd = None
        if result.get("disc"):
            if len(result['disc']['release-list']) == 0:
                print "Found the disc id, but it didn't have any releases..."
                return None
            print "Found a musicbrainz release id"
            open_url(KLAP_MB_URL.format(result['disc']['release-list'][0]['id']))
            sys.exit()
        elif result.get("cdstub"):
            artist = normalize(result["cdstub"]["artist"])
            album = normalize(result["cdstub"]["title"])
            subd = result["cdstub"]
            c = 1
            for track in subd['track-list']:
                title = normalize(track['title'])
                tartist = normalize(track['artist'])
                d = {'number': c,
                     'title': title}
                if tartist != artist:
                    d['artist'] = tartist
                tracks.append(d)
                c += 1
    
    # Make sure the info is safe for KLAP
    artist = artist
    album = album
    
    # Make the dict
    obj = {'artist': artist,
           'album': album,
           'tracks': tracks,
          }
    return obj
开发者ID:KMNR,项目名称:KLAP-CDDBAdds,代码行数:57,代码来源:CDDBAdd.py


示例14: __init__

    def __init__(self):

        musicbrainzngs.set_useragent("NRG Processor", "0.01", "http://anorg.net/")
        musicbrainzngs.set_rate_limit(MUSICBRAINZ_RATE_LIMIT)

        self.file_metadata = None

        if MUSICBRAINZ_HOST:
            musicbrainzngs.set_hostname(MUSICBRAINZ_HOST)
开发者ID:hzlf,项目名称:openbroadcast.org,代码行数:9,代码来源:identifier.py


示例15: automatic_item_matches

 def automatic_item_matches(self, data):
     musicbrainzngs.set_useragent('geordi', 'discogs-item-matches', 'http://geordi.musicbrainz.org')
     try:
         url_data = musicbrainzngs.browse_urls(
             resource='http://www.discogs.com/release/%s' % data['discogs']['release']['_id'],
             includes=['release-rels'])
         mbids = [release['release']['id'] for release in url_data['url']['release-relation-list']]
         return {'release': mbids}
     except:
         return {'unmatch': []}
开发者ID:M0rg4n,项目名称:geordi,代码行数:10,代码来源:discogs.py


示例16: disc_info_fetch

def disc_info_fetch(disc_id=None):
    if not disc_id:
        disc = _read_disc()
        disc_id = disc.id

    musicbrainzngs.set_useragent(afro.name, afro.version, afro.url)
    try:
        return musicbrainzngs.get_releases_by_discid(disc_id, includes=['artists', 'recordings'])
    except musicbrainzngs.ResponseError as exception:
        return None
开发者ID:mathgl67,项目名称:Afro,代码行数:10,代码来源:disc_info.py


示例17: __init__

    def __init__(self):

        musicbrainzngs.set_useragent("NRG Processor", "0.01", "http://anorg.net/")
        musicbrainzngs.set_rate_limit(MUSICBRAINZ_RATE_LIMIT)
        
        self.pp = pprint.PrettyPrinter(indent=4)
        self.pp.pprint = lambda d: None
        
        if MUSICBRAINZ_HOST:
            musicbrainzngs.set_hostname(MUSICBRAINZ_HOST)
开发者ID:alainwolf,项目名称:openbroadcast.org,代码行数:10,代码来源:process.py


示例18: main

def main():
    # set user agent
    musicbrainzngs.set_useragent("whipper", whipper.__version__,
                                 "https://github.com/JoeLametta/whipper")

    try:
        server = config.Config().get_musicbrainz_server()
    except KeyError, e:
        sys.stderr.write('whipper: %s\n' % e.message)
        sys.exit()
开发者ID:RecursiveForest,项目名称:whipper,代码行数:10,代码来源:main.py


示例19: test_set_useragent

    def test_set_useragent(self):
        """ When a useragent is set it is sent with the request """
        musicbrainzngs.set_useragent("caa-test", "0.1")

        resp = b'{"images":[]}'
        self.opener = _common.FakeOpener(resp)
        musicbrainzngs.compat.build_opener = lambda *args: self.opener
        res = caa.get_image_list("8ec178f4-a8e8-4f22-bcba-1964466ef214")

        headers = dict(self.opener.headers)
        self.assertTrue("User-agent" in headers)
        self.assertEqual("caa-test/0.1 python-musicbrainzngs/%s" % _version, headers["User-agent"])
开发者ID:alastair,项目名称:python-musicbrainzngs,代码行数:12,代码来源:test_caa.py


示例20: handle

 def handle(self, **options):
     musicbrainzngs.set_useragent(settings.MB_APP, settings.MB_VERSION, settings.MB_CONTACT)
     if options['changed']:
         artists = Artist.objects.exclude(lastfm_mbid=F('mbid'))
     else:
         artists = Artist.objects\
             .filter(lastfm_playcount__gt=settings.LASTFM_MIN_PLAY_COUNT, mbid__gt='')\
             .order_by('lastfm_playcount')
     for artist in artists:
         print 'ARTIST: ', artist.title
         if artist.updated and not (now() - artist.updated).days:
             print 'updated recently'
             continue
         if options['changed']:
             # deleting old releases and albums
             artist.max_year = 0
             for old_release in artist.releases.all():
                 old_release.delete()
             for old_album in artist.albums.all():
                 old_album.delete()
             artist.save()
         # getting new releases
         for release_type in settings.MB_RELEASE_TYPES:
             limit = 100
             offset = 0
             parsed = 0
             cont = True
             while cont:
                 releases = musicbrainzngs.browse_releases(artist=artist.mbid,
                                                           release_type=[release_type],
                                                           release_status=settings.MB_RELEASE_STATUSES,
                                                           limit=limit,
                                                           offset=offset)
                 for release in releases['release-list']:
                     parsed += 1
                     album, created = Release.objects.get_or_create(mbid=release.get('id'), artist=artist)
                     if created:
                         print 'NEW: ', release.get('id'), release.get('title')
                         album.date = release.get('date')
                         if album.date:
                             album.year = release.get('date').split('-')[0]
                         album.title = release.get('title')
                         album.country = release.get('country')
                         album.type = release_type
                         album.save()
                 if parsed < releases['release-count']:
                     offset += limit
                 else:
                     cont = False
         artist.updated = now()
         artist.save()
     print 'FINISHED'
开发者ID:Sinkler,项目名称:music,代码行数:52,代码来源:releases.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python mbxml.parse_message函数代码示例发布时间:2022-05-27
下一篇:
Python musicbrainzngs.set_rate_limit函数代码示例发布时间: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