我认为最简单的方法是在客户端进行确认。它在外观上并不漂亮,但是
a window.confirm('Are you sure?');会做同样的事情。也就是说,如果你只是在寻找服务器端解决方案,则可以创建一个
@/confirm/iation_required装饰器来处理重定向。然后,你可以包装需要确认的任何视图,并传入一个函数以获取要显示的消息。
from functools import wrapsfrom urllib import urlenpre, quote, unquotefrom flask import Flask, request, redirect, url_for, render_templateapp = Flask(__name__)def /confirm/iation_required(desc_fn): def inner(f): @wraps(f) def wrapper(*args, **kwargs): if request.args.get('/confirm/i') != '1': desc = desc_fn() return redirect(url_for('/confirm/i', desc=desc, action_url=quote(request.url))) return f(*args, **kwargs) return wrapper return inner@app.route('//confirm/i')def confirm(): desc = request.args['desc'] action_url = unquote(request.args['action_url']) return render_template('_/confirm/i.html', desc=desc, action_url=action_url)def you_sure(): return "Are you sure?"@app.route('/')@/confirm/iation_required(you_sure)def hello_world(): return 'Hello World!'if __name__ == '__main__': app.run(debug=True)_/confirm/i.html:<html xmlns="http://www.w3.org/1999/html"><body><h1>{{ desc }}</h1><form action="{{ action_url }}" method="GET"> <input type="hidden" name="/confirm/i" value="1"> <input type="submit" value="Yes"></form></body></html>请注意,尽管仅当你要包装的视图接受GET时才执行此重定向,并且对任何修改数据的操作都允许GET并不是一个好主意。(请参阅为什么不应该在HTTP GET请求上修改数据?)
更新:如果你真的想要一个与POST一起使用的通用解决方案,我将切换到基于类的视图并创建一个处理确认逻辑的mixin。就像是:
class ConfirmationViewMixin(object): /confirm/iation_template = '_/confirm/i.html' def get_/confirm/iation_context(self): # implement this in your view class raise NotImplementedError() def post(self): if request.args.get('/confirm/i') == '1': return super(/confirm/iationViewMixin, self).post() return render_template( self./confirm/iation_template, **self.get_/confirm/iation_context())


