redirect()函数允许我们将用户重定向到我们选择的URL。在我们目前正在构建的Flask应用程序中,我们有一个*/shortenurl*路由,可以检查使用的是什么方法类型。如果是GET请求,我们就会简单地返回一些文本给用户。取而代之的是,我们可以将他们重定向到主页,这样他们就可以输入一个URL和短码。这里的代码中强调了重定向的使用。
flask-tutorial/app.py
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
if request.method == 'POST':
return render_template('shortenurl.html', shortcode=request.form['shortcode'])
elif request.method == 'GET':
return redirect('/')
else:
return 'Not a valid request method for this route'
现在试着在网页浏览器中直接进入127.0.0.1:5000/shortenurl。你会发现,你会立即被重定向到主页(/)路线,并且显示我们之前创建的表单。

url_for()
在Flask中执行重定向时,你可以使用的另一种方法是url_for()函数。url_for()的工作方式是,你提供你想重定向的路由的函数名,而不是根据路由的字符串表示来重定向。因此,如果我们将代码更新为这里的片段,我们会得到相同的结果,但使用url_for()而不是redirect()。还要注意,redirect和url_for都是在app.py的第一行导入的。
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
if request.method == 'POST':
return render_template('shortenurl.html', shortcode=request.form['shortcode'])
elif request.method == 'GET':
return redirect(url_for('home'))
else:
return 'Not a valid request method for this route'
短码到URL重定向
这个应用程序需要两个输入,一个是你想访问的URL,另一个是代表该URL的短代码
from flask import Flask, render_template, request, redirect, url_for
import json
import os.path
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
if request.method == 'POST':
urls = {}
if os.path.exists('urls.json'):
with open('urls.json') as url_storage:
urls = json.load(url_storage)
if request.form['shortcode'] in urls.keys():
return redirect(url_for('home'))
urls[request.form['shortcode']] = request.form['url']
with open('urls.json', 'w') as url_storage:
json.dump(urls, url_storage)
return render_template('shortenurl.html', shortcode=request.form['shortcode'])
elif request.method == 'GET':
return redirect(url_for('home'))
else:
return 'Not a valid request method for this route'
现在,当我们添加另一个短码/URL组合时,它会显示在创建的JSON存储中。


在Flask项目根中,现在有一个urls.json文件,当我们打开它时,我们到目前为止提交的数据就在那里。

执行重定向短码到URL的操作
在这一点上,我们可以添加代码,将用户从短代码带到一个实际的网站。
from flask import Flask, render_template, request, redirect, url_for
import json
import os.path
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/shortenurl', methods=['GET', 'POST'])
def shortenurl():
if request.method == 'POST':
urls = {}
if os.path.exists('urls.json'):
with open('urls.json') as url_storage:
urls = json.load(url_storage)
if request.form['shortcode'] in urls.keys():
return redirect(url_for('home'))
urls[request.form['shortcode']] = request.form['url']
with open('urls.json', 'w') as url_storage:
json.dump(urls, url_storage)
return render_template('shortenurl.html', shortcode=request.form['shortcode'])
elif request.method == 'GET':
return redirect(url_for('home'))
else:
return 'Not a valid request method for this route'
@app.route('/<string:shortcode>')
def shortcode_redirect(shortcode):
if os.path.exists('urls.json'):
with open('urls.json') as url_storage:
urls = json.load(url_storage)
if shortcode in urls.keys():
return redirect(urls[shortcode])
当然,这现在已经开始工作了。
