def main():
    #Get token from previously created script
    token = get_auth_token()

    # Define local variables for reuse
    api_path = "https://sandboxdnac.cisco.com/dna"

    # Provide header information using JSON and X-Auth-Token
    hdrs = {'X-Auth-Token': token, 'Content-Type': 'application/json'}

    # Issue GET request to get list of network devices
    get_resp = requests.get(f"{api_path}/intent/api/v1/network-device",
                            headers=hdrs,
                            verify=False)
    # Convert output to JSON and Print
    print(json.dumps(get_resp.json(), indent=2))

    # With JSON output, iterate over the dictionaries and print specified dictionaries
    if get_resp.ok:
        for device in get_resp.json()["response"]:
            print(
                f"Hostname: {device['hostname']}  Platform: {device['platformId']}  Software: {device['softwareVersion']}  IP: {device['managementIpAddress']}"
            )
    else:
        print(f"Device collection failed with code {get_resp.status_code}")
        print(f"Failure body: {get_resp.text}")
Beispiel #2
0
def main_single(args):
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # POST
    url = args.url_base
    book_dict = {
        "title": "TestBook1",
        "abbr": "test conf.",
        "style": "BOOK",
    }
    create_book(url, token, book_dict)
Beispiel #3
0
def main_single(args):
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # POST
    url = args.url_base + "authors/"
    author_dict = {
        "name_en": "TestAuthor2",
        "name_ja": "テスト2",
        "dep_en": "Osaka University",
        "dep_ja": "Osaka University",
        "mail": "*****@*****.**",
    }
    create_author(url, token, author_dict)
Beispiel #4
0
def main():
    #Get token from previously created script
    token = get_auth_token()

    # Define local variables for reuse
    api_path = "https://sandboxdnac.cisco.com/dna"

    # Provide header information using JSON and X-Auth-Token
    hdrs = {'X-Auth-Token': token, 'Content-Type': 'application/json'}

    # Issue GET request to get list of network devices
    get_resp = requests.get(f"{api_path}/intent/api/v1/network-device",
                            headers=hdrs,
                            verify=False)
    # Convert output to JSON and Print
    print(json.dumps(get_resp.json(), indent=2))
Beispiel #5
0
def main_single(args):
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # POST
    url = args.url_base
    author_order_dict = {
        "bibtex": {
            "title": "{IoT}環境における処理削減によるストリーミング処理時間短縮手法",
        },
        "authors":
        "AI-Sakib Khan Pathan,Akihito Hiromori,Akiko Yamazoe-Umemoto",
    }
    df = create_author_order(url, token, author_order_dict)
    print(df)
Beispiel #6
0
def main_single(args):
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # POST
    url = args.url_base
    author_order_dict = {
        "bibtex": "bibtex entry 1",
        "book": "TestBook1",
        "pub_date": "2018-01-02",
        "page": "123-124",
        "authors": "Test Author4, Test Author, Test Abc",
    }
    df = create_author_order(url, token, author_order_dict)
    print(df)
Beispiel #7
0
def main_single(args):
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # POST
    url = args.url_base
    bibtex_dict = {
        "language": "EN",
        "title":    "bibtex entry 1",
        "volume":   "0",
        "number":   "1",
        "chapter":  "2",
        "page":     "123-124",
        "edition":  "",
        "pub_date": "2018-01-02",
        "use_data_info": False,
        "url": "",
        "note": "",
        "memo": "",
        "book": {"title":"IEEE Int'l Conf. on Mobile Data Management (MDM2015)", "style": "INTPROC"},
    }
    create_bibtex(url, token, bibtex_dict)
