从URL检索音频/ mp3文件并保存到blobstore

时间:2013-05-24 19:48:06

标签: python google-app-engine urllib2 blobstore

我正在尝试将文件(在这种情况下为音频/ mp3)保存到App Engine blobstore,但结果好坏参半。一切似乎都有效,文件保存在blobstore中,类型正确,但它基本上是空的(1.5kB与预期的6.5kB相比),所以不会播放。相关网址为http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=revenues+in+new+york+were+56+million

应用引擎日志没有显示任何异常 - 所有部分都按预期执行...任何指针都将不胜感激!

class Dictation(webapp2.RequestHandler):
  def post(self):
    sentence = self.request.get('words')

    # Google Translate API cannot handle strings > 100 characters
    sentence = sentence[:100]

    # Replace the non-alphanumeric characters 
    # The spaces in the sentence are replaced with the Plus symbol
    sentence = urllib.urlencode({'q': sentence})

    # Name of the MP3 file generated using the MD5 hash
    mp3_file = hashlib.md5(sentence).hexdigest()

    # Save the MP3 file in this folder with the .mp3 extension
    mp3_file = mp3_file + ".mp3"

    # Create the full URL
    url = 'http://translate.google.com/translate_tts?ie=UTF-8&tl=en&' + sentence

    # upload to blobstore
    mp3_file = files.blobstore.create(mime_type = 'audio/mp3', _blobinfo_uploaded_filename = mp3_file)
    mp3 = urllib.urlopen(url).read()

    with files.open(mp3_file, 'a') as f:
      f.write(mp3)

    files.finalize(mp3_file)

    blob_key = files.blobstore.get_blob_key(mp3_file)
    logging.info('blob_key identified as %s', blob_key)

1 个答案:

答案 0 :(得分:2)

问题与您的代码无关;它正确地从您提供的URL中检索数据。

例如,如果我在命令行中尝试此操作:

$ curl -O http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=revenues+in+new+york+were+56+million

我得到一个1.5kB 403错误页面,其内容如下:

  

403。那是一个错误。

     

您的客户无权获取URL / translate_tts?ie = UTF-8& tl = en& q = income + in + new + york +来自此服务器的+ 56 +百万。 (客户端IP地址:1.2.3.4)

     

这就是我们所知道的。

您的代码完全相同,无论是在GAE中运行还是直接在交互式解释器中运行。

最有可能的是,它在您的浏览器中运行的原因是您拥有权限。那么,这意味着什么?这可能意味着您的浏览器中有来自google.com的有效SID Cookie,但不是您的脚本。或者它可能意味着您的浏览器的用户代理被识别为可以播放HTML5音频的内容,但您的脚本不是。或者......

好吧,您可以尝试对浏览器和脚本之间的Cookie,标题等进行反向工程,并将其缩小到相关差异,并使用显式标题或Cookie或任何您需要的工作围绕这个问题。

但是下次谷歌改变任何事情时它都会破裂。

如果您尝试这一点,Google可能会对您不满意。他们提供他们希望您使用的Google Translate API服务,并且由于“广泛滥用导致的巨大经济负担”,他们摆脱了该API的所有免费选项。试图通过抓取他们的网页来发布逃避Google API定价的Google App Engine网络服务可能不是他们喜欢客户所做的事情。

相关问题