safetyduck
safetyduck

Reputation: 6874

How to reference self in flask route method?

For example, this pattern is usually accomplished with globals. How to use attributed?

from flask import Flask
app = Flask(__name__)
app._this_thing = None

@app.route('/')
def hello_world():
    self._this_thing = 123
    return 'Hello, World!'

Upvotes: 0

Views: 955

Answers (1)

oschlueter
oschlueter

Reputation: 2698

You can import the global variable current_app (see doc) and access it in your function like this:

from flask import Flask, current_app

app = Flask(__name__)
app._this_thing = 'Hello world!'
    
@app.route('/')
def hello_world():
    return current_app._this_thing

Saving the this as so.py and starting it like this

$ FLASK_APP=so.py flask run

then returns the expected response:

$ curl http://localhost:5000
Hello world!

Upvotes: 1

Related Questions