您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Flask / MongoDB 搭建简易图片服务器

2025/4/3 3:13:06发布28次查看
前期准备 通过 pip 或 easy_install 安装了 pymongo 之后, 就能通过 python 调教 mongodb 了. 接着安装个 flask 用来当 web 服务器. 当然 mongo 也是得安装的. 对于 ubuntu 用户, 特别是使用 server 12.04 的同学, 安装最新版要略费些周折, 具体说是 sudoapt
前期准备通过 pip 或 easy_install 安装了 pymongo 之后, 就能通过 python 调教 mongodb 了.
接着安装个 flask 用来当 web 服务器.
当然 mongo 也是得安装的. 对于 ubuntu 用户, 特别是使用 server 12.04 的同学, 安装最新版要略费些周折, 具体说是
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7f0ceb10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
sudo apt-get update
sudo apt-get install mongodb-10gen
如果你跟我一样觉得让通过上传文件名的后缀判别用户上传的什么文件完全是捏着山药当小黄瓜一样欺骗自己, 那么最好还准备个 pillow 库
pip install pillow
或 (更适合 windows 用户)
easy_install pillow
正片flask 文件上传    flask 官网上那个例子居然分了两截让人无从吐槽. 这里先弄个最简单的, 无论什么文件都先弄上来
import flask
app = flask.flask(__name__)
app.debug = true
@app.route('/upload', methods=['post'])
def upload():
    f = flask.request.files['uploaded_file']
    print f.read()
    return flask.redirect('/')
@app.route('/')
def index():
    return '''
    nbsp;html>
'''
if __name__ == '__main__':
    app.run(port=7777)
注: 在 upload 函数中, 使用 flask.request.files[key] 获取上传文件对象, key 为页面 form 中 input 的 name 值    因为是在后台输出内容, 所以测试最好拿纯文本文件来测.
保存到 mongodb    如果不那么讲究的话, 最快速基本的存储方案里只需要
import pymongo
import bson.binary
from cstringio import stringio
app = flask.flask(__name__)
app.debug = true
db = pymongo.mongoclient('localhost', 27017).test
def save_file(f):
    content = stringio(f.read())
    db.files.save(dict(
        content=bson.binary.binary(content.getvalue()),
    ))
@app.route('/upload', methods=['post'])
def upload():
    f = flask.request.files['uploaded_file']
    save_file(f)
    return flask.redirect('/')
把内容塞进一个 bson.binary.binary 对象, 再把它扔进 mongodb 就可以了.
    现在试试再上传个什么文件, 在 mongo shell 中通过
db.files.find()
就能看到了. 不过 content 这个域几乎肉眼无法分辨出什么东西, 即使是纯文本文件, mongo 也会显示为 base64 编码.
提供文件访问    给定存进数据库的文件的 id (作为 uri 的一部分), 返回给浏览器其文件内容, 如下
def save_file(f):
    content = stringio(f.read())
    c = dict(content=bson.binary.binary(content.getvalue()))
    db.files.save(c)
    return c['_id']
@app.route('/f/')
def serve_file(fid):
    f = db.files.find_one(bson.objectid.objectid(fid))
    return f['content']
@app.route('/upload', methods=['post'])
def upload():
    f = flask.request.files['uploaded_file']
    fid = save_file(f)
    return flask.redirect('/f/' + str(fid))
上传文件之后, upload 函数会跳转到对应的文件浏览页. 这样一来, 文本文件内容就可以正常预览了, 如果不是那么挑剔换行符跟连续空格都被浏览器吃掉的话.
当找不到文件时    有两种情况, 其一, 数据库 id 格式就不对, 这时 pymongo 会抛异常 bson.errors.invalidid; 其二, 找不到对象 (!), 这时 pymongo 会返回 none.
    简单起见就这样处理了
@app.route('/f/')
def serve_file(fid):
    import bson.errors
    try:
        f = db.files.find_one(bson.objectid.objectid(fid))
        if f is none:
            raise bson.errors.invalidid()
        return f['content']
    except bson.errors.invalidid:
        flask.abort(404)
正确的 mime    从现在开始要对上传的文件严格把关了, 文本文件, 狗与剪刀等皆不能上传.
    判断图片文件之前说了我们动真格用 pillow
from pil import image
allow_formats = set(['jpeg', 'png', 'gif'])
def save_file(f):
    content = stringio(f.read())
    try:
        mime = image.open(content).format.lower()
        if mime not in allow_formats:
            raise ioerror()
    except ioerror:
        flask.abort(400)
    c = dict(content=bson.binary.binary(content.getvalue()))
    db.files.save(c)
    return c['_id']
然后试试上传文本文件肯定虚, 传图片文件才能正常进行. 不对, 也不正常, 因为传完跳转之后, 服务器并没有给出正确的 mimetype, 所以仍然以预览文本的方式预览了一坨二进制乱码.
    要解决这个问题, 得把 mime 一并存到数据库里面去; 并且, 在给出文件时也正确地传输 mimetype
def save_file(f):
    content = stringio(f.read())
    try:
        mime = image.open(content).format.lower()
        if mime not in allow_formats:
            raise ioerror()
    except ioerror:
        flask.abort(400)
    c = dict(content=bson.binary.binary(content.getvalue()), mime=mime)
    db.files.save(c)
    return c['_id']
@app.route('/f/')
def serve_file(fid):
    try:
        f = db.files.find_one(bson.objectid.objectid(fid))
        if f is none:
            raise bson.errors.invalidid()
        return flask.response(f['content'], mimetype='image/' + f['mime'])
    except bson.errors.invalidid:
        flask.abort(404)
