我正在使用python和flask进行图像上传器构建。我把它放在我的VPS上运行
http://107.170.119.38/
应用程序显示前25个图像就好了,但是第25个图像之后的任何内容都不会显示在任何地方。我正在尝试添加一个按钮,允许我显示下面的25个图像。这是我的代码示例
@app.route('/', methods=['GET', 'POST'])
def get_more_pics():
g.db = connect_db()
cur = g.db.execute('select filename, label from pics order by id desc limit 25')
more_pics = [dict("filename": row[0], "label": row[1]) for row in cur.fetchall()]
g.db.close()
return render_template('upload.html', more_pics=more_pics)
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())
@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)
# 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 []
并在jinja2模板文件中:
<input type="button" value="Get More Pics" onclick="{{ more_pics }}">
<ul>
{% for pic in more_pics %}
<li class="thumb">
<a href="{{ url_for('show_pic', filename=pic.filename) }}"><img class="thumb" src="{{ pic_path('thumb2_'+pic.filename) }}"></a></li>
{% endfor %}
</ul>
总而言之,我无法弄清楚如何让get_more_pics()函数显示接下来的25个图像。任何帮助将不胜感激
答案 0 :(得分:1)
您需要在SQL中添加offset
参数:
select filename, label from pics order by id desc limit 25 offset 0
你必须将它传递给你的SQL,因为它对于第一页是0,然后是25,然后是50,等等。可能更好的是将25分解为参数而不是硬编码,并将偏移量计算为页面和限制的乘积。
另外,请记住,LIMIT和OFFSET不一定适用于所有数据库,尽管它们可以与SQLite和MySQL一起使用,但语法可能会有所不同。例如。对于Oracle:http://www.oracle-base.com/articles/12c/row-limiting-clause-for-top-n-queries-12cr1.php。
另一种方法是使用略高级别的方法,例如ORM。