Beispiel #8
0
def main_csv(args):
    """
    Args.
    -----
    - url       : str, API Endpoint
    - token     : str, Authentication Token
    - file_path : str, path to CSV file

    Returns.
    --------
    - pd.DataFrame
    """
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # Read and Check CSV
    import pandas as pd
    df = pd.read_csv(args.file).fillna("")
    print(df.head())
    key_expected, key_actual = set([
        "bib_title",
        "keys_author",
    ]), set(list(df.columns))
    if not key_expected <= key_actual:
        raise ValueError(
            "Check CSV some keys are missing [diff={}]".format(key_expected -
                                                               key_actual))

    # Create New Author_Orders
    df["status"] = "None"
    df["msg"] = ""
    df_results = pd.DataFrame()
    if args.debug:
        df = df[1130:1140].reset_index(drop=True)
    for i in range(len(df)):
        row = df.loc[i, :]
        author_order_dict = {
            "bibtex": {
                "title": row["bib_title"]
            },
            "authors": row["keys_author"],
        }
        df_tmp = create_author_order(args.url_base, token, author_order_dict)
        df_results = pd.concat([df_results, df_tmp], axis=0)
    df_results = df_results.reset_index(drop=False)
    print(df_results)

    # Results
    logger.info("=== Results ===")
    df_tried = df_results[df_results["status"].isin([True, False])]
    df_success, df_error = df_results[df_results["status"] ==
                                      True], df_results[df_results["status"] ==
                                                        False]
    logger.info("Total  : {}".format(len(df_tried)))
    logger.info("Success: {} [{}%]".format(
        len(df_success),
        len(df_success) / len(df_tried) * 100))
    logger.info("Errors : {} [{}%]".format(len(df_error),
                                           len(df_error) / len(df_tried) *
                                           100))
    for no, idx in enumerate(df_error.index):
        logger.info("- No.{}: {}".format(
            no,
            df_error.loc[idx, ["status", "msg", "bibtex_id", "author"]].values,
        ))
    logger.info("==============")

    # Write Results
    filename = "/".join(str(
        args.file).split("/")[:-1]) + "/author_order.results.csv"
    logger.info("Write results to {}".format(filename))
    df_results.to_csv(filename)
Beispiel #9
0
def main_csv(args):
    """
    Args.
    -----
    - url       : str, API Endpoint
    - token     : str, Authentication Token
    - file_path : str, path to CSV file

    Returns.
    --------
    - pd.DataFrame
    """
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # Read and Check CSV
    import pandas as pd
    df = pd.read_csv(args.file).fillna("")
    df = df.rename(columns={"bib_{}".format(c):c for c in KEYS_CREATE_BIBTEX+["title"]})
    df["book"] = df["key_book"]
    df["language"] = df["language"].str.replace("en", "EN")
    df["language"] = df["language"].str.replace("ja", "JA")
    print(df.head())
    key_expected, key_actual = set(KEYS_CREATE_BIBTEX), set(list(df.columns)+["title_en","title_ja"])
    if not key_expected <= key_actual:
        raise ValueError("Check CSV some keys are missing [diff={}]".format(key_expected - key_actual))


    # Create New Bibtexs
    df["status"] = "None"
    df["msg"] = ""
    if args.debug:
        df = df[200:210].reset_index(drop=True)
    for i in range(len(df)):
        row = df.loc[i, :]
        bibtex_dict = {
            "language": row["language"],
            "title_en": row["title"] if row["language"] == "EN" else "",
            "title_ja": row["title"] if row["language"] == "JA" else "",
            "volume":   row["volume"],
            "number":   row["number"],
            "chapter":  row["chapter"],
            "page":     row["page"],
            "edition":  row["edition"],
            "pub_date": row["pub_date"],
            "use_data_info": False if row["use_data_info"] == 0 else True,
            "url": row["url"],
            "note": row["note"],
            "memo": row["memo"],
            "book": {"title": row["book_title"], "style": row["key_book_style"]},
        }
        status, msg = create_bibtex(args.url_base, token, bibtex_dict)
        df.loc[i, "status"] = status
        df.loc[i, "msg"] = msg


    # Results
    logger.info("=== Results ===")
    df_tried = df[df["status"].isin([True, False])]
    df_success, df_error = df[df["status"] == True], df[df["status"] == False]
    logger.info("Total  : {}".format(len(df_tried)))
    logger.info("Success: {} [{}%]".format(
        len(df_success), len(df_success)/len(df_tried)*100))
    logger.info("Errors : {} [{}%]".format(
        len(df_error), len(df_error)/len(df_tried)*100))
    for no,idx in enumerate(df_error.index):
        logger.info("- No.{}: {} {}".format(
            no,
            df_error.loc[idx, ["status", "msg"]].values,
            df_error.loc[idx, ["key_book_style", "title", "key_book",]].values))
    logger.info("==============")

    # Write Results
    filename = "".join(str(args.file).split(".")[:-1]) + ".results.csv"
    df.to_csv(filename)
