gpt4 book ai didi

python - 使用 Flask 上传图片和标签

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:16 25 4
gpt4 key购买 nike

我正在玩弄一个使用 Flask 的图片 uploader 。我从这个存储库中克隆了它 https://github.com/chokepoint/flaskgur .我在我的 VPS 上运行它

http://107.170.119.38

我想做的是让某人能够为他们即将上传的图像编写自定义标签。最终产品应显示图像和用户输入的自定义标签。图像 uploader 工作正常但我似乎无法在上传时将标签存储在数据库中。这是我的代码

from flask import Flask, request, g, redirect, url_for, abort, render_template,send_from_directory
from werkzeug import secure_filename
from hashlib import md5
from PIL import Image
import sqlite3
import os
import time

DEBUG = True
BASE_DIR = '/var/www/flaskgur/'
UPLOAD_DIR = BASE_DIR + 'pics'
DATABASE = BASE_DIR + 'flaskgur.db'
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config.from_object(__name__)

# Make sure extension is in the ALLOWD_EXTENSIONS set
def check_extension(extension):
return extension in ALLOWED_EXTENSIONS

def connect_db():
return sqlite3.connect(app.config['DATABASE'])

# Return a list of the last 25 uploaded images
def get_last_pics():
cur = g.db.execute('select * from pics order by id desc limit 25')
filenames = [dict(id=row[0], filename=row[1], label=row[2]) for row in cur.fetchall()]
#filenames = [row[0] for row in cur.fetchall()]
return filenames

# Insert filename into database
def add_pic(filename, label):
g.db.executemany('insert into pics (filename, label) values (?, ?)', [filename, label])
g.db.commit()

# Generate thumbnail image
def gen_thumbnail(filename):
height = width = 200
original = Image.open(os.path.join(app.config['UPLOAD_DIR'], filename))
thumbnail = original.resize((width, height), Image.ANTIALIAS)
thumbnail.save(os.path.join(app.config['UPLOAD_DIR'], 'thumb_'+filename))


def add_label(label):
label = request.form['label']
g.db.execute('INSERT INTO pics (label) VALUES (?)', [label])
g.db.commit()


# Taken from flask example app
@app.before_request
def before_request():
g.db = connect_db()

# Taken from flask example app
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()

@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404

@app.route('/', methods=['GET','POST'])
def upload_pic():
if request.method == 'POST':
file = request.files['file']
try:
extension = file.filename.rsplit('.', 1)[1].lower()
except IndexError, e:
abort(404)
if file and check_extension(extension):
# Salt and hash the file contents
filename = md5(file.read() + str(round(time.time() * 1000))).hexdigest() + '.' + extension
file.seek(0) # Move cursor back to beginning so we can write to disk
file.save(os.path.join(app.config['UPLOAD_DIR'], filename, label))
add_pic(filename)
add_label(label)
gen_thumbnail(filename)
return redirect(url_for('show_pic', filename=filename))
else: # Bad file extension
abort(404)
else:
return render_template('upload.html', pics=get_last_pics())

@app.route('/show')
def show_pic():
filename = request.args.get('filename','')
return render_template('upload.html', filename=filename, label=label)
def show_label():
g.db = connect_db()
cur = g.db.execute('SELECT label FROM pics WHERE id=(?)')
labels = cur.fetchone()
return render_template('upload.html', labels=labels)

@app.route('/pics/<filename>')
def return_pic(filename):
return send_from_directory(app.config['UPLOAD_DIR'], secure_filename(filename))

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

还有我的模板 (upload.html):

{% if filename is defined %}
<div id="image"><a href="{{ pic_path(filename) }}" target="_blank"><img class="new" src="{{ pic_path(filename) }}"></a></div>

<h2><p>The Label is: </p>{{ labels }}</h2>


{% else %}
<ul>
{% for pic in pics %}
<li class="thumb"><a href="{{ url_for('show_pic', filename=pic) }}"><img class="thumb" src="{{ pic_path('thumb_'+pic) }}"></a></li>
{% endfor %}

基础模板(base.html):

    <div id="upload">
<h1>Upload Picture</h1>
<form action="/" method=post enctype=multipart/form-data>
<p>
<input type=file name=file><br />
<p>Add a Label:</p>
<input type=text name=label value={{ request.form.label }}><br />
<input type=submit value=Upload>
</p>
</div>

如果我的代码很糟糕,我深表歉意。我正在努力学习

最佳答案

我想通了。将 get_last_pics() 函数重写为:

# Return a list of the last 25 uploaded images
def get_last_pics():
try:
cur = g.db.execute('select filename, label from pics order by id desc limit 25')
filenames = []
for row in cur.fetchall():
filenames.append({"filename": row[0], "label": row[1] or ''})
return filenames
except:
return []

将 add_pic() 重写为:

# Insert filename and label into database
def add_pic(filename, label):
g.db.execute('insert into pics (filename, label) values (?, ?)', [filename, label])
g.db.commit()

将 upload_pic() 重写为:

@app.route('/', methods=['GET', 'POST'])
def upload_pic():
if request.method == 'POST':
file = request.files['file']
label = request.form['label']
try:
extension = file.filename.rsplit('.', 1)[1].lower()
except IndexError, e:
abort(404)
if file and check_extension(extension):
# Salt and hash the file contents
filename = md5(file.read() + str(round(time.time() * 1000))).hexdigest() + '.' + extension
file.seek(0) # Move cursor back to beginning so we can write to disk
file.save(os.path.join(app.config['UPLOAD_DIR'], filename))
add_pic(filename, label)
gen_thumbnail(filename)
return redirect(url_for('show_pic', filename=filename))
else:
# Bad file extension
abort(404)
else:
return render_template('upload.html', pics=get_last_pics())

将 show_pic() 重写为:

@app.route('/show')
def show_pic():
filename = request.args.get('filename', '')
t = (filename,)
cur = g.db.execute('select label from pics where filename=?', t)
label = cur.fetchone()[0]

return render_template('upload.html', filename=filename, label=label)

现在一切正常。希望对以后的人有所帮助

关于python - 使用 Flask 上传图片和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25756177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com