Open a file from urlfetch in GAE

与世无争的帅哥 提交于 2019-12-08 03:09:46

问题


I'm trying to open a file in GAE that was retrieved using urlfetch().

Here's what I have so far:

from google.appengine.api import urlfetch

result = urlfetch.fetch('http://example.com/test.txt')
data = result.content
## f = open(...) <- what goes in here?

This might seem strange but there's a very similar function in the BlobStore that can write data to a blobfile:

f = files.blobstore.create(mime_type='txt', _blobinfo_uploaded_filename='test')
with files.open(f, 'a') as data:
    data.write(result.content)

How can I write data into an arbitrary file object?

Edit: Should've been more clear; I'm trying to urlfetch any file and open result.content in a file object. So it might be a .doc instead of a .txt


回答1:


Yoy do not have to open a file. You have received the txt data in data = result.content.




回答2:


You can use the StringIO module to emulate a file object using the contents of your string.

from google.appengine.api import urlfetch
from StringIO import StringIO

result = urlfetch.fetch('http://example.com/test.txt')
f = StringIO(result.content)

You can then read() from the f object or use other file object methods like seek(), readline(), etc.



来源:https://stackoverflow.com/questions/12682983/open-a-file-from-urlfetch-in-gae

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!