UnboundLocalError: cannot access local variable 'api_response'

Why does the error appear in the console but only with the last user registered in the database?
The error appears when I login.

# UnboundLocalError
UnboundLocalError: cannot access local variable 'api_response' where it is not associated with a value

Before this error, I had two users registered in the database, they do not give me an error, it is only the last one recently registered that gives an error.

UnboundLocalError is raised when you try to use the value of a local variable before assigning to it:

>>> def foo():
...     print(x)
...     x = 'Hello'
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value

And why does it work with two users and not with the latter?

We would need to see the code in question that is producing the error to answer that without guessing.

I attach this to see if it works for you but I attach code. What specific file would you need?

What is curious is that the same code works for two users and not for a third…

Judging by the last message, it’s in the function all_reports in C:\Flask\APP-POWERBY\src\embedded.py.

Oh, and it would’ve saved me having to retype it from an image if you’d copied and pasted the traceback as text!

def all_workshop2(app,db,id):
    url='https://api.powerbi.com/v1.0/myorg/groups'
    api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    #print(api_response)
    api_response['value']

    return (api_response['value'])


def all_reports(app,db,workshop,id):
    reportes=[]
    # print(session)
    # print(workshop)
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)



def get_request_header():
        '''Get Power BI API request header

        Returns:
            Dict: Request header
        '''

        return {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + AadService.get_access_token()}

It looks like api_response is only defined conditionally.
Specifically, if i['type'] == 'Workspace'.

The error you’re seeing is a direct result of that condition not being met, or the iterable workshop not returning any values.
When the line if api_response.status_code != 200: is executed, api_response has not been defined yet.

You can correct this by initially setting api_response to None and then doing an early return prior to the status code check if it’s value is still None.

Something similar to this should work:

def all_reports(app,db,workshop,id):
    reportes=[]
    api_response = None
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
    if api_response is None:
        return []
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)
1 Like

@Axe319 is correct.

It’s also an opportunity to use the for...else construct, if you’re so inclined:

def all_reports(app,db,workshop,id):
    reportes=[]
    for i in workshop:
        if i['type'] == 'Workspace':
            url=f"https://api.powerbi.com/v1.0/myorg/groups/{i['id']}/reports"
            api_response = requests.get(url, headers=get_request_header(app,db,id))
            break
    else:
        return []
    if api_response.status_code != 200:
        abort(api_response.status_code, description=f'Error while retrieving Embed URL\n{api_response.reason}:\t{api_response.text}\nRequestId:\t{api_response.headers.get("RequestId")}')
    api_response = json.loads(api_response.text)
    print(api_response['value'])
    for a in api_response['value']:
        dic2={'id_workshop':i['id'],'id_report':a['id'], 'name_report':a['name'] }
        reportes.append(dic2)
    return (reportes)

Thank you very much, I will try it and report results.