0

I am following Massimiliano Pippi's Python for Google App engine. In chapter 3, we are trying to upload a file that the user of my app select thanks to this html code:

<div class="form-group">
            <label for="uploaded_file">Attached file:</label>
            <input type="file" id="uploaded_file" name="uploaded_file">
</div>

And from the python part, in my MainHandler on webapp2, I get the request content using:

def post(self):
    uploaded_file = self.request.POST.get("uploaded_file", None)
    file_name = getattr(uploaded_file, 'filename')
    file_content = getattr(uploaded_file, 'file', None)
    content_t = mimetypes.guess_type(file_name)[0]

    bucket_name = app_identity.get_default_gcs_bucket_name()
    path = os.path.join('/', bucket_name, file_name)
    with cloudstorage.open(path, 'w', content_type=content_t) as f:
        f.write(file_content.read())

The problem is that the variable uploaded_file is handled as if it was a file by Massimiliano Pippi, but my Python tells me that this variable is a unicode containing the name of the file. Therefore, when I try file_name = getattr(uploaded_file, 'filename'), I get an error.

Obviously, the code in the book is false, how can I fix it?

2
  • I haven't read that book , and you haven't said if your using webapp2. If you are the underlying request object is built using WebOb. WebOb uses a cgi.FieldStorage object to hold the file contents. Read up on WebOb (if the context of webapp2 holds true) and poke around at the contents of the request object and see what is there. On the dev server adding a strategic import pdb; pdb.set_trace() and using the debugger will teach you a whole lot of things about how the request object works. Commented Oct 25, 2015 at 12:09
  • yes I am using webapp2. I will check doc on WebOb, thanks for the tips. Commented Oct 25, 2015 at 12:13

1 Answer 1

1

Ok so after Tim's advice, I chcked the doc of WebOb and notice that in the html file, I should have put enctype="multipart/form-data" as follows:

<form action="" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="uploaded_file">Attached file:</label>
        <input type="file" id="uploaded_file" name="uploaded_file">
    </div>
</form>

Instead of:

<form action="" method="post">
    <div class="form-group">
        <label for="uploaded_file">Attached file:</label>
        <input type="file" id="uploaded_file" name="uploaded_file">
    </div>
</form>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.