PYTHON - Как я могу проверить, правильно ли я вызываю этот API? - PullRequest
0 голосов
/ 26 ноября 2018

Не совсем уверен, что не так с моим кодом, я пытаюсь вызвать API openrates.io и передаю две переменные, дату и базовую валюту - которые обе являются допустимыми переменными при вызове API, он изменитсяURL при вызове API - например,желаемый URL: http://api.openrates.io/2018-11-22?base=EUR

Затем я пытаюсь передать результаты этого URL, который является выводом JSON, в класс, а затем извлечь отдельные пары ключ: значение из других функций.

На данный момент это мой код:

import datetime
import requests
import sys
import json

class APIError(Exception):
    """
    APIError represents an error returned by the OpenRates API.
    """
    pass

class Currency(object):
    """
    Currency object will store all currency related data such as present rates and historical rates
    """
    #    def __init__(self, today_rate, yesterday_rate, lastweek_rate):
    def __init__(self, exchange_rates):
    # Store the raw data from the exchange rate API for today's rates - this will be used in the average rate calculations
        self.currency_data = exchange_rates

class Time(object):
    """
    Here are all the time related elements we will need for this program to work
    """
    def __init__(self):
        # Call the API here for use in the Currency object later
        self.url = "http://api.openrates.io/"

    def call_api(self, **kwargs):
        """
        Openrates API takes in Base Currency, Dates and Destination Currency as parameters, individually, however,
        not altogther
        """
    # Call the API by requesting the URL. Use `json()` to decode the raw JSON data.
        response_data = requests.get(self.url, kwargs).json()

        # Check for an error and throw an exception if needed.
        if "Error" in response_data:
            raise APIError(response_data["Error"])

        # Return the decoded data.
            return response_data

    def get_today(self, base_curr):
        # Call today's exchange rate API
#        date = datetime.date.today(
#        today_rate = self.call_api(str(date), base=base_curr)
#        today_rate = self.call_api(str(date))
        self.url = "http://api.openrates.io/latest"
        today_rate = self.call_api(base=base_curr)
        return Currency(today_rate)

    def get_yesterday(self, base_curr):
        # Call today's exchange rate API
        date = datetime.date.today() - datetime.timedelta(days = 1)
        self.url = "http://api.openrates.io/" + str(date)
        yesterday_rate = self.call_api(base=base_curr)
#        print(yesterday_rate)
#yesterday_rate = self.call_api(str(date),
        return Currency(yesterday_rate)

    def get_last_week(self, base_curr):
        #Return last week's datetime
        date = datetime.date.today() - datetime.timedelta(days = 7)
        self.url = "http://api.openrates.io/" + str(date)
        lastweek_rate = self.call_api(base=base_curr)
        return Currency(lastweek_rate)

def home():
    # Get the conversion amount from the website.
    conv_amt = input("conv_amt")
    print("Amount to change is:", conv_amt)

    base = input("base_curr")
    print("Changing from:", base)

    dest = input("dest_curr")
    print("Changing to:", dest)

    #Create Time client
    time = Time()
    if base:
        try:
            pony = time.get_today(base)
            today_amt = conv_amt * pony.currency_data["rates"][dest]
        except APIError:
            pony = "(error)"
        yesterpony = time.get_yesterday(base)
        yesterday_amt = conv_amt * yesterpony.currency_data["rates"][dest]
        lastweekpony = time.get_last_week(base)
        lastweek_amt = conv_amt * lastweekpony.currency_data["rates"][dest]
    return today_amt, yesterday_amt, lastweek_amt

if __name__ == "__main__":
    home()

Если я попытаюсь запустить это, я получаю ошибку:объект не может быть подписан "

Кто-нибудь знает, где проблема?Разве он не может вызвать API или что-то не так с тем, как я называю свой объект Class?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...