本文整理汇总了Python中pylast.get_lastfm_network函数的典型用法代码示例。如果您正苦于以下问题:Python get_lastfm_network函数的具体用法?Python get_lastfm_network怎么用?Python get_lastfm_network使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_lastfm_network函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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])}
示例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)
示例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
}
})
示例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
示例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
示例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
示例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())
示例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]
示例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)
示例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)
示例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))
示例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()
示例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)
示例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! :)"