How to pass variables to nested functions in cProfile's runctx()

56 Views Asked by At

I'm trying to profile some code, but it has nested function calls.

It looks something like this:

### user.py
class MyFlaskAPI:
  def get(self):
        page = 1
        pagesize = 100
        offset = 0

        user = get_user()
        results = paginate(user, page=page, pagesize=pagesize, offset=offset)

        return results

## paginate.py
def paginate(user, page=1, pagesize=100, offset=0):
        query = session.query(Foo).filter_by(ninja_id=user.org.ninja_id)
        results = # do some extra work
        return results

I am using cProfile's runctx() method. This particular function is within a request context, and looks like this:

user = <SQLAlchemy user object>

with app.test_request_context():
        cProfile.runctx('MyFlaskAPI.get()', dict(MyFlaskAPI=MyFlaskAPI()), dict(user=user))

When I run this code, I am getting the following error:

query = session.query(Foo).filter_by(ninja_id=user.org.ninja_id)
AttributeError: 'NoneType' object has no attribute 'organization'

I have also tried passing the user as a global, like this:

with app.test_request_context():
        cProfile.runctx('MyFlaskAPI.get()', dict(MyFlaskAPI=MyFlaskAPI(), user=user), None)

In both cases I get the same error.

This leads me to believe that the user in the filter_by clause is None. However, I am trying to pass the user object as a global in runctx(). I must be doing something wrong. Any help is greatly appreciated!


EDIT: The issue had to do with the get_user() call. I thought I could override the user variable by passing in the user directly, but that is not the case. This issue is now resolved.

0

There are 0 best solutions below