python - 使用flask在html页面上从gridfs渲染图像
问题描述
我想使用烧瓶在我的 html pyge 上从 gridfs 渲染图像。我使用带有一个按钮的gridfs将图像存储在我的mongodb中,并使用Flask-Session将图像的ObjectId存储在服务器端会话中。当我单击另一个按钮时,我通过我的会话获得了之前存储的图像的正确 ObjectId,然后想在我的 html 页面中从 gridfs 呈现此图像,但我不知道该怎么做。
我的app.py
文件:
from flask import Flask, render_template, request, redirect, session
from werkzeug.utils import secure_filename
from pymongo import MongoClient
from gridfs import GridFS
from flask_session import Session
DB = 'test-grid'
COLLECT = 'test-session'
client = MongoClient('mongodb://127.0.0.1:27017')
db = client[DB]
fs = GridFS(db)
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16*1024*1024
app.config['SESSION_TYPE'] = 'mongodb'
app.config['SESSION_MONGODB'] = client
app.config['SESSION_MONGODB_DB'] = DB
app.config['SESSION_MONGODB_COLLECT'] = COLLECT
Session(app)
@app.route("/")
def home():
return render_template("index.html")
@app.route('/upload', methods=['POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
filename = secure_filename(f.filename)
f_id = fs.put(f, filename=filename)
session['f_id'] = f_id
session['filename'] = filename
return redirect('/')
@app.route('/display', methods=['GET'])
def display_file():
if request.method == 'GET':
f = fs.get(session['f_id'])
image = f.read()
return render_template("index.html", user_image=image)
if __name__ == "__main__":
app.run(debug=True)
我的index.html
文件:
<html lang='en'>
<head>
<meta charset='UTF-8'/>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="file" autocomplete="off" required>
</form>
<form method="get" action="/display">
<input type="submit" value="Display">
</form>
<img src="{{ user_image }}" alt="Show image here"/>
</body>
</html>
我的requirements.txt
文件:
Flask
Flask-Session
pymongo
但这不起作用,我得到以下输出: 输出
有人可以帮我解决这个问题吗?也许有例子我可以查一下。
解决方案
推荐阅读
- c++ - 如何从cpp中的函数返回字典
- swift - 以编程方式设置 CFBundleShortVersionString
- argo-workflows - 在 Argo Workflows 中定义工作流之间的依赖关系
- java - 断言这两个列表具有相同的长度。创建所有姓名和姓氏的列表
- entity-framework-core - EFCore 和 C# 5.0 的多对多关系:如何从两个表中获取字段
- python - 从班级打开的窗口显示不正确
- plot - AttributeError: 'list' object has no attribute 'shape', 如何解决这个错误
- android - 如何制作一个返回通用对象的函数?
- npm - Npm 在定义对等依赖时包括所有预发布范围
- reactjs - 如何重用重载的函数类型并将其分配给另一个函数?