Home > Mobile >  Unable to redirect variable in python with flask
Unable to redirect variable in python with flask

Time:04-03

yesterday I started to learn Flask and got into a pitfall for redirection with a variable. I tried without session as well but can't get ahead.

Code is as below -

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)

Whenever, I submit \translate.html, I get an error as :

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 -

CodePudding user response:

TypeError: The view function for 'thank_you' did not return a valid response. The function either returned None or ended without a return statement.

If you look at the thank_you func, it only knows how to handle a POST request, but in case of GET is returning 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

And now you are returning for a GET request.

And if you are on flask 2.0, you could also specify the http method in the app decorator. For more clarity:

@app.get('/thank-you')
def thank_you():
   return 'Thank you'
  • Related