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

Python pylast.get_lastfm_network函数代码示例

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

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



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

示例1: clicked

    def clicked(self, *ignore):
        if self.auth_url:
            def err(e):
                logging.error(e)
                self.set_button_text()

            get_worker().send(self.sg.get_web_auth_session_key, (self.auth_url,), self.setkey, err) 
            self.button.set_label("Checking...")
            self.button.set_sensitive(False)
            self.auth_url = False
                
        elif self.enabled:
            self.setkey(False)
        else:
            self.network = pylast.get_lastfm_network(api_key=API_KEY, api_secret=API_SECRET)
            self.sg = pylast.SessionKeyGenerator(self.network)
            
            def callback(url):
                self.auth_url = url
                self.set_button_text()
                webbrowser.open(self.auth_url)
            
            get_worker().send(self.sg.get_web_auth_url, (), callback)
            self.button.set_label("Connecting...")
            self.button.set_sensitive(False)
开发者ID:andybarry,项目名称:pithos,代码行数:25,代码来源:scrobble.py


示例2: lfm_artists

def lfm_artists(username, cutoff=20, period = '12month'):
	net = pylast.get_lastfm_network(LAST_KEY, LAST_SECRET)
	user = pylast.User(username, net)
	artists = user.get_top_artists(period=period)
	return {'username':user.get_name(),
			'top_artists':\
			map(lambda artist:(artist.item.name, artist.weight), artists[:20])}
开发者ID:gearmonkey,项目名称:pathival,代码行数:7,代码来源:agendafest_api.py


示例3: lastfm

def lastfm(inp, reply=None, say=None, nick=''):
   API_KEY = "30cabd8b57c765a42f78e8f5d329fdc0"
   API_SECRET = "0ab2d0a46763e71d1ed8877b4ea209cf"
   username = "elgruntox"
   password_hash = pylast.md5("justpurple")
   network = pylast.get_lastfm_network(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)
   try:   
      if inp == '':
         user = network.get_user(nick)
      else: 
         user = network.get_user(inp)
         nick = inp
   except WSError:
      say("This user doesn't exist.")
   try:
      tracks = user.get_recent_tracks()
   except pylast.WSError:
       if inp == '':
          return("It seems like your current nickname does not have a lastFM account. Try '.lastfm username' instead.")  
       else: 
          return("The user '%s' does not exist. Maybe you misspelled it?" % inp)
   recent = tracks[0][0]
   artist = recent.get_artist().get_name()
   title = recent.get_title()
   url = recent.get_url()
   bitlyURL = bitly_api.shorten(url) 

   finalise = "\x02%s\x0F's last track - \x02%s\x0f :: Artist - \x02%s\x0f :: Link to Song - \x02%s\x0F" % (nick, title, artist, bitlyURL)
   say(finalise)
开发者ID:limnick,项目名称:siri,代码行数:29,代码来源:lastfm.py


示例4: lfmInit

def lfmInit(user):
	#initialize lfm objects
	url = user['lfm_url']
	network = pylast.get_lastfm_network(os.environ.get('LFM_APIKEY'), os.environ.get('LFM_SECRET'))
	sg = pylast.SessionKeyGenerator(network)
	sg.web_auth_tokens[url] = url[(url.index('token')+6):]
	sg.api_key = os.environ.get('LFM_APIKEY')
	sg.api_secret = os.environ.get('LFM_SECRET')
	#try to authorize token
	try:
		session_key = sg.get_web_auth_session_key(user['lfm_url'])
		print session_key
	except pylast.WSError:
		print "Error authorizing user for last.fm"
		markUser(user, 'LASTFM INIT ERROR')
	#success, add new session key and remove auth token
	else:
		getDatabase().users.update(
		{'userid': user['userid'], 'version': user['version']},
		{
			'$set':{
				'lfm_session': session_key,
				'status': 'working'
			},
			'$unset':{
				'lfm_url': True
			}
		})
开发者ID:benhgreen,项目名称:iidxscrobbler,代码行数:28,代码来源:usermanager.py


示例5: get_biography

 def get_biography(self):
     """Import artist briography from Last.fm."""
     # Make sure the pylast module is available.
     try:
         pylast
     except NameError:
         return False
     # Open a connection to the Last.fm API.
     lastfm = pylast.get_lastfm_network(api_key=settings.LASTFM_API_KEY)
     lastfm_artist = lastfm.get_artist(self.name)
     try:
         # Get the biography from Last.fm.
         biography = lastfm_artist.get_bio_content()
         bio_published_date = lastfm_artist.get_bio_published_date()
         if bio_published_date:
             plain_text_biography = strip_tags(biography)
             # If the biography is different to the saved version or the
             # artist biography is blank, save the artist's biography.
             # Note this will overwrite any changes that have been made
             # to the biography via the admin.
             if (not plain_text_biography == self.biography or
                     self.biography == ''):
                 self.biography = plain_text_biography
                 self.save()
     except (pylast.WSError, urllib2.URLError, urllib2.HTTPError):
         # An error occurs if the artist's name has a character in that
         # Last.fm doesn't like, or on the occasional dropped connection.
         pass
开发者ID:flother,项目名称:gigs,代码行数:28,代码来源:models.py


示例6: get_cover_art

 def get_cover_art(self):
     """Attempt to get the album's cover art from Last.fm."""
     try:
         pylast
     except NameError:
         return False
     album_id = unicodedata.normalize('NFKD',
         unicode(' '.join([self.artist.name, self.title]))).encode('ascii',
         'ignore')
     album_hash = hashlib.sha1(album_id).hexdigest()
     lastfm = pylast.get_lastfm_network(api_key=settings.LASTFM_API_KEY)
     lastfm_album = lastfm.get_album(self.artist.name, self.title)
     try:
         cover_image = lastfm_album.get_cover_image()
         response = urllib2.urlopen(cover_image)
         data = response.read()
         # Store the photo on disk and link the photo to the album.
         filename = os.path.join(settings.MEDIA_ROOT,
             Album.PHOTO_UPLOAD_DIRECTORY, '%s.jpg' % album_hash)
         fh = open(filename, 'w')
         fh.write(data)
         fh.close()
         self.cover_art = os.path.join(Album.PHOTO_UPLOAD_DIRECTORY,
             '%s.jpg' % album_hash)
         self.save()
     except (pylast.WSError, AttributeError, urllib2.HTTPError):
         pass
开发者ID:flother,项目名称:gigs,代码行数:27,代码来源:models.py


示例7: fetchTopTagStats

 def fetchTopTagStats(self, retries=2):
     '''
     LastFM provides a unified list tags/counts, for the top tags. By fetching these in one call, we can
     typically avoid a ton of unnecessary network calls for individual tags.
     '''
     tags = {}
     try:
         lastfm = pylast.get_lastfm_network(api_key=self.api_key, api_secret=self.api_secret)
         lastTopTags = lastfm.get_top_tags(10000)
         for lastTopTag in lastTopTags:
             if (self.useNamedTuple):
                 key = str(lastTopTag.item.name).lower()
                 count = int(lastTopTag.weight)
             elif type(lastTopTag) == pylast.TopItem:
                 key = str(lastTopTag.item.get_name()).lower()
                 count = int(lastTopTag.weight)
             else:
                 key = str(lastTopTag['item'].name).lower()
                 count = int(lastTopTag['weight'])
             if (key in tags):
                 self.outputWrapper.logError('Duplicate tag retrieved from lastFM, merging counts: ' + lastTopTag)
                 tags[key] += count
             else:
                 tags[key] = count
         return tags
     except Exception as err:
         if (retries > 0):
             self.outputWrapper.logError('Problem retrieving top tag information, ' + str(retries) + ' retries left: ' + str(err))
             time.sleep(5)
             return self.fetchTopTagStats(retries - 1)
         else:
             self.outputWrapper.logError('Problem retrieving top tag information, ' + str(retries) + ' skipping: ' + str(err))
     return None
开发者ID:brenthuisman,项目名称:lastfmtagupdater,代码行数:33,代码来源:lastfmwrapper.py


示例8: getNetworkObject

def getNetworkObject(API_KEY, API_SECRET):
    """Gets the network object needed to get information."""
    network = None
    try:
        network = pylast.get_lastfm_network(api_key = API_KEY, api_secret = API_SECRET)
        network.enable_caching() # enables caching for certain calls (see pylast.py)
    except pylast.WSError, e:
        irc.error("Houston, we have a problem. %s" % e.get_id())
开发者ID:wonaldson,项目名称:supybot-LastFM,代码行数:8,代码来源:plugin.py


示例9: getHits

def getHits(artist_name):
    network = pylast.get_lastfm_network(api_key = config.LAST_FM_API_KEY,
                                        api_secret = config.LAST_FM_API_KEY)
    artist = network.get_artist(artist_name)
    try:
        hits = artist.get_top_tracks()
    except pylast.WSError:
        return []
    return [hit.item.title for hit in hits]
开发者ID:philippp,项目名称:youvj,代码行数:9,代码来源:lastfm.py


示例10: crawl

def crawl(username_filename):
    network = pylast.get_lastfm_network(api_key = API_KEY,
                                        api_secret = API_SECRET)
    for username in open(username_filename, 'r').readlines():
        try:
            crawl_user_data(username.strip(), network)
        except:
            sys.stderr.write('ERROR in processing user %s; continuing on.\n' %
                             username)
开发者ID:kpich,项目名称:last.fm-Historical-User-Data-Gathering,代码行数:9,代码来源:crawl_user_data.py


示例11: main

def main():
    config = configparser.ConfigParser()
    config.read('config.ini')

    # last.fm initialization
    last_fm = config['Last.fm']
    last_fm_api_key = 'bbad67cabcce9598501d485b701698f1'
    if not last_fm['username']:
        print('Last.fm is required to use Tune Saver. Provide your Last.fm username in config.ini')
        quit()
    ln = pylast.get_lastfm_network(api_key=last_fm_api_key)
    user = pylast.User(last_fm['username'], ln)

    # The order these appear in this list will determine the order they appear
    # in the selection prompt.
    # List of (constructor, config) tuples
    service_constructors = [
        # Highest priority: The ability to download the track directly.
        # Try the services with better search capabilities first.
        (jamendo.Jamendo, config['Jamendo']),
        (fma.FMA, config['Free Music Archive']),
        (soundcloud_download.SoundcloudDownload, config['Soundcloud']),
        # Failing that, try to save to a streaming music service
        (spotify.Spotify, config['Spotify']),
        (soundcloud_playlist.SoundcloudPlaylist, config['Soundcloud']),
        # Last free resort: maybe it's available in video form
        (youtube.Youtube, config['YouTube']),
        # If the track cannot be obtained for free, look for a way to buy it.
        (last_fm_purchase.LastFmPurchase, config['Last.fm']),
    ]
    
    services = []
    for sc, config_section in service_constructors:
        if not all(value for _,value in config_section.items()):
            print('To use {}, fill out all of its fields in config.ini'.format(
                config_section.name))
            continue
        try:
            services.append(sc(config_section))
        except Exception as e:
            # This service could not be initialized. Print the reason,
            # but continue attempting to initialize other services.
            print(str(e))
    
    # Main input loop
    while True:
        input('\nPress enter to save song')
        # Fetch the song from the Last.fm api
        track = most_current_track(user)
        if not track:
            print('Could not get a track from Last.fm.')
            continue
        print('\nNow Playing: {} - {}\n'.format(
            track.artist.name, track.title))

        save_track(track, services)
