Code simplification scenarios

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?

Pass the address to the function as an argument:

def get_graph_data(address):
    if "access_token" in result:
        graph_data = requests.get(
            address,
            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")

However, there is one other difference between the three functions: the users function only returns the "value" field of graph_data, whereas the other two functions returns the whole graph_data object. You could add an optional argument to get a specific field:

def get_graph_data(address, field=None):
    if "access_token" in result:
        graph_data = requests.get(
            address,
            headers={'Authorization': 'Bearer ' + result['access_token']}, ).json()
        data = graph_data[field] if field else graph_data
        return json.loads(json.dumps(data))
    else:
        return result.get("error"), result.get("error_description"), result.get("correlation_id")
1 Like

Thank you for solving my problem :grinning: