0Pricing
Flask Academy · Lección

current_app y el objeto g

Acceda a la aplicación activa y al almacenamiento por solicitud.

current_app y el objeto g es una lección gratuita de Flask Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flask Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flask Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Meet current_app

current_app is a proxy that always points to the app handling the work right now. Import it whenever you need the active application.

from flask import current_app

Why Not Import app?

Importing your app object directly causes circular imports as projects grow. current_app sidesteps that by resolving the app at runtime.

Reading Config

A common use is reading settings: current_app.config gives you the active app's configuration without importing the app module.

key = current_app.config["SECRET_KEY"]

It Needs a Context

current_app only works while an app context is active. Inside a view that is automatic, since the request pushed one for you.

Meet the g Object

g is a simple scratchpad for one request. Attach anything to it and read it back later in the same request.

from flask import g
g.user = "alice"

g Is Per Request

The g object is reset for every request. Data you stash on it never leaks into another visitor's request.

A Typical g Use

Use g to share work across functions in one request, like caching the current user so you fetch it from the database only once.

if "db" not in g:
    g.db = connect()

g Is Not Storage

Do not treat g as a database. It forgets everything the moment the request ends, so use it only for that request's lifetime.

g Lives in the App Context

Surprisingly, g belongs to the app context, not the request context. In practice both exist during a request, so it just works.

Cleaning Up With g

Pair g with teardown handlers to close what you opened, like closing a database connection after the response is sent.

@app.teardown_appcontext
def close(exc):
    g.pop("db", None)

current_app and g Together

They pair nicely: read settings from current_app, then stash request-specific results on g so the rest of the request can reuse them.

Quick Check

Let us pin down what g is for.

Recap

Two handy proxies: current_app finds the active app and its config, while g is a per-request scratchpad you wipe clean each time. 🎉

Preguntas frecuentes

¿La lección «current_app y el objeto g» es gratis?

Sí — el texto completo de «current_app y el objeto g» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flask Academy, actualiza a CoddyKit PRO. El curso de Flask Academy incluye 4 lecciones en total.

¿Qué aprenderé en «current_app y el objeto g»?

Acceda a la aplicación activa y al almacenamiento por solicitud. Practicas Flask Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Flask Academy?

No se requiere experiencia previa. Flask Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «current_app y el objeto g»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Flask Academy?

Sí. Cada lección de Flask Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Contexto de aplicación frente a contexto de solicitud
  2. current_app y el objeto g
  3. Locales de contexto y seguridad de los hilos
  4. Active un contexto en scripts y shells
← Volver a Flask Academy