0Pricing
Flask Academy · Lezione

Attivare un context in script e shell

Esegua codice al di fuori di una richiesta con app_context.

Attivare un context in script e shell è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Outside the Web

Sometimes you run Flask code with no request, like a script that seeds the database. There is no context, so the usual proxies fail.

The Telltale Error

Run such code and Flask raises RuntimeError: working outside of application context. It is telling you no app context is active.

Push It Yourself

Fix it by pushing one with app.app_context(). Wrap your code in a with block and current_app starts working again.

with app.app_context():
    print(current_app.name)

What the with Block Does

Entering the with block pushes the context, and leaving it pops the context. You never have to clean up by hand.

Now Extensions Work

Inside the block, extensions bound to the app behave normally. You can run db.create_all() or query models from a plain script.

with app.app_context():
    db.create_all()

Need a Fake Request?

To exercise code that reads request, push a test request context with test_request_context instead of an app context.

with app.test_request_context("/hello"):
    print(request.path)

The Flask Shell

The flask shell command opens a Python shell with an app context already pushed, so you can poke at your app interactively.

flask shell

CLI Commands Too

Custom flask commands you register also run inside an app context automatically, so seed and admin scripts just work.

@app.cli.command()
def seed():
    db.create_all()

Match the Right Context

Pick by need: use app_context when you only touch the app or database, and a request context when your code reads request data.

Keep It Scoped

Push contexts in a tight with block, not for the whole script. Smaller scope means clearer code and predictable teardown.

Why This Matters

Pushing contexts lets you reuse app logic in migrations, cron jobs, and tests, not just inside live web requests.

Quick Check

Let us nail the fix for the context error.

Recap

No request? Push one. Use app_context for app and database work, test_request_context for request data, and let flask shell handle it for you. 🎉

Domande Frequenti

La lezione «Attivare un context in script e shell» è gratuita?

Sì — il testo completo di «Attivare un context in script e shell» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «Attivare un context in script e shell»?

Esegua codice al di fuori di una richiesta con app_context. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Attivare un context in script e shell»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flask Academy?

Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. App context e request context
  2. current_app e l'oggetto g
  3. Context local e sicurezza dei thread
  4. Attivare un context in script e shell
← Torna a Flask Academy