alexprengere / currencyconverter

A Python currency converter using the European Central Bank data.
http://alexprengere.github.io/currencyconverter
Apache License 2.0
215 stars 59 forks source link

Detecting target currency based on user's locale #42

Closed kubinka0505 closed 2 years ago

kubinka0505 commented 2 years ago

I know it's obsolete, and probably stupid but is it possible to get target currency based on user's locale.getdefaultlocale()? On user demand of course.


>>> import currency_converter as cc
>>> from locale import getdefaultlocale as loc
>>> c = cc.CurrencyConverter()
>>>
>>> # View locale
>>> loc()
('pl_PL', 'cp1250')
>>> # pl_PL - PLN
>>> # en_US - USD
>>> # etc...
>>>
>>> # Based on `getdefaultlocale()`
>>> c.convert(125, "GBP", "local")  # or "auto"?
701.6934625842298
>>>
>>> # Manual
>>> c.convert(125, "GBP", "PLN")
701.6934625842298
alexprengere commented 2 years ago

This is an interesting idea, though I think this logic belong outside of the library. To implement this, you first need the mapping of country_code to currency, which you can find in many places, for example this CSV file.

# Do not download the file at every execution :)
COUNTRIES_URL = "https://raw.githubusercontent.com/opentraveldata/opentraveldata/master/opentraveldata/optd_countries.csv"
import urllib.request

urllib.request.urlretrieve(COUNTRIES_URL, "countries.csv")

# Build the "country -> currency" mapping
country_to_currency = {}
with open("countries.csv") as f:
    next(f)  # skipping header
    for row in f:
        row = row.rstrip().split("^")
        country_code, currency = row[0], row[10]
        country_to_currency[country_code] = currency

# Expose a function to get the locale associated currency
from locale import getdefaultlocale

def get_locale_currency():
    language_code, _ = getdefaultlocale()
    country_code = language_code[-2:]
    return country_to_currency[country_code]

# Use that function to retrieve the currency
import currency_converter as cc

c = cc.CurrencyConverter()
c.convert(125, "GBP", get_locale_currency())
kubinka0505 commented 1 year ago

...and since python 3.7 we can use locale.localeconv to make this easier 🙂 No need to download anything.


>>> import locale
>>> import currency_converter as cc
>>> _ = locale.setlocale(locale.LC_ALL, "")
>>>
>>> def locale_curr(amount: float, from_: str = "USD", use_currency_name: bool = True):
...     Converted = cc.CurrencyConverter().convert(
...         float(amount),
...         from_.upper().strip(),
...         locale.localeconv()["int_curr_symbol"]
...     )
...     ResVal = [Converted]
...     #-=-=-=-#
...     __LCnv = locale.localeconv()
...     if use_currency_name:
...         ResVal += [__LCnv["currency_symbol"]]
...     else:
...         ResVal += [__LCnv["int_curr_symbol"]]
...     #-=-=-=-#
...     return tuple(ResVal)
...
>>> locale_curr(10, "USD", 1)
(40.63289979849789, 'zł')
>>> locale_curr(50, "USD", 0)
(203.16449899248946, 'PLN')
>>>```