Python中使用Flask、MongoDB搭建简易图片服务器

转载:http://www.cppcns.com/shujuku/mongodb/119378.html

这篇文章主要介绍了Python中使用Flask、MongoDB搭建简易图片服务器,本文是一个详细完整的教程,需要的朋友可以参考下

1、前期准备

通过 pip 或 easy_install 安装了 pymongo 之后, 就能通过 Python 调教 mongodb 了.
接着安装个 flask 用来当 web 服务器.

当然 mongo 也是得安装的. 对于 Ubuntu 用户, 特别是使用 Server 12.04 的同学, 安装最新版要略费些周折, 具体说是

 
  1. sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
  2. echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
  3. sudo apt-get update
  4. sudo apt-get install mongodb-10gen

如果你跟我一样觉得让通过上传文件名的后缀判别用户上传的什么文件完全是捏着山药当小黄瓜一样欺骗自己, 那么最好还准备个 Pillow 库

复制代码 代码如下:


pip install Pillow

或 (更适合 Windows 用户)

复制代码 代码如下:


easy_install Pillow

2、正片

2.1 Flask 文件上传

Flask 官网上那个例子居然分了两截让人无从吐槽. 这里先弄个最简单的, 无论什么文件都先弄上来

 
  1. import flask
  2. app = flask.Flask(__name__)
  3. app.debug = True
  4. @app.route('/upload', methods=['POST'])
  5. def upload():
  6. f = flask.request.files['uploaded_file']
  7. print f.read()
  8. return flask.redirect('/')
  9. @app.route('/')
  10. def index():
  11. return '''
  12. <!doctype html>
  13. <html>
  14. <body>
  15. <form action='/upload' method='post' enctype='multipart/form-data'>
  16. <input type='file' name='uploaded_file'>
  17. <input type='submit' value='Upload'>
  18. </form>
  19. '''
  20. if __name__ == '__main__':
  21. app.run(port=7777)

注: 在 upload 函数中, 使用 flask.request.files[KEY] 获取上传文件对象, KEY 为页面 form 中 input 的 name 值

因为是在后台输出内容, 所以测试最好拿纯文本文件来测.

2.2 保存到 mongodb

如果不那么讲究的话, 最快速基本的存储方案里只需要

 
  1. import pymongo
  2. import bson.binary
  3. from cStringIO import StringIO
  4. app = flask.Flask(__name__)
  5. app.debug = True
  6. db = pymongo.MongoClient('localhost', 27017).test
  7. def save_file(f):
  8. content = StringIO(f.read())
  9. db.files.save(dict(
  10. content= bson.binary.Binary(content.getvalue()),
  11. ))
  12. @app.route('/upload', methods=['POST'])
  13. def upload():
  14. f = flask.request.files['uploaded_file']
  15. save_file(f)
  16. return flask.redirect('/')
  17.  

把内容塞进一个  bson.binary.Binary  对象, 再把它扔进 mongodb 就可以了.

现在试试再上传个什么文件, 在 mongo shell 中通过  db.files.find() 就能看到了.

不过 content  这个域几乎肉眼无法分辨出什么东西, 即使是纯文本文件, mongo 也会显示为 Base64 编码.

2.3 提供文件访问

给定存进数据库的文件的 ID (作为 URI 的一部分), 返回给浏览器其文件内容, 如下

 
  1. def save_file(f):
  2. content = StringIO(f.read())
  3. c = dict(content=bson.binary.Binary(content.getvalue()))
  4. db.files.save(c)
  5. return c['_id']
  6. @app.route('/f/<fid>')
  7. def serve_file(fid):
  8. f = db.files.find_one(bson.objectid.ObjectId(fid))
  9. return f['content']
  10. @app.route('/upload', methods=['POST'])
  11. def upload():
  12. f = flask.request.files['uploaded_file']
  13. fid = save_file(f)
  14. return flask.redirect( '/f/' + str(fid))
  15.  

上传文件之后,  upload  函数会跳转到对应的文件浏览页. 这样一来, 文本文件内容就可以正常预览了, 如果不是那么挑剔换行符跟连续空格都被浏览器吃掉的话.

2.4 当找不到文件时

有两种情况, 其一, 数据库 ID 格式就不对, 这时 pymongo 会抛异常  bson.errors.InvalidId ; 其二, 找不到对象 (!), 这时 pymongo 会返回  None .
简单起见就这样处理了

 
  1. @app.route('/f/<fid>')
  2. def serve_file(fid):
  3. import bson.errors
  4. try:
  5. f = db.files.find_one(bson.objectid.ObjectId(fid))
  6. if f is None:
  7. raise bson.errors.InvalidId()
  8. return f['content']
  9. except bson.errors.InvalidId:
  10. flask.abort(404)
  11.  

