ego008 avatar

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

🕠 by ego008

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- 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)

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 1ms