httplib(discogs-API)的python性能

2024-05-22 09:37:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个简短的程序,它使用了python中的Discogs API,但是它太慢了,不能用于真正的web应用程序。 下面是Python代码和Python概要文件结果(仅发布耗时的点):

# -*- coding: utf-8 -*-

import profile
import discogs_client as discogs

def main():
    discogs.user_agent = 'Mozilla/5.0'
    #dump released albums into the file. You could also print it to the console
    f=open('DiscogsTestResult.txt', 'w+')

    #Use another band if you like, 
    #but if you decide to take "beatles" you will wait an hour! (cause of the num of releases)
    artist = discogs.Artist('Faust')
    print >> f, artist
    print  >> f," "

    artistReleases = artist.releases
    for r in artistReleases:
        print >> f, r.data
        print >> f,"---------------------------------------------"


print 'Performance Analysis of Discogs API'
print '=' * 80
profile.run('print main(); print')

下面是Python剖面图的结果:

^{pr2}$

有人知道如何加快速度吗。 我希望迪斯科舞曲能有一些变化_客户端.py会更快。 也许从httplib改成别的什么,或者别的什么。 或者mybe使用另一个协议代替http更快?在

(迪斯科音乐的来源_客户端.py可在此处访问:“https://github.com/discogs/discogs_client/blob/master/discogs_client.py”)

如果有人有任何想法请回复,很多人都会从中受益。在

问候 丹尼尔


Tags: ofthetopyimportclientyouapi
2条回答

更新:来自discogs文档:Requests are throttled by the server to one per second per IP address. Your application should (but doesnt have to) take this into account and throttle requests locally, too.

瓶颈似乎在(discogs)服务器端,检索单个版本。你对此无能为力,除了给他们钱买更快的服务器。在

我的建议是缓存结果,这可能是唯一有用的方法。重写迪斯科芹菜.\u回复如下:

def _response(self):
    if not self._cached_response:
        self._cached_response=self._load_response_from_disk()
    if not self._cached_response:
        if not self._check_user_agent():
            raise UserAgentError("Invalid or no User-Agent set.")
        self._cached_response = requests.get(self._uri, params=self._params, headers=self._headers)
        self._save_response_to_disk()

    return self._cached_response

另一种方法是将请求写入日志并说“我们不知道,稍后再试”,然后在另一个过程中,读取日志,下载数据,将其存储在数据库中。然后当他们稍后回来时,请求的数据就会准备好了。在

您需要自己编写_load_response_from_disk()和_save_response_to_disk(),存储的数据应该以_uri, _params, and _headers为键,并且应该在数据中包含一个时间戳。如果数据太旧(在这种情况下,我建议以月为单位-我不知道编号是否持久-我想最初尝试几天-几周),或者没有找到,返回None。存储必须处理并发访问和快速索引—可能是一个数据库。在

请尝试以下操作:不要使用print>;>;来写入文件,请使用f.write('hello\n')。在

相关问题 更多 >