2.5 正确的 MIME

从现在开始要对上传的文件严格把关了, 文本文件, 狗与剪刀等皆不能上传.
判断图片文件之前说了我们动真格用 Pillow

 
  1. from PIL import Image
  2. allow_formats = set(['jpeg', 'png', 'gif'])
  3. def save_file(f):
  4. content = StringIO(f.read())
  5. try:
  6. mime = Image.open(content).format.lower()
  7. if mime not in allow_formats:
  8. raise IOError()
  9. except IOError:
  10. flask.abort(400)
  11. c = dict(content=bson.binary.Binary(content.getvalue()))
  12. db.files.save(c)
  13. return c['_id']
  14.  

然后试试上传文本文件肯定虚, 传图片文件才能正常进行. 不对, 也不正常, 因为传完跳转之后, 服务器并没有给出正确的 mimetype, 所以仍然以预览文本的方式预览了一坨二进制乱码.
要解决这个问题, 得把 MIME 一并存到数据库里面去; 并且, 在给出文件时也正确地传输 mimetype

 
  1. def save_file(f):
  2. content = StringIO(f.read())
  3. try:
  4. mime = Image.open(content).format.lower()
  5. if mime not in allow_formats:
  6. raise IOError()
  7. except IOError:
  8. flask.abort(400)
  9. c = dict(content=bson.binary.Binary(content.getvalue()), mime=mime)
  10. db.files.save(c)
  11. return c['_id']
  12. @app.route('/f/<fid>')
  13. def serve_file(fid):
  14. try:
  15. f = db.files.find_one(bson.objectid.ObjectId(fid))
  16. if f is None:
  17. raise bson.errors.InvalidId()
  18. return flask.Response(f['content'], mimetype='image/' + f['mime'])
  19. except bson.errors.InvalidId:
  20. flask.abort(404)
  21.  

当然这样的话原来存进去的东西可没有 mime 这个属性, 所以最好先去 mongo shell 用  db.files.drop()  清掉原来的数据.

2.6 根据上传时间给出 NOT MODIFIED
利用 HTTP 304 NOT MODIFIED 可以尽可能压榨与利用浏览器缓存和节省带宽. 这需要三个操作

1)、记录文件最后上传的时间
2)、当浏览器请求这个文件时, 向请求头里塞一个时间戳字符串
3)、当浏览器请求文件时, 从请求头中尝试获取这个时间戳, 如果与文件的时间戳一致, 就直接 304

体现为代码是

 
  1. import datetime
  2. def save_file(f):
  3. content = StringIO(f.read())
  4. try:
  5. mime = Image.open(content).format.lower()
  6. if mime not in allow_formats:
  7. raise IOError()
  8. except IOError:
  9. flask.abort(400)
  10. c = dict(
  11. content=bson.binary.Binary(content.getvalue()),
  12. mime=mime,
  13. time=datetime.datetime.utcnow(),
  14. )
  15. db.files.save(c)
  16. return c['_id']
  17. @app.route('/f/<fid>')
  18. def serve_file(fid):
  19. try:
  20. f = db.files.find_one(bson.objectid.ObjectId(fid))
  21. if f is None:
  22. raise bson.errors.InvalidId()
  23. if flask.request.headers.get('If-Modified-Since') == f['time'].ctime():
  24. return flask.Response(status=304)
  25. resp = flask.Response(f['content'], mimetype='image/' + f['mime'])
  26. resp.headers['Last-Modified'] = f['time'].ctime()
  27. return resp
  28. except bson.errors.InvalidId:
  29. flask.abort(404)
  30.  

然后, 得弄个脚本把数据库里面已经有的图片给加上时间戳.
顺带吐个槽, 其实 NoSQL DB 在这种环境下根本体现不出任何优势, 用起来跟 RDB 几乎没两样.

2.7 利用 SHA-1 排重

与冰箱里的可乐不同, 大部分情况下你肯定不希望数据库里面出现一大波完全一样的图片. 图片, 连同其 EXIFF 之类的数据信息, 在数据库中应该是惟一的, 这时使用略强一点的散列技术来检测是再合适不过了.

达到这个目的最简单的就是建立一个  SHA-1  惟一索引, 这样数据库就会阻止相同的东西被放进去.

在 MongoDB 中表中建立惟一 索引 , 执行 (Mongo 控制台中)

复制代码 代码如下:


db.files.ensureIndex({sha1: 1}, {unique: true})

