mongodb + nginx 存储照片方案

1. mongo中存储照片

方式一:存储本地图片

from pymongo import MongoClient
from gridfs import *

conn = MongoClient(["xxx1:37017", "xxx:47017", "xxx:57017"], replicaset="rs", connect=True)
# 必须是database
db = conn["test"]
with open("./img.png", "rb") as f:
    content = f.read()
    imgput = GridFS(db)
    # content,filename 用户自定义的参数,用于查询和分类,可以自定义多个参数
    insertimg = imgput.put(content, content_type="png", filename="img")
    # 611142397b8dfa47886211c1 返回的是 fs.files一条数据的_id
    print(insertimg)

完成查看数据库结果

自动生成collection:名字为fs.files

自动生成collection:名字为fs.chunks

导出图片

gridFS = GridFS(db, collection="fs")
count = 0
for grid_out in gridFS.find():
    count += 1
    print(count)
    data = grid_out.read()  # 获取图片数据
    outf = open('output.jpg', 'wb')  # 创建文件
    outf.write(data)  # 存储图片
    outf.close()

参考:https://blog.csdn.net/dk1543100966/article/details/81266632?utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-4.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromMachineLearnPai2~default-4.control

2. flask接口访问图片

from flask import Flask, request, Response
from pymongo import MongoClient
import gridfs

conn = MongoClient(["xxx:37017", "xxx:47017", "xxx:57017"], replicaset="rs", connect=True)
db = conn["test"]
app = Flask(__name__)


@app.route("/api/<filename>")
def test(filename):
    fs = gridfs.GridFS(db)
    thing = fs.get_last_version(filename=filename)
    resp = Response(thing, mimetype="image/jpg")
    return resp


if __name__ == '__main__':
    app.run(debug=True)

访问:http://127.0.0.1:5000/api/img

显示图片

posted @ 2021-08-09 23:31  张京墨  阅读(608)  评论(0编辑  收藏  举报