ego008
ego008
3624 0 0

urlfetch.fetch, add request with a multipart/form-data POST

send HTTP POST using multipart/form-data in Google app engine's httplib

http://code.google.com/p/googleappengine/issues/attachmentText?id=627&aid=941648146561400028&name=handlers.py.stub&token=gjz1kzguQ6ZlI8cg60eu3snhDcM%3A1358567338814

# -*- 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)
0

See Also

Nearby


Discussion

Login Topics