如果你的库中有多条记录的话, MongoDB 会给报个错. 这看起来很和谐无害的索引操作被告知数据库中有重复的取值 null (实际上目前数据库里已有的条目根本没有这个属性). 与一般的 RDB 不同的是, MongoDB 规定 null, 或不存在的属性值也是一种相同的属性值, 所以这些幽灵属性会导致惟一索引无法建立.

解决方案有三个:

1)删掉现在所有的数据 (一定是测试数据库才用这种不负责任的方式吧!)
2)建立一个 sparse 索引, 这个索引不要求幽灵属性惟一, 不过出现多个 null 值还是会判定重复 (不管现有数据的话可以这么搞)
3)写个脚本跑一次数据库, 把所有已经存入的数据翻出来, 重新计算 SHA-1, 再存进去
具体做法随意. 假定现在这个问题已经搞定了, 索引也弄好了, 那么剩是 Python 代码的事情了.

 
  1. import hashlib
  2. def save_file(f):
  3. content = StringIO(f.read())
  4. try:
  5. mime = Image.open(content).format.lower()
  6. if mime not in allow_formats:
  7. raise IOError()
  8. except IOError:
  9. flask.abort(400)
  10. sha1 = hashlib.sha1(content.getvalue()).hexdigest()
  11. c = dict(
  12. content=bson.binary.Binary(content.getvalue()),
  13. mime=mime,
  14. time=datetime.datetime.utcnow(),
  15. sha1=sha1,
  16. )
  17. try:
  18. db.files.save(c)
  19. except pymongo.errors.DuplicateKeyError:
  20. pass
  21. return c['_id']
  22.  

在上传文件这一环就没问题了. 不过, 按照上面这个逻辑, 如果上传了一个已经存在的文件, 返回  c['_id']  将会是一个不存在的数据 ID. 修正这个问题, 最好是返回  sha1 , 另外, 在访问文件时, 相应地修改为用文件 SHA-1 访问, 而不是用 ID.
最后修改的结果及本篇完整源代码如下 :

 
  1. import hashlib
  2. import datetime
  3. import flask
  4. import pymongo
  5. import bson.binary
  6. import bson.objectid
  7. import bson.errors
  8. from cStringIO import StringIO
  9. from PIL import Image
  10. app = flask.Flask(__name__)
  11. app.debug = True
  12. db = pymongo.MongoClient('localhost', 27017).test
  13. allow_formats = set(['jpeg', 'png', 'gif'])
  14. def save_file(f):
  15. content = StringIO(f.read())
  16. try:
  17. mime = Image.open(content).format.lower()
  18. if mime not in allow_formats:
  19. raise IOError()
  20. except IOError:
  21. flask.abort(400)
  22. sha1 = hashlib.sha1(content.getvalue()).hexdigest()
  23. c = dict(
  24. content=bson.binary.Binary(content.getvalue()),
  25. mime=mime,
  26. time=datetime.datetime.utcnow(),
  27. sha1=sha1,
  28. )
  29. try:
  30. db.files.save(c)
  31. except pymongo.errors.DuplicateKeyError:
  32. pass
  33. return sha1
  34. @app.route('/f/<sha1>')
  35. def serve_file(sha1):
  36. try:
  37. f = db.files.find_one({'sha1': sha1})
  38. if f is None:
  39. raise bson.errors.InvalidId()
  40. if flask.request.headers.get('If-Modified-Since') == f['time'].ctime():
  41. return flask.Response(status=304)
  42. resp = flask.Response(f['content'], mimetype='image/' + f['mime'])
  43. resp.headers['Last-Modified'] = f['time'].ctime()
  44. return resp
  45. except bson.errors.InvalidId:
  46. flask.abort(404)
  47. @app.route('/upload', methods=['POST'])
  48. def upload():
  49. f = flask.request.files['uploaded_file']
  50. sha1 = save_file(f)
  51. return flask.redirect('/f/' + str(sha1))
  52. @app.route('/')
  53. def index():
  54. return '''
  55. <!doctype html>
  56. <html>
  57. <body>
  58. <form action='/upload' method='post' enctype='multipart/form-data'>
  59. <input type='file' name='uploaded_file'>
  60. <input type='submit' value='Upload'>
  61. </form>
  62. '''
  63. if __name__ == '__main__':
  64. app.run(port=7777)
  65.  


3、REF

Developing RESTful Web APIs with Python, Flask and MongoDB

http://www.slideshare.net/nicolaiarocci/developing-restful-web-apis-with-python-flask-and-mongodb

https://github.com/nicolaiarocci/eve

猜你喜欢

转载自blog.csdn.net/weixin_39121325/article/details/84229877