Skip to content
Advertisement

Ubuntu 18.04 python 2.7 urllib request not getting data

I have this python script which works with no problem on ubuntu 16.04 But it wont get data in ubuntu 18.04, any idea what the problem could be? No errors.

    try:
        exchrate=float(json.loads(requests.get("http://api.coindesk.com/v1/bpi/currentprice.json").read())['bpi'][currency]['rate_float'])
        print exchrate
    except:
            try:
                print("Can not get data from coindesk.com")
                print("Trying to get data from coinbase.com")
                exchrate=float(json.loads(urllib2.urlopen("https://api.coinbase.com/v2/exchange-rates?currency=BTC").read())["data"]["rates"][currency])
                print exchrate
            except:
                try:
                    print("Can not get data from coinbase.com")
                    print("Trying to get data from blockchain.info")
                    exchrate=float(json.loads(urllib2.urlopen("https://blockchain.info/ticker").read())[currency]["last"])
                    print exchrate
                except:
                    print("Can not get data from blockchain.info")
                    print("Failed to get BTC exchange rate")
                    sys.exit()

Output:

Can not get data from coindesk.com
Trying to get data from coinbase.com
Can not get data from coinbase.com
Trying to get data from blockchain.info
Can not get data from blockchain.info
Failed to get BTC exchange rate

Full code is here : https://github.com/papampi/nvOC_by_fullzero_Community_Release/blob/Dual-cuda/WTM_SWITCHER

Advertisement

Answer

Since you’re using the Requests library, you should use it on each API. Requests provides a method to extract JSON, so you don’t need to call the json module yourself.

When multiple things can go wrong, it’s not a good idea to bundle them all together in one line. Do them in stages so you can see exactly where the error occurred, and deal it with it appropriately. Also, using unnamed except blocks is rarely a good idea: you might catch something that you don’t know how to handle.

Here’s a re-organized version of your code.

import requests

currency = "USD"

apis = [
    {
        "name": "coindesk.com",
        "url": "https://api.coindesk.com/v1/bpi/currentprice.json",
        "keys": ("bpi", currency, "rate_float"),
    },
    {
        "name": "coinbase.com",
        "url": "https://api.coinbase.com/v2/exchange-rates?currency=BTC",
        "keys": ("data", "rates", currency),
    },
    {
        "name": "blockchain.info",
        "url": "https://blockchain.info/ticker",
        "keys": (currency, "last"),
    },
]

for d in apis:
    name, url, keys = d["name"], d["url"], d["keys"]
    print("Trying", name)
    try:
        req = requests.get(url)
        req.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(e)
        print("Cannot get data from", name)
        continue

    try:
        # Extract the exchange rate
        data = req.json()
        for k in keys:
            data = data[k]
    except KeyError as e:
        print("Bad key!:", e)
        continue

    try:
        # Convert the exchange rate to a float.
        # Some APIs return it as a float, but coinbase.com returns
        # a string. This code also handles None, which in JSON is null
        # If you just want to print the rate, this conversion is not needed.
        rate = float(data) 
        print("Rate", rate)
        break
    except (ValueError, TypeError) as e:
        print("Invalid exchange rate data", data, type(data))
else:
    print("Failed to get BTC exchange rate")

typical output

Trying coindesk.com
Rate 6440.64

Update: I’ve improved the error-handling of this code.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement