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
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)
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)