Beispiel #10
0
 def get_auth_token(self):
     self._auth_token = auth_token.get_auth_token(self._api_key, self._api_secret, Client.WIX_MEDIA_AUTH_TOKEN_URL)
Beispiel #11
0
 def _auth_token():
     url = os.path.join(args.url_base, "api-token-auth/")
     token = get_auth_token(url, args.username)
     logger.debug("Token [{}]: {}".format(args.username, token))
     return token
Beispiel #12
0
 def get_auth_token(self):
     self._auth_token = auth_token.get_auth_token(
         self._api_key, self._api_secret, self._wix_media_auth_token_url, auth_service=self._auth_service
     )
Beispiel #13
0
def main_csv(args):
    """
    Args.
    -----
    - url       : str, API Endpoint
    - token     : str, Authentication Token
    - file_path : str, path to CSV file

    Returns.
    --------
    - pd.DataFrame
    """
    # Get Token
    url = args.url_base + "api-token-auth/"
    token = get_auth_token(url, args.username)
    logger.debug("Token [{}]: {}".format(args.username, token))

    # Read and Check CSV
    import pandas as pd
    df = pd.read_csv(args.file).fillna("")
    print(df.head())
    key_expected, key_actual = set(KEYS_CREATE_AUTHOR), set(df.columns)
    if not key_expected <= key_actual:
        raise ValueError(
            "Check CSV some keys are missing [diff={}]".format(key_expected -
                                                               key_actual))

    # Create New Authors
    df["status"] = "None"
    df["msg"] = ""
    if args.debug:
        df = df[:10].reset_index(drop=True)
    for i in range(len(df)):
        row = df.loc[i, :]
        author_dict = {
            "name_en": row["name_en"],
            "name_ja": row["name_ja"],
            "dep_en": row["dep_en"],
            "dep_ja": row["dep_ja"],
            "mail": row["mail"],
        }
        status, msg = create_author(args.url_base, token, author_dict)
        df.loc[i, "status"] = status
        df.loc[i, "msg"] = msg

    # Results
    logger.info("=== Results ===")
    df_tried = df[df["status"].isin([True, False])]
    df_success, df_error = df[df["status"] == True], df[df["status"] == False]
    logger.info("Total  : {}".format(len(df_tried)))
    logger.info("Success: {} [{}%]".format(
        len(df_success),
        len(df_success) / len(df_tried) * 100))
    logger.info("Errors : {} [{}%]".format(len(df_error),
                                           len(df_error) / len(df_tried) *
                                           100))
    for no, idx in enumerate(df_error.index):
        logger.info("- No.{}: {} {}".format(
            no, df_error.loc[idx, ["status", "msg"]].values,
            df_error.loc[idx, [
                "name_en",
                "name_ja",
                "mail",
            ]].values))
    logger.info("==============")

    # Write Results
    filename = "".join(str(args.file).split(".")[:-1]) + ".results.csv"
    df.to_csv(filename)
 def get_auth_token(self):
     self._auth_token = auth_token.get_auth_token(self._api_key, self._api_secret, self._wix_media_auth_token_url, auth_service=self._auth_service)