4

i have many .py file in insidemyapp

@def_app.before_request
def before_request():
    if 'user' in session:
        if session['type']=='rest':
            try:
                r=query_db('select email,name,r_area,city,mobile_no,r_image,r_id from rest_user where email =%s',[session['user']])
                if r:
                    for i in r:
                        g.user=i
                        break
            except:
                pass
        else:
            try:
                r= query_db('select email,name,street,city,mobile_no,image from r_users where email = %s',[session['user']])
                if r:
                    for i in r:
                        g.user=i
                        print(g.user)
                        break
            except:
                pass

when i use g.user in other py file we get an error (AttributeError: '_AppCtxGlobals' object has no attribute 'user')

this happen when i convert my single app file into multiple using blueprint

error result

  Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python33\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Python33\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python33\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python33\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python33\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python33\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python33\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python33\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Python33\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\mehrab alam\Google Drive\organized\myapp\insidemyapp\profile.py", line 25, in profile
    print(g.user)
  File "C:\Python33\lib\site-packages\werkzeug\local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
AttributeError: '_AppCtxGlobals' object has no attribute 'user'

please help..............

1
  • There are many paths that don't set the user attribute. For example, if the first if is false the rest of the function is skipped. Commented Nov 19, 2014 at 23:18

1 Answer 1

2

There are a couple ways that you can address keeping the context and sharing before_request between Flask applications that use blueprints.

Why you're getting an error:

my_blueprint.before_request gets called before each request within my_blueprint only.

If your other file is not in that blueprint, you need to do some more work.

Here are some options:

  1. If you need something to run before all requests in all blueprints, use before_app_request. http://flask.pocoo.org/docs/api/#flask.Blueprint.before_app_request

  2. If you have a before_request command that you want to re-use (but not set globally), write your before_request function, store it in a file, import it, and feed it to the decorator.

e.g. utils/shared_functions.py:

from flask import g, session

from app.users.models import Users

def before_request():
    """pull user info from the database based on session id"""

    g.user = None

    if 'user_id' in session:
        try:
            try:
                g.user = Users.query.get(session['user_id'])
            except TypeError:  # session probably expired
                pass
        except KeyError:
            pass

and then in your calling file site_view.py:

from ..utils import shared_functions

my_module = Blueprint('reviews', __name__, url_prefix='/cat_farm')
my_module.before_request(shared_functions.before_request)

the second way will allow you to discriminately apply the before_request function to blueprints without storing it in every file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.