Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python flask, keeping session in scope using another class

So my basic question. I have a flask application. Inside of this application I have built a simple login system that uses flask sessions. I want to break my code up into different classes to help separate my logic. But i am receiving the following error.

Traceback (most recent call last):
  File "server.py", line 22, in <module>
    securty = Security()
  File "/Users/chrisburgin/Development/pigarage/security.py", line 6, in __init__
    print(session.get('logged_in'))
NameError: global name 'session' is not defined

This error is receiving using the following.

My External Class

class Security:
    def __init__(self):
        print('Security Created')
        print(session.get('logged_in'))

    def loggedIn(self):
        if session.get('logged_in') != True:
            return False

And I am calling this from inside of my server file

securty = Security()

Just as summery. I understand that the 'Security' class doesn't have access to session because its not in scope but I could very much use assistance in understanding how to provide it access.

Please correct me on anything I have done wrong. Thanks!

editing using from flask import session at the top of my external class file

 File "server.py", line 22, in <module>
    securty = Security()
  File "/Users/chrisburgin/Development/pigarage/security.py", line 5, in __init__
    print(session.get('logged_in'))
  File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/Library/Python/2.7/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/Library/Python/2.7/site-packages/flask/globals.py", line 20, in _lookup_req_object
    raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
like image 205
Chris Burgin Avatar asked Apr 24 '26 07:04

Chris Burgin


1 Answers

The session variable from Flask is a context local. Context locals are a somewhat special type of global variable, in that they are only accessible at certain times.

Specifically for session, you can only use it when the application is responding to a request. Flask sets the value of this variable right before invoking a view function.

In your stack trace, it appears you are creating an instance of the Security class during initialization. The constructor for this class accesses session, but at this time, there is really no client, no request, and no session, so this gives you an error. It's okay to create an object of this class, as long as you don't access the session in the constructor. Then you must make sure that you invoke the loggedIn method only inside a view function or a function called from a view function, to ensure a request context exists.

like image 124
Miguel Avatar answered Apr 26 '26 05:04

Miguel