How to Resolve "RuntimeError: object is not bound" in Frappe Standalone Script?

Hi everyone,

I’m trying to run a standalone Python script to count users in my Frappe application, but I’m encountering the following error:

(env) bento@ZADID-ADVAN:~/frappe/frappe-bench/apps/temporal_app$ python3.11 temporal_app/api/test.py 
executing get user with data 
Error fetching users: object is not bound
Traceback (most recent call last):
  File "/home/bento/frappe/frappe-bench/apps/temporal_app/temporal_app/api/test.py", line 15, in <module>
    get_user()
  File "/home/bento/frappe/frappe-bench/apps/temporal_app/temporal_app/api/test.py", line 6, in get_user
    user = frappe.db.count("User")
           ^^^^^^^^^^^^^^^
  File "/home/bento/frappe/frappe-bench/env/lib/python3.11/site-packages/werkzeug/local.py", line 318, in __get__
    obj = instance._get_current_object()
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/bento/frappe/frappe-bench/env/lib/python3.11/site-packages/werkzeug/local.py", line 501, in _get_current_object
    raise RuntimeError(unbound_message) from None
RuntimeError: object is not bound

Here’s the code I’m using:

import frappe

def get_user():
    print("executing get user with data")
    try:
        user = frappe.db.count("User")
        print(f"user is : {user}")
        if user:
            return user
        return "User not found"
    except Exception as e:
        print(f"Error fetching users: {str(e)}")
        raise
      
get_user()

It seems like frappe.db is not bound, but I’m unsure how to correctly set up the Frappe context in a standalone script like this.

How can I resolve this error and access frappe.db.count() without encountering the “object is not bound” error?

Thanks in advance!