ped*_*ism 2 html python sql flask
我正在学习 Python 并使用 Flask 开发一个应用程序,其中一个功能是用户可以上传个人资料图片,并且该图像应该保存在数据库中。
我有一个用户可以上传文件的表单,如下所示:
<form action="/myprofile" method="post" enctype="multipart/form-data">
<div class="form-group">
<input class="form-control" name="picture" placeholder="Picture" type="file">
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
然后,在 application.py 文件中我像这样处理它:
@app.route("/myprofile", methods=["GET", "POST"])
@login_required
def myprofile():
if request.method == "POST":
db.execute("UPDATE users SET role = :role, picture = :picture, linkedin = :linkedin WHERE id = :user_id", role = request.form.get("role"), picture = request.files("picture"), linkedin = request.form.get("linkedin"), user_id = session["user_id"])
return render_template("home.html")
else:
return render_template("myprofile.html")
Run Code Online (Sandbox Code Playgroud)
这将返回内部服务器错误。有谁知道为什么吗?
谢谢你的时间!
我不知道你得到了什么错误,但是我想分享我之前关于将图像上传到 Flask 的答案之一。我准备了一个迷你应用程序,它使用flask、flask_sqlalchemy(带有sqlite3)、html和Bootstrap来完成您所要求的操作。
您可以在这里找到完整的代码(我将使用更安全的文件上传来更新它),因为这里给出的只是一小部分:
在类 FileContent(db.Model) 中:
data = file.read() 它将文件的二进制版本保存在数据库中 -render_file = render_picture(data)。它保存解码版本,以便您可以在网页中看到它并进行渲染。
# Built-in Imports
import os
from datetime import datetime
from base64 import b64encode
import base64
from io import BytesIO #Converts data from Database into bytes
# Flask
from flask import Flask, render_template, request, flash, redirect, url_for, send_file # Converst bytes into a file for downloads
# FLask SQLAlchemy, Database
from flask_sqlalchemy import SQLAlchemy
basedir = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data.sqlite')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = basedir
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'dev'
db = SQLAlchemy(app)
# Picture table. By default the table name is filecontent
class FileContent(db.Model):
"""
The first time the app runs you need to create the table. In Python
terminal import db, Then run db.create_all()
"""
""" ___tablename__ = 'yourchoice' """ # You can override the default table name
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
data = db.Column(db.LargeBinary, nullable=False) #Actual data, needed for Download
rendered_data = db.Column(db.Text, nullable=False)#Data to render the pic in browser
text = db.Column(db.Text)
location = db.Column(db.String(64))
pic_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
def __repr__(self):
return f'Pic Name: {self.name} Data: {self.data} text: {self.text} created on: {self.pic_date} location: {self.location}'
Run Code Online (Sandbox Code Playgroud)
以下是应用程序路线中发生的情况:
def render_picture(data) --> 获取图片的原始版本并返回解码版本,以便它可以用于在网络上显示。
data = file.read() :这是原始数据。可用于从数据库下载图片
render_file:解码文件,以便您可以检索它并在网页中渲染
#渲染图片,该函数将request.files['inputFile']中的数据进行转换,以便可以显示
def render_picture(data):
render_pic = base64.b64encode(data).decode('ascii')
return render_pic
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['inputFile']
data = file.read()
render_file = render_picture(data)
text = request.form['text']
location = request.form['location']
newFile = FileContent(name=file.filename, data=data,
rendered_data=render_file, text=text, location=location)
db.session.add(newFile)
db.session.commit()
flash(f'Pic {newFile.name} uploaded Text: {newFile.text} Location:
{newFile.location}')
return render_template('upload.html')
Run Code Online (Sandbox Code Playgroud)
# Index It routes to index.html where the upload forms is
@app.route('/index', methods=['GET', 'POST'])
@app.route('/')
def index():
return render_template('index.html')
Run Code Online (Sandbox Code Playgroud)
<form method="POST" action="/upload" enctype="multipart/form-data">
<!-- File Upload-->
<div class="form-group">
<label for="inputFile">File input</label>
<input class="form-control-file" type="file" name="inputFile">
</div>
<!-- Location -->
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location">
</div>
<!-- Text -->
<div class="form-group">
<label for="text">Write Text</label>
<textarea class="form-control" name="text" id="text" rows="5" placeholder="Add a Description"></textarea>
</div>
<!-- Submit -->
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14292 次 |
| 最近记录: |