I am creating a simple web application, where you can upload your article along with an image, using bottle framework. The HTML code for the upload page is:
<html>
<body>
<form action="/created" method="POST" encrypt="multipart/form-data">
Title: <input type="text" name="title"><br>
Body: <textarea rows = 10 name="body"></textarea><br>
Choose image: <input type="file" name="image" ><br>
<input type="submit" >
</form>
</body>
</html>
I want to store the article in mongodb database and so, I want to store the image in GridFS. The bottle framework code for the same is:
@post("/created")
def created():
connect = pymongo.MongoClient(server_address)
db = connect.practiceB3
articles = db.articles
title = request.forms.get('title')
body = request.forms.get('body')
fs = gridfs.GridFS(db)
image = request.files.get('image')
img_content = image.file.read()
img_name = image.filename
document = { "title":title,"body":body}
articles.insert(document)
fs.put(img_content,filename = img_name)
return "Article successfully stored"
But when I run this code, I get the following error for the image section:
Error: 500 Internal Server Error
Sorry, the requested URL 'http://localhost:8080/created.html' caused an error:
Internal Server Error
Exception:
AttributeError("'NoneType' object has no attribute 'file'",)
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 862, in _handle
return route.call(**args)
File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 1732, in wrapper
rv = callback(*a, **ka)
File "blogger.py", line 70, in created
img_content = image.file.read()
AttributeError: 'NoneType' object has no attribute 'file'
I have run the exact same code on another machine and it worked perfectly. But on my laptop it fails. Thank you in advance.
For your error, if request.files.get('image')
have no index 'image'
, it will return None
(default behavior of dict.get()
.
So the next line will fail image.file.read()
.
Ensure your form do really send an image (with your browser webtools).