We have a piece of code
import json
import logging
import requests
import msal
config = {
"authority": "https://login.microsoftonline.com/organizations",
"client_id": "",
"username": '' ,
"password": '',
"scope": ["User.ReadBasic.All"],
# "endpoint": "https://graph.microsoft.com/v1.0/me/calendars"
}
config = json.loads(json.dumps(config))
app = msal.ClientApplication(
config["client_id"], authority=config["authority"],
client_credential=config.get("client_secret"),
)
result = None
accounts = app.get_accounts(username=config["username"])
if accounts:
logging.info("Account(s) exists in cache, probably with token too. Let's try.")
result = app.acquire_token_silent(config["scope"], account=accounts[0])
if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_by_username_password(
config["username"], config["password"], scopes=config["scope"])
def calendars():
if "access_token" in result:
graph_data = requests.get(
"https://graph.microsoft.com/v1.0/me/calendars",
headers={'Authorization': 'Bearer ' + result['access_token']}, ).json()
return json.loads(json.dumps(graph_data))
else:
return result.get("error"), result.get("error_description"), result.get("correlation_id")
def users():
if "access_token" in result:
graph_data = requests.get(
"https://graph.microsoft.com/v1.0/users",
headers={'Authorization': 'Bearer ' + result['access_token']}, ).json()
return json.loads(json.dumps(graph_data["value"]))
else:
return result.get("error"), result.get("error_description"), result.get("correlation_id")
def security_alerts():
if "access_token" in result:
graph_data = requests.get(
"https://graph.microsoft.com/v1.0/security/alerts",
headers={'Authorization': 'Bearer ' + result['access_token']}, ).json()
return json.loads(json.dumps(graph_data))
else:
return result.get("error"), result.get("error_description"), result.get("correlation_id")
print(security_alerts())
We have a lot of duplicate code content in def
The only difference is that the address of the API call is different
is there any solution I can optimize
such as using decorators?