Open a file from urlfetch in GAE

2019-05-31 15:15发布

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

2条回答
Juvenile、少年°
2楼-- · 2019-05-31 15:18

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

查看更多
\"骚年 ilove
3楼-- · 2019-05-31 15:28

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.

查看更多
登录 后发表回答