Пример #1
0
def jsonToDict(path: str) -> dict:
    """loads JSON from a file and converts to a dict

    Parameters
    ----------
    path : str
        path to json file 

    Returns
    -------
    dict
        json object as a dict
    """
    logger = Logger().logger
    try:
        json_file = open(path, "r")
        json_data = json_file.read()
        json_file.close()

        return json.loads(json_data)
    except ValueError as e:
        Logger().error(
            1, f"Error: cannot load JSON at path: {path}. Invalid json: {e}")
    except Exception as e:
        logger.debug(e)
        Logger().error(
            1,
            f"Error: Cannot load json data from path: {path}",
        )
Пример #2
0
def order(ctx, **kwargs):
    """ Order a drink """
    # Initialize the logger
    logger = Logger().logger
    # combine the current context with sub command options
    ctx.obj.update(**kwargs)

    store = jsonToDict(
        os.path.join(os.path.dirname(os.path.dirname(__file__)),
                     "api/store.json"))

    client = Client(**store)
    menu = client.get("menu")
    drinks = [d["name"].lower().strip() for d in menu]
    order = {}

    order["name"] = input("What drink would you like? ")
    if order["name"].lower().strip() not in drinks:
        Logger().error(
            f"'{order['name']}' is not a valid drink. Run the menu command to see valid options.",
            1,
        )

    order["size"] = input("What size should it be? ")
    for item in menu:
        if item["name"].lower().strip() == order["name"]:
            if order["size"].lower().strip() not in item["size"]:
                Logger().error(
                    f"'{order['size']}' is not a valid size. Run the menu command to see valid options.",
                    1,
                )

    order["iced"] = input("Do you want it iced? True|False ")
    if order["iced"] not in ["True", "False"]:
        Logger().error(
            f"'{order['iced']}' is not a valid answer. Please provide either True or False.",
            1,
        )
    else:
        order["iced"] = bool(order["iced"])

    logger.info("Sending order to server.")
    client.post([order])
Пример #3
0
    def __init__(self, *args, **kwargs):
        self.host = kwargs.get("host", None)
        self.port = kwargs.get("port", 5984)
        self.base_url = f"http://{self.host}:{self.port}/api"

        self.logger = Logger().logger

        self.session = requests.session()

        self.session.headers.update(
            {"accept": "application/json", "content-type": "application/json"}
        )
Пример #4
0
def saveJSON(path: str, data: dict):
    """Save a python dict to a json file

    Parameters
    ----------
    path : str
        path to save json file 
    data : [type]
        python dict
    """
    logger = Logger().logger
    try:
        file = open(path, "w+")
        file.write(json.dumps(data, indent=4))
        file.close()
    except Exception as e:
        logger.debug(e)
        Logger().error(
            1,
            f"Error: Cannot save json to path: {path}",
        )
Пример #5
0
def cli(ctx, **kwargs):
    """ Coffee
    Orders yummy beverages from a server

    Has Coof powers
    \f

    The cli for the Coffee API.
    """
    # create a object in the current context
    ctx.obj = kwargs

    # Initialize the logger
    Logger(verbose=ctx.obj["verbose"],).logger
Пример #6
0
def store(ctx, **kwargs):
    """ Show the menu """
    # Initialize the logger
    logger = Logger().logger
    # combine the current context with sub command options
    ctx.obj.update(**kwargs)

    location = {}

    location["host"] = input("What is the store host? ☕️ ")
    location["port"] = input("What is the store port? ☕️ ")

    logger.info("Saving store details")
    saveJSON(
        os.path.join(os.path.dirname(os.path.dirname(__file__)), "api/store.json"),
        location,
    )
Пример #7
0
def hiss(ctx, **kwargs):
    """ Generate example templates and models """
    # Initialize the logger
    logger = Logger().logger
    # combine the current context with sub command options
    ctx.obj.update(**kwargs)
    print("    (  )   (   )  )")
    print("     ) (   )  (  (")
    print("     ( )  (    ) )")
    print("     _____________")
    print("    <_____________> ___")
    print("    |             |/ _ \\")
    print("    |               | | |")
    print("    |               |_| |")
    print(" ___|             |\___/")
    print("/    \___________/    \\")
    print("\_____________________/")
    print("Have you had your coffee?")
Пример #8
0
def menu(ctx, **kwargs):
    """ Show the menu """
    # Initialize the logger
    logger = Logger().logger
    # combine the current context with sub command options
    ctx.obj.update(**kwargs)

    store = jsonToDict(
        os.path.join(os.path.dirname(os.path.dirname(__file__)),
                     "api/store.json"))

    client = Client(**store)
    menu = client.get("menu")

    # print(list(menu[0].keys()))
    print("{:<15} {:<30} {:<30} {:<10}".format("name", "sizes", "prices",
                                               "calories"))
    for item in menu:
        name = item["name"]
        size = ", ".join(item["size"])
        price = ", ".join((map(str, item["price"])))
        calories = item["calories"]
        print("{:<15} {:<30} {:<30} {:<10}".format(name, size, price,
                                                   calories))