【发布时间】:2015-10-15 18:28:59
【问题描述】:
我正在创建一个简单的 Web 应用程序,您可以在其中使用瓶子框架上传您的文章和图片。上传页面的HTML代码是:
<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>
我想将文章存储在 mongodb 数据库中,因此,我想将图像存储在 GridFS 中。同样的瓶子框架代码是:
@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"
但是当我运行这段代码时,我得到图像部分的以下错误:
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'
我在另一台机器上运行了完全相同的代码,它运行良好。但在我的笔记本电脑上它失败了。提前谢谢你。
【问题讨论】:
-
有趣的是,您的代码中有
img_content = image.file.read(),而您的错误归咎于img_content = image.files.read()...注意s? -
@Cyrbil 感谢您注意到这一点。我不小心上传了我在进行实验以将“文件”更改为“文件”时遇到的错误,以防万一确保后者是错误的。
标签: python html mongodb bottle gridfs