python - 在 Python 中构建 API 调用

标签 python api oop data-structures

我很难确定构建数据以调用包含比特币价格的各种 API 的最佳实践是什么。我希望能够调用多个 API,而无需重复代码。

我最初的想法是为我将调用的每个 API 构建类,并将它们的属性(api_id、url 和 json_tree(我想从中提取数据的 json 路径)提供给 BtcAPI 类,然后吐出他们出来了。

*请注意,在阅读 BtcAPI 工作时,Coindesk/Bitstamp 类尚未与该类进行交互之前请注意。我想问一下在我遇到麻烦之前我应该​​怎么做......*

现在,我想知道我是否不应该列出它们,例如:

coindesk = ['http://www.something.com', 'coindesk', '["time"]["updated"]']

...然后遍历它们中的每一个。或听写,或任何其他种类的东西。这里表示什么数据结构?

我基本上是在寻找一些代码审查(因为这段代码不起作用,我不想将它发送到代码审查堆栈)和对最佳实践的理解:告诉我你认为我在哪里我搞砸了,我能做些什么来更好地构建这些数据?我是 python 和 oop 菜鸟。我可以按程序执行此操作,但这会很丑陋且多余。我想我在使用类时也有点不对。见解?帮助?谢谢!

谢谢!

import json
import urllib.request

#The BtcAPI class works well when you feed it static variables. It returns json.

class BtcAPI:

    def __init__(self, url, api_id):
        self.url = url
        self.api_id = api_id

    def btc_api_call(self):

        hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'     }
        req = urllib.request.Request(url, headers=hdr)
        readdata = urllib.request.urlopen(req)
        json_data = readdata.read()

        json_dict = json.loads(json_data)
        return(json_dict)

class Coindesk:


    api_id = 'Coindesk'
    url = 'https://api.coindesk.com/v1/bpi/currentprice.json'               
    json_tree = json_dict['time']['updated']

    def __init__(self):

        self.current_us_price = current_us_price

class Bitstamp:


    api_id = 'Bitstamp'
    url = 'https://www.bitstamp.net/api/ticker/'               
    json_tree = json_dict['last']

    def __init__(self):

        self.current_us_price = current_us_price

coindesk_url = Coindesk()
coindeskoutput = coindesk_url.url
print(coindeskoutput)

最佳答案

如果您想要一段通用代码,我建议您将代码和配置数据分离到 2 个文件中。这样您就可以管理您的配置数据(URL、您想要检索的 JSON 属性)而无需修改您的实际 Python 代码。这通常被认为是一种很好的做法,但它意味着要管理两个文件而不是一个文件,因此如果您的项目非常小,这可能会有点负担。

以您的情况为例,您可以:

  • 配置文件
  • bitcoin_api.py

conf.ini

配置文件看起来像这样:

[COINDESK]
url: https://api.coindesk.com/v1/bpi/currentprice.json
response: time.updated

[BITSTAMP]
url: https://www.bitstamp.net/api/ticker
response: last

bitcoin_api.py

您的代码如下所示:

import configparser
import requests
import os


class BitcoinAPI:
    def __init__(self, API):
        config = configparser.ConfigParser()
        config.read(os.path.dirname(__file__) + '/conf.ini')
        self.url = config.get(API, 'url')
        self.attribute = config.get(API, 'response')
        self.header = {'content-type': 'application/json'}

    def get(self):
        response = requests.get(self.url, headers=self.header)
        response = response.json()

        # Browse the response to fetch only the attributes you want
        self.attribute = self.attribute.split('.')
        depth = len(self.attribute)
        for i in range(depth):
            response = response[self.attribute[i]]

        print(response)
        return response

然后你可以在你的主脚本中调用你的类:

import bitcoin_api
result = bitcoin_api.BitcoinAPI('COINDESK').get()
result = bitcoin_api.BitcoinAPI('BITSTAMP').get()

关于python - 在 Python 中构建 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48572494/

相关文章:

api - Rest api design : POST to create with duplicate data, would-be IntegrityError/500,什么是正确的?

c# - 如何使用泛型实现此功能?

c# - 具有许多通用和一些独特方法的类对象的设计方法

python - NumPy数组,保存SoundDevice的.wav音频数据

python - 如何使用python将列表中的数据帧名称更改为字符串?

python - 如何使用 Flask 和 WTForms 在保留表单数据的同时进行重定向?

api - 股票市场API

python - 误导性的 Python 错误消息

xml - 在哪里可以找到有关 Microsoft Dynamics CRM API 的 SOAP/XML 查询的信息

php - 将现有的 php 搜索重构为 OOP