Context: I have a Django based application. This application has various REST API endpoints where users can gather data. Some of this data needs to be pulled from a third-party API. This external API uses basic authentication.
In order to fetch this data, I have the following code implemented in my endpoint logic.
def metadata(jira_key: str, format=None):
username = "example"
password = "example"
try:
print(f"fetching {jira_key} with '{username}' credentials")
url = f"https://external.api.com/issue/{jira_key}"
session = requests.Session()
session.auth = username, password
headers = {'Content-Type': 'application/json'}
response = session.get(
url, headers=headers)
print(f"response: {response.status_code}")
return response
except Exception as e:
message = {"error": "Uncaught error", "message": str(e)}
return message
Long story short; it works! This endpoint is essentially just a proxy for another API. This is done for security purposes.
However, I have been experiencing lock-outs where permission for the service account needs to be reinstated periodically...
I suspect the session is being generated every time the endpoint is hit.
So my question is this: How can I implement a persisted request.Session() with basic auth that is established at build time, and reused for each requests?
这个答案解决了您的问题,即在应用程序配置类的ready
功能中实例化您的会话,该功能在启动 django 时仅运行一次,然后存储在应用程序内存中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.