当然这样的话原来存进去的东西可没有 mime 这个属性, 所以最好先去 mongo shell 用 db.files.drop() 清掉原来的数据.
根据上传时间给出 not modified    利用 http 304 not modified 可以尽可能压榨与利用浏览器缓存和节省带宽. 这需要三个操作
记录文件最后上传的时间当浏览器请求这个文件时, 向请求头里塞一个时间戳字符串当浏览器请求文件时, 从请求头中尝试获取这个时间戳, 如果与文件的时间戳一致, 就直接 304    体现为代码是
import datetime
def save_file(f):
    content = stringio(f.read())
    try:
        mime = image.open(content).format.lower()
        if mime not in allow_formats:
            raise ioerror()
    except ioerror:
        flask.abort(400)
    c = dict(
        content=bson.binary.binary(content.getvalue()),
        mime=mime,
        time=datetime.datetime.utcnow(),
    )
    db.files.save(c)
    return c['_id']
@app.route('/f/')
def serve_file(fid):
    try:
        f = db.files.find_one(bson.objectid.objectid(fid))
        if f is none:
            raise bson.errors.invalidid()
        if flask.request.headers.get('if-modified-since') == f['time'].ctime():
            return flask.response(status=304)
        resp = flask.response(f['content'], mimetype='image/' + f['mime'])
        resp.headers['last-modified'] = f['time'].ctime()
        return resp
    except bson.errors.invalidid:
        flask.abort(404)
然后, 得弄个脚本把数据库里面已经有的图片给加上时间戳.
    顺带吐个槽, 其实 nosql db 在这种环境下根本体现不出任何优势, 用起来跟 rdb 几乎没两样.
利用 sha-1 排重    与冰箱里的可乐不同, 大部分情况下你肯定不希望数据库里面出现一大波完全一样的图片. 图片, 连同其 exiff 之类的数据信息, 在数据库中应该是惟一的, 这时使用略强一点的散列技术来检测是再合适不过了.
    达到这个目的最简单的就是建立一个 sha-1 惟一索引, 这样数据库就会阻止相同的东西被放进去.
    在 mongodb 中表中建立惟一索引, 执行 (mongo 控制台中)
db.files.ensureindex({sha1: 1}, {unique: true})
如果你的库中有多条记录的话, mongodb 会给报个错. 这看起来很和谐无害的索引操作被告知数据库中有重复的取值 null (实际上目前数据库里已有的条目根本没有这个属性). 与一般的 rdb 不同的是, mongodb 规定 null, 或不存在的属性值也是一种相同的属性值, 所以这些幽灵属性会导致惟一索引无法建立.
    解决方案有三个
删掉现在所有的数据 (一定是测试数据库才用这种不负责任的方式吧!)建立一个 sparse 索引, 这个索引不要求幽灵属性惟一, 不过出现多个 null 值还是会判定重复 (不管现有数据的话可以这么搞)写个脚本跑一次数据库, 把所有已经存入的数据翻出来, 重新计算 sha-1, 再存进去    具体做法随意. 假定现在这个问题已经搞定了, 索引也弄好了, 那么剩是 python 代码的事情了.
import hashlib
def save_file(f):
    content = stringio(f.read())
    try:
        mime = image.open(content).format.lower()
        if mime not in allow_formats:
            raise ioerror()
    except ioerror:
        flask.abort(400)
sha1 = hashlib.sha1(content.getvalue()).hexdigest()
    c = dict(
        content=bson.binary.binary(content.getvalue()),
        mime=mime,
        time=datetime.datetime.utcnow(),
        sha1=sha1,
    )
    try:
        db.files.save(c)
    except pymongo.errors.duplicatekeyerror:
        pass
    return c['_id']
在上传文件这一环就没问题了. 不过, 按照上面这个逻辑, 如果上传了一个已经存在的文件, 返回 c['_id'] 将会是一个不存在的数据 id. 修正这个问题, 最好是返回 sha1, 另外, 在访问文件时, 相应地修改为用文件 sha-1 访问, 而不是用 id.
    最后修改的结果及本篇完整源代码如下
import hashlib
import datetime
import flask
import pymongo
import bson.binary
import bson.objectid
import bson.errors
from cstringio import stringio
from pil import image
app = flask.flask(__name__)
app.debug = true
db = pymongo.mongoclient('localhost', 27017).test
allow_formats = set(['jpeg', 'png', 'gif'])
def save_file(f):
    content = stringio(f.read())
    try:
        mime = image.open(content).format.lower()
        if mime not in allow_formats:
            raise ioerror()
    except ioerror:
        flask.abort(400)
sha1 = hashlib.sha1(content.getvalue()).hexdigest()
    c = dict(
        content=bson.binary.binary(content.getvalue()),
        mime=mime,
        time=datetime.datetime.utcnow(),
        sha1=sha1,
    )
    try:
        db.files.save(c)
    except pymongo.errors.duplicatekeyerror:
        pass
    return sha1
@app.route('/f/')
def serve_file(sha1):
    try:
        f = db.files.find_one({'sha1': sha1})
        if f is none:
            raise bson.errors.invalidid()
        if flask.request.headers.get('if-modified-since') == f['time'].ctime():
            return flask.response(status=304)
        resp = flask.response(f['content'], mimetype='image/' + f['mime'])
        resp.headers['last-modified'] = f['time'].ctime()
        return resp
    except bson.errors.invalidid:
        flask.abort(404)
@app.route('/upload', methods=['post'])
def upload():
    f = flask.request.files['uploaded_file']
    sha1 = save_file(f)
    return flask.redirect('/f/' + str(sha1))
@app.route('/')
def index():
    return '''
    nbsp;html>
'''
if __name__ == '__main__':
    app.run(port=7777)
原文地址:flask / mongodb 搭建简易图片服务器, 感谢原作者分享。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product