He estado intentando hacer una aplicación de matraz, pero aunque he declarado la variable de sesión, python genera Keyerror al acceder a esa variable de sesión. el rastreo exacto se da a continuación también. comente a continuación si necesita más ayuda. A veces también he recibido algunas advertencias sobre el desbordamiento de la sesión

Traceback (most recent call last):
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Ratan\Documents\GitHub\smart-recorder\main.py", line 58, in give_transcript
    transcript = session['text_only_transcript']
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\werkzeug\local.py", line 377, in <lambda>
    __getitem__ = lambda x, i: x._get_current_object()[i]
  File "C:\Users\Ratan\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\sessions.py", line 84, in __getitem__
    return super(SecureCookieSession, self).__getitem__(key)
KeyError: 'text_only_transcript'

Aquí está el código

import other_functions
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
from flask import session
## Imports ##

app = Flask(__name__)
app.secret_key = other_functions.get_secret_key()

## app config  ##

# functions


@app.route('/home/')
@app.route('/')
def main_page():
    return render_template('index.html')


@app.route('/from-yt-link', methods=['POST', 'GET'])
def youtube_link_page():
    if request.method == 'GET':
        return render_template('give_link_page.html')
    elif request.method == 'POST':
        video_url = request.form['url-enter']
        video_id = other_functions.get_video_id(video_url)
        session['video_id'] = video_id
        return redirect(url_for('give_transcript'))


@app.route('/upload_page/')
@app.route('/upload/')
def upload():
    return render_template('upload_page.html')

'''
The error originates here in the get_transcript() function
'''
@app.route('/get-transcript/', methods=['POST', 'GET'])
@app.route('/transcript/', methods=['POST', 'GET'])
def give_transcript():
    if request.method == 'GET':
        try:
            transcript = other_functions.return_transcript(session["video_id"])
            session['transcript'] = transcript
            text_only_transcript = ''
            for i in transcript:
                text_only_transcript = text_only_transcript + i['text'] + ' '
            session['text_only_transcript'] = text_only_transcript
            return render_template('transcript.html', transcript=transcript, raw_text=text_only_transcript)
        except KeyError:
            return '<p>No YT Url Provided</p>'
    elif request.method == 'POST':
        search_query = request.form['search-query']
        print(f"we obtained {search_query} form js with ajax")
        transcript = session['text_only_transcript']
        list_of_words = transcript.split(' ')
        where_is_the_word_present = other_functions.a_small_engine_for_finding_words(
            transcript,  search_query)
        print(f'the word is present in places {where_is_the_word_present}')
        if where_is_the_word_present != []:
            for i in where_is_the_word_present:
                list_of_words.insert(i, '<mark>')
                list_of_words.insert(i+2, '</mark>')
            print(list_of_words)
        else:
            print('lol, word not found')
        return '', 204


if __name__ == "__main__":
    app.run(debug=True)

Gracias de antemano por responder a mi pregunta :)

EDITAR : resuelto, verifique los comentarios sobre la respuesta aceptada a continuación

1
AkIonSight 27 oct. 2020 a las 21:35

1 respuesta

La mejor respuesta

Ha agregado text_only_transcript a la sesión en el método GET.

Y tienes este error en el método POST.

He aquí algunas de las posibles razones.

  1. La clave text_only_transcript no se agrega en la sesión porque olvidó llamar a la URL a través del método GET. Entonces, primero debe llamar a la URL con el método GET, luego con el método POST.
  2. Probablemente la sesión se eliminó. Verifique su sesión si tiene todas las claves o no.
1
NavaneethaKrishnan 28 oct. 2020 a las 07:35