Related to using the global object in flask.

Asked 2 years ago, Updated 2 years ago, 58 views

Hello.

I have a question while reading a book called "Flask-based Python Web Programming."

The contents below are part of the book.

"Global objects are efficient at storing and using data that needs to be shared across applications, but multiple simultaneous access to attributes stored on global objects can cause application operational problems."

from flask import g

@resource.after_request
def after_request(response):
    # One example of using a global object.
    pritn g.userid

# Default Auth Check
def authCheck(func):
    @wraps(func)
    def checkFunc(*args, **kwargs):
        g.userid = 'H2'
        return func(*args, **kwargs)
    return checkFunc

@app.route("/")
@authCheck
def main():
    # Another example of using a global object.
    print "hello", g.userid 


Among the above, there is a part called "multiple simultaneous access." Previously, I was using the global object as a user ID. (g.userid)

When processing a request for a session, make sure that any function can obtain and use its ID value...

By the way, are you saying that the contents of the above book should not be used with me? If multiple users' requests come in at the same time, can the ID value change?

Then it's a big problem.

I am currently running a web service with nginx + uwsgi + flask combination.

Please give us advice from masters.

Then have a good day today.

flask python global-object

2022-09-22 16:54

1 Answers

In Flask, the g object is a thread local variable whose value is valid only within the thread and each request. Even if the user's request comes in at the same time, there is no problem saving the user ID because the g object is valid only within each request.

flask.g

Just store on this whatever you want. For example a database connection or the user that is currently logged in.

It would be meaningful to make a test by yourself by referring to the test code in the following link.


2022-09-22 16:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.