Google AppEngine Python Web upload file and read t

2019-07-30 03:56发布

I'm new at Python AND AppEngine, so maybe my question is basic but I've searched it for hours...

So, I'm using Google AppEngine with python and HTML...

So in my htlm file I have something like that :

 <form action="/sign?guestbook_name={{ guestbook_name }}" method="post">
  <div><input type="file" name="file"></div>
  <div><textarea name="content" rows="3" cols="60"></textarea></div>
  <div><input type="submit" value="Sign Guestbook"></div>
</form>

and in my py file, something like that :

class Guestbook(webapp2.RequestHandler):

    def post(self):
    # We set the same parent key on the 'Greeting' to ensure each Greeting
    # is in the same entity group. Queries across the single entity group
    # will be consistent. However, the write rate to a single entity group
    # should be limited to ~1/second.
    guestbook_name = self.request.get('guestbook_name',
                                      DEFAULT_GUESTBOOK_NAME)
    greeting = Greeting(parent=guestbook_key(guestbook_name))

    if users.get_current_user():
        greeting.author = users.get_current_user()

    greeting.content = self.request.get('file')


    greeting.put()

    query_params = {'guestbook_name': guestbook_name}
    self.redirect('/?' + urllib.urlencode(query_params))


application = webapp2.WSGIApplication([
('/', MainPage),
('/sign', Guestbook),
], debug=True)

So I saved thank's to the line " greeting.content = self.request.get('file')" the name of the file in the datastore.

But in fact I want to upload my file. Open and read the content thank's to python so that the user who upload it can see the content of the file in his browser.

How can I do it ?

I tried to use :

Import cgi
form = cgi.FieldStorage()

# A nested FieldStorage instance holds the file
fileitem = form['file']

But I have an Key error with 'file'.

So, how can I read the content of the file a user have uploaded directly in his browser ?

2条回答
We Are One
2楼-- · 2019-07-30 04:23

You can use cgi.FieldStorage() to upload a file < 32 megabytes. But you have to send the form as enctype="multipart/form-data"

<form action="/upload" enctype="multipart/form-data" method="post">
    <div><input type="file" name="file"/></div>
    <div><input type="submit" value="Upload"></div>
</form>

The post method in the /upload webapp2 request handler:

def post(self):

    field_storage = self.request.POST.get("file", None)
    if isinstance(field_storage, cgi.FieldStorage):
        file_name = field_storage.filename
        file_data = field_storage.file.read())
        ..... 

    else:
        logging.error('Upload failed')

Example taken from this gist

查看更多
对你真心纯属浪费
3楼-- · 2019-07-30 04:35

Try this:

fileitem = self.request.POST['file']

If you want to store the file I would look into uploading it straight to Blob store first then process it as needed.

https://developers.google.com/appengine/docs/python/blobstore/

查看更多
登录 后发表回答