无法使用烧瓶重定向 python 中的变量
Unable to redirect variable in python with flask
昨天开始学习Flask,遇到了一个变量重定向的坑。我也尝试过不使用会话,但无法取得成功。
代码如下-
from flask import Flask, render_template, request, redirect, url_for, session
from flask_wtf import Form
from wtforms import StringField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'our very hard to guess secretfir'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
def translate_text(target, text):
import six
from google.cloud import translate_v2 as translate
translate_client = translate.Client()
if isinstance(text, six.binary_type):
text = text.decode("utf-8")
# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(text, target_language=target)
output_text = format(result["translatedText"])
return output_text
# approach using WTForms
class RegistrationForm(Form):
input_lang = StringField('Input Language in length(2) ==> ')
output_lang = StringField('Output Language in length(2) ==> ')
input_text = StringField('Input Text ==> ')
@app.route('/translate', methods=['GET', 'POST'])
def translate():
error = ""
form = RegistrationForm(request.form)
if request.method == 'POST':
input_lang = form.input_lang.data
output_lang = form.output_lang.data
input_text = form.input_text.data
if len(input_lang) != 2 or len(output_lang) != 2 or len(input_text) == 0:
error = "Please supply proper inputs! "
else:
translated_text = translate_text(output_lang, input_text)
session['translated_text'] = translated_text
return redirect(url_for('thank_you',transalted_text=translated_text))
return render_template('translate.html', form=form, message=error)
# Run the application
app.run(debug=True)
每当我提交 \translate.html
时,我都会收到一个错误:
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?transalted_text=salut HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1526, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1545, in finalize_request
response = self.make_response(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1701, in make_response
raise TypeError(
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
如果你查看 thank_you
函数,它只知道如何处理 POST 请求,但如果 GET 返回 None
@app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
# move the logic for GET request here
return {'msg': 'example'} # I asume that you are working with flask 2.0
现在您正在返回 GET 请求。
如果您使用的是 flask 2.0,您还可以在 app
装饰器中指定 http 方法。为了更清楚:
@app.get('/thank-you')
def thank_you():
return 'Thank you'
昨天开始学习Flask,遇到了一个变量重定向的坑。我也尝试过不使用会话,但无法取得成功。
代码如下-
from flask import Flask, render_template, request, redirect, url_for, session
from flask_wtf import Form
from wtforms import StringField
app = Flask(__name__)
app.config['SECRET_KEY'] = 'our very hard to guess secretfir'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
def translate_text(target, text):
import six
from google.cloud import translate_v2 as translate
translate_client = translate.Client()
if isinstance(text, six.binary_type):
text = text.decode("utf-8")
# Text can also be a sequence of strings, in which case this method
# will return a sequence of results for each text.
result = translate_client.translate(text, target_language=target)
output_text = format(result["translatedText"])
return output_text
# approach using WTForms
class RegistrationForm(Form):
input_lang = StringField('Input Language in length(2) ==> ')
output_lang = StringField('Output Language in length(2) ==> ')
input_text = StringField('Input Text ==> ')
@app.route('/translate', methods=['GET', 'POST'])
def translate():
error = ""
form = RegistrationForm(request.form)
if request.method == 'POST':
input_lang = form.input_lang.data
output_lang = form.output_lang.data
input_text = form.input_text.data
if len(input_lang) != 2 or len(output_lang) != 2 or len(input_text) == 0:
error = "Please supply proper inputs! "
else:
translated_text = translate_text(output_lang, input_text)
session['translated_text'] = translated_text
return redirect(url_for('thank_you',transalted_text=translated_text))
return render_template('translate.html', form=form, message=error)
# Run the application
app.run(debug=True)
每当我提交 \translate.html
时,我都会收到一个错误:
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?transalted_text=salut HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1526, in full_dispatch_request
return self.finalize_request(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1545, in finalize_request
response = self.make_response(rv)
File "C:\Dev\Python\Python310\lib\site-packages\flask\app.py", line 1701, in make_response
raise TypeError(
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 304 -
127.0.0.1 - - [03/Apr/2022 13:35:04] "GET /thank-you?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 304 -
TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.
如果你查看 thank_you
函数,它只知道如何处理 POST 请求,但如果 GET 返回 None
@app.route('/thank-you')
def thank_you():
if request.method == 'POST':
messages = request.args['translated_text'] # counterpart for url_for()
messages = session['translated_text'] # counterpart for session
return render_template('thank-you.html',messages=messages)
# move the logic for GET request here
return {'msg': 'example'} # I asume that you are working with flask 2.0
现在您正在返回 GET 请求。
如果您使用的是 flask 2.0,您还可以在 app
装饰器中指定 http 方法。为了更清楚:
@app.get('/thank-you')
def thank_you():
return 'Thank you'