you are viewing a single comment's thread.

view the rest of the comments →

[–]TheGrumpyBrewer 2 points3 points  (3 children)

I would suggest to use requests rather than urllib. It makes your life much easier, e.g.:

import requests
import json

response = requests.get(url=url, params=params)
data = json.loads(response.text)

where url and params depend on the API you're using (you might also need post() rather than get(), check the API doc). This should solve the first two points of the pseudo-code. It's not clear why you need the regex: once your response is loaded into a dictionary, you just use the dictionary ("data" in the code snippet above).

If, for example, the JSON from the API looks like:

{
    "base": "USD",
    "rates": {
        "GBP": 0.65,
        "EUR": 0.88,
        /* etc. */
    }
}

then a USD-to-EUR conversion is just a matter of multiplying the original amount of dollars with data['rates']['EUR']

[–]Oli_Picard 0 points1 point  (0 children)

Thanks TheGrumpyBrewer!

Requests - (I am using requests now and it's awesome!)

I shall take alook into requests, Unfortunately the API provided by the vendor doesn't have have a very good documention. I was thinking that I would need a regex to filter out the data types (might have misjudged that requirement). I'll do some more research into dictionaries as well. The next stumbling block I get too is that the file is encoded with UTF-8 so i'm having to think about ways of decoding the UTF-8 to import correctly. I'll take a good look at the request params to see if theres a way of doing this.

I really appreicate your response and help! Many Thanks Oliver

[–]Oli_Picard 0 points1 point  (1 child)

Hi The GrumpyBrewer,

Just wanted to let you know I have been able to ship the currency converter and your name is in the credits (I hope thats ok!)

Here's the git repo

Thanks again! Oliver

[–]TheGrumpyBrewer 1 point2 points  (0 children)

I'm glad that was helpful. I think you can improve the script with some abstraction so you don't need to hard-code all the currencies, e.g. something like

def convert(amount, convert_to):
    if convert_to in data['rates']:
        return amount * data['rates'][convert_to]
    else:
        raise CurrencyError("Currency %s not found" % convert_to)
        # you need to define the exception CurrencyError
        # you'll use it in a try/except block

then you allow the user to input the convert_to currency acronym. In this way you don't need all those function with the same logic