Skip to content

Instantly share code, notes, and snippets.

@ego008
Last active June 26, 2017 17:12
Show Gist options
  • Save ego008/4570847 to your computer and use it in GitHub Desktop.
Save ego008/4570847 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Example of how to use Poster.encode on AppEngine.
http://atlee.ca/software/poster/
The only variation needed versus the example from Poster is that
GAE's UrlFetch cannot use the generator returned by multipart_encode()
for payload, so simply create a payload string first.
"""
from google.appengine.ext import db, webapp
from google.appengine.api import urlfetch
from poster.encode import multipart_encode, MultipartParam
"""
class Image(db.Model):
filename = db.StringProperty()
mimetype = db.StringProperty()
blob = db.BlobProperty()
"""
class TestHandler(webapp.RequestHandler):
def get(self):
params = []
# Fabricate the form field <input name="FileItem1" type="file" />.
params.append(MultipartParam(
"FileItem1",
filename='myfile.txt',
filetype='text/plain',
value='this is a test'))
# Grab first Image entity that exists in datastore.
img = Image.all().get()
# Fabricate the form field <input name="FileItem2" type="file" />.
params.append(MultipartParam(
"FileItem2",
filename=img.filename,
filetype=img.mimetype,
value=img.blob))
# Fabricate the form field <input name="TextItem1" type="text" />.
params.append(MultipartParam(
'TextItem1',
value='My testing text.'))
# headers contains the necessary Content-Type and Content-Length
# payloadgen is a generator object that yields the encoded parameters
payloadgen, headers = multipart_encode(params)
# urlfetch cannot use a generator an argument for payload so
# build the payload as a string.
payload = str().join(payloadgen)
url = 'http://myserver.com/upload'
result = urlfetch.fetch(
url=url,
payload=payload,
method=urlfetch.POST,
headers=headers,
deadline=10)
self.response.out.write('HTTP RESPONSE STATUS: %s<br />' % result.status_code)
self.response.out.write(result.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment