kennysong
kennysong

Reputation: 2124

Open a file from urlfetch in GAE

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

Upvotes: 1

Views: 1232

Answers (2)

David Parrish
David Parrish

Reputation: 33

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.

Upvotes: 3

voscausa
voscausa

Reputation: 11706

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

Upvotes: 2

Related Questions