Post request with multipart/form-data in appengine python not working

前端 未结 2 1032
予麋鹿
予麋鹿 2020-12-18 05:44

I\'m attempting to send a multipart post request from an appengine app to an external (django) api hosted on dotcloud. The request includes some text and a file (pdf) and is

相关标签:
2条回答
  • 2020-12-18 06:33

    Here is some code I tested locally that should do the trick (I used a different handler than webapp2 but tried to modify it to webapp2. You'll also need the poster lib found here http://atlee.ca/software/poster/):

    In your POST handler on GAE:

    from google.appengine.api import urlfetch
    from poster.encode import multipart_encode
    payload = {}
    payload['test_file'] = self.request.POST['test_file']
    payload['user_id'] = self.request.POST['user_id']
    to_post = multipart_encode(payload)
    send_url = "http://127.0.0.1:8000/"
    result = urlfetch.fetch(url=send_url, payload="".join(to_post[0]), method=urlfetch.POST, headers=to_post[1])
    logging.info(result.content)
    

    Make sure your HTML form contains method="POST" enctype="multipart/form-data". Hope this helps!

    EDIT: I tried using the webapp2 handler and realized the way files are served are different than how the framework I used to test with works (KAY). Here is updated code that should do the trick (tested on production):

    import webapp2
    from google.appengine.api import urlfetch
    from poster.encode import multipart_encode, MultipartParam
    
    class UploadTest(webapp2.RequestHandler):
      def post(self): 
        payload = {}
        file_data = self.request.POST['test_file']
        payload['test_file'] = MultipartParam('test_file', filename=file_data.filename,
                                              filetype=file_data.type,
                                              fileobj=file_data.file)
        payload['name'] = self.request.POST['name']
        data,headers= multipart_encode(payload)
        send_url = "http://127.0.0.1:8000/"
        t = urlfetch.fetch(url=send_url, payload="".join(data), method=urlfetch.POST, headers=headers)
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(t.content)
      def get(self):
        self.response.out.write("""
        <html>
            <head>
                <title>File Upload Test</title>
            </head>
            <body>
                <form action="" method="POST" enctype="multipart/form-data">
                    <input type="text" name="name" />
                    <input type="file" name="test_file" />
                    <input type="submit" value="Submit" />
                </form>
            </body>
        </html>""")
    
    0 讨论(0)
  • 2020-12-18 06:33

    You're urlencoding the data where you should be multipart_encoding it. Have a look at this: Trying to post multipart form data in python, won't post

    0 讨论(0)
提交回复
热议问题