开发者ID:clentner,项目名称:Tune-Saver,代码行数:56,代码来源:__main__.py


示例12: oauth_callback

 def oauth_callback(self, request):        
     sg = pylast.SessionKeyGenerator(self.network)
     sg.web_auth_tokens["fake"] = request.args.get("token")
     sk = sg.get_web_auth_session_key("fake")
     user = {}
     for k in pylast.get_lastfm_network(self.api_key, self.api_secret, session_key=sk).get_authenticated_user()._request("user.getInfo", True).getElementsByTagName('*'):
         if k.firstChild and k.firstChild.nodeValue.strip() != "":
             user[k.tagName] = k.firstChild.nodeValue
     
     return (int(user["id"]), dict(user, session_key=sk))
开发者ID:themylogin,项目名称:thelogin.ru,代码行数:10,代码来源:__init__.py


示例13: plot

def plot(artistName, numArtists, API_KEY, sizeX, sizeY):
  size(sizeX,sizeY)

  network = pylast.get_lastfm_network(api_key = API_KEY)
  network.enable_caching()

  font("Gill Sans MT Pro Medium", 24)
  text(artistName, WIDTH/10, HEIGHT/10)
  font("Gill Sans MT Pro Light", 12)

  artist = network.get_artist(artistName)

  similares = artist.get_similar(numArtists)

  posiciones = []
  
  colormode(HSB)

  for sim in similares:
      artSimil = sim[0].name
      angle = 0
      noFound = True
      while noFound: #Brutish collision management
        angle = random.randint(0,360/numArtists+1)
        if (angle in posiciones):
          noFound = True
        else:
          posiciones.append(angle)
          noFound = False
          
      angle = angle * (numArtists+1)
      
      dist = WIDTH/2 - (sim[1]*WIDTH/2)
      if (dist < WIDTH/10):
        dist = dist+WIDTH/10
      
      X = coordinateX(WIDTH/2,HEIGHT/2, dist, angle)
      Y = coordinateY(WIDTH/2,HEIGHT/2, dist, angle)
      
      fill(angle/360.0, 0.8*360, 0.5)
      
      if (angle > 90 and angle < 270):
        angle = angle + 180
        align(RIGHT)
      else:
        align(LEFT)
      
      push()
      rotate(angle)
      
      text(artSimil, X, Y, width=50)
      pop()
开发者ID:tian2992,项目名称:botboxvis,代码行数:52,代码来源:beat.py


示例14: handle_last

def handle_last(t, s, p):
 if not p: s.syntax(t, 'last')
 else:
  p = p.strip()
  try:
   api = pylast.get_lastfm_network(lastfm_key)
   seq = api.get_user(p).get_recent_tracks(limit=1)
   mesg = u'Последний трек пользователя %s:\n' % (p)
   for item in seq:
    mesg +='%s - %s (%s)\n' % (item[0].get_artist().get_name(), item[0].get_name(), item[1])
  except:
   mesg = u'Невозможно получить доступ к данным.'
  s.msg(t, mesg)
开发者ID:TLemur,项目名称:freq-bot,代码行数:13,代码来源:lastfm.py


示例15: connect_to_lastfm

 def connect_to_lastfm(self):
     print "Connecting to Last.fm",
     password_hash = pylast.md5( self.param['lastfm_password'] )
     try:
         self.network = pylast.get_lastfm_network( api_key = self.param['lastfm_api'], \
                                             api_secret = self.param['lastfm_secret'], \
                                             username = self.param['lastfm_username'], \
                                             password_hash = password_hash)
     except:
         print "\tcouldn't establish connection. Sorry :( '"
         exit()
     else:
         print "successfully! :)"
开发者ID:brabadu,项目名称:sharkfm,代码行数:13,代码来源:sharkfm.py


示例16: album_art

def album_art(track_id, **kw):
    tr = Track.objects.get(pk=track_id)
    try:
        fm = pylast.get_lastfm_network(api_key=settings.LAST_FM_KEY)
        alb = fm.get_album(tr.artist, tr.album)
        (Track.objects.filter(pk=track_id)
         .update(large_art_url=alb.get_cover_image(pylast.COVER_LARGE),
                 medium_art_url=alb.get_cover_image(pylast.COVER_MEDIUM),
                 small_art_url=alb.get_cover_image(pylast.COVER_SMALL)))
    except pylast.WSError:
        # Probably album not found
        log.exception('in album_art')
    print 'got artwork for %s' % tr
开发者ID:kumar303,项目名称:rockit,代码行数:13,代码来源:tasks.py


示例17: login

 def login(self, query):
     form = self._deserialize(query)
     storage = harkfm.Storage()
     api_key = harkfm.Engine.config['apis']['last.fm']['key']
     api_secret = harkfm.Engine.config['apis']['last.fm']['secret']
     try:
         network = pylast.get_lastfm_network(api_key, api_secret)
         session_key = pylast.SessionKeyGenerator(network).get_session_key(form['username'],  pylast.md5(form['password']))
         storage.config_set('apis/last.fm/session_key', session_key)
         interface = harkfm.Interface()
         interface.index()
     except Exception as e:
         harkfm.Interface.logger.error('%s  %s', type(e), e)
开发者ID:emmercm,项目名称:HarkFM,代码行数:13,代码来源:interface.py


示例18: __init__

    def __init__(self, name, type, username, password, password_cmd, password_hash, submit_url, client_version):
    
        self.name = name
        self.username = username
        self.type = type
        
        if password_cmd:
            password = os.popen(password_cmd).read()

        if not password_hash:
            password_hash = hashlib.md5(password).hexdigest()
        
        if type == "lastfm":
            self.network = pylast.get_lastfm_network(username = username, password_hash = password_hash)
        elif type == "librefm":
            self.network = pylast.get_librefm_network(username = username, password_hash = password_hash)
        elif type == "custom":
            self.network = pylast.get_lastfm_network(username = username, password_hash = password_hash)
            self.network.submission_server = submit_url
        
        self.scrobbler = self.network.get_scrobbler("sth", client_version)
        self.cache = []
开发者ID:eqyiel,项目名称:scrobblethis,代码行数:22,代码来源:accounts.py


示例19: connect_to_lastfm

def connect_to_lastfm():
    CONF_FILE = join(getenv("XDG_CONFIG_HOME", expanduser("~/.config")), "mpdt", "config")
    conf = {}
    with open(CONF_FILE, "r") as configfile:
        for i in configfile.readlines():
            i = i.split(" ")
            conf[i[0]] = i[1][:-1]
    network = pylast.get_lastfm_network(
        api_key=conf["api_key"],
        api_secret=conf["api_secret"],
        username=conf["username"],
        password_hash=conf["password"],
    )
    return network
开发者ID:mineo,项目名称:mpdstuff,代码行数:14,代码来源:common.py


示例20: handle_now

def handle_now(t, s, p):
 if not p: s.syntax(t, 'now')
 else:
  p = p.strip()
  try:
   api = pylast.get_lastfm_network(lastfm_key)
   seq = api.get_user(p).get_now_playing()
   if seq:
    mesg = u'Пользователь %s сейчас слушает ' % (p) 
    mesg += '%s - %s' % (seq.get_artist().get_name(), seq.get_name())
   else:
    mesg = u'Пользователь %s сейчас ничего не слушает.' % (p)
  except:
   mesg = u'Невозможно получить доступ к данным.'
  s.msg(t, mesg)
开发者ID:TLemur,项目名称:freq-bot,代码行数:15,代码来源:lastfm.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python pylast.md5函数代码示例发布时间:2022-05-25
下一篇:
Python pylase.loadIdentity函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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