'Exception handling of expired firebase auth tokens
I have a python flask app that links to a firebase realtime database using pyrebase4. I would like to create a try/except block that catches exceptions to do with unauthorised or expired access tokens trying to access data records. I have tried implementing the following:
import from urllib.error import HTTPError
from flask import jsonify
# Fetch task from db using access token.
try:
data = db.child("tasks").child(task["id"]).get(accessToken)
return jsonify(data.val()), 200
except HTTPError as e:
return jsonify({"msg": f"Authorisation error:{e}"}), 400
When testing the block with an expired token I am presented with the following error:
...raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: URL
During handling of the above exception, another exception occurred:
...raise HTTPError(e, request_object.text) requests.exceptions.HTTPError: [Errno 401 Client Error: Unauthorized for url: URL] { "error" : "Auth token is expired"}
Both errors reference the line: data = db.child("tasks").child(task["id"]).get(accessToken)
What exactly is happening here and how would I go about handling this exception within an exception?
Solution 1:[1]
You may be importing 'HTTPError' from a different library than the pyrebase4 package uses. Check you are importing the error from the correct library. E.g.
from requests.exceptions import HTTPError
not
from urllib.error import HTTPError
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SH1V13 |
