How to use the pycountry.currencies function in pycountry

To help you get started, we鈥檝e selected a few pycountry examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pretix / pretix / src / pretix / settings.py View on Github external
CSRF_TRUSTED_ORIGINS = [urlparse(SITE_URL).hostname]

TRUST_X_FORWARDED_FOR = config.get('pretix', 'trust_x_forwarded_for', fallback=False)

if config.get('pretix', 'trust_x_forwarded_proto', fallback=False):
    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

PRETIX_PLUGINS_DEFAULT = config.get('pretix', 'plugins_default',
                                    fallback='pretix.plugins.sendmail,pretix.plugins.statistics,pretix.plugins.checkinlists,pretix.plugins.autocheckin')
PRETIX_PLUGINS_EXCLUDE = config.get('pretix', 'plugins_exclude', fallback='').split(',')

FETCH_ECB_RATES = config.getboolean('pretix', 'ecb_rates', fallback=True)

DEFAULT_CURRENCY = config.get('pretix', 'currency', fallback='EUR')
CURRENCIES = list(currencies)
CURRENCY_PLACES = {
    # default is 2
    'BIF': 0,
    'CLP': 0,
    'DJF': 0,
    'GNF': 0,
    'JPY': 0,
    'KMF': 0,
    'KRW': 0,
    'MGA': 0,
    'PYG': 0,
    'RWF': 0,
    'VND': 0,
    'VUV': 0,
    'XAF': 0,
    'XOF': 0,
github Ousret / pyTeliumManager / TeliumManager / telium.py View on Github external
def setCurrency(self, uneMonnaieISO):
        """
        Applique une nouvelle monnaie au TPE
        :param uneMonnaieISO: str
        :return: bool
        """
        try:
            cur = pycountry.currencies.get(letter=uneMonnaieISO.upper())
            self._currency = str(cur.numeric).zfill(3)
            return True
        except Exception as e:
            return False
github akretion / pypostelium / pypostelium / pypostelium.py View on Github external
payment_mode = 'C'
        elif payment_info_dict['payment_mode'] == 'card':
            payment_mode = '1'
        else:
            logger.error(
                "The payment mode '%s' is not supported"
                % payment_info_dict['payment_mode'])
            return False
        cur_decimals = payment_info_dict.get('currency_decimals', 2)
        cur_fact = 10**cur_decimals
        cur_iso_letter = payment_info_dict['currency_iso'].upper()
        if cur_iso_letter == 'EUR':  # Small speed-up
            cur_numeric = '978'
        else:
            try:
                cur = pycountry.currencies.get(alpha_3=cur_iso_letter)
                cur_numeric = str(cur.numeric)
            except Exception:
                logger.error("Currency %s is not recognized" % cur_iso_letter)
                return False
        data = {
            'pos_number': str(1).zfill(2),
            'answer_flag': '0',
            'transaction_type': '0',
            'payment_mode': payment_mode,
            'currency_numeric': cur_numeric.zfill(3),
            'private': ' ' * 10,
            'delay': 'A011',
            'auto': 'B010',
            'amount_msg': ('%.0f' % (amount * cur_fact)).zfill(8),
        }
        return data
github xesscorp / KiCost / kicost / distributors / digikey / digikey.py View on Github external
currency='USD' and locale='US' for DigiKey.
        
        @param locale_iso `str` Country in ISO3166 alpha 2 standard.
        @param currency_iso `str` Currency in ISO4217 alpha 3 standard.'''

        url = 'https://www.digikey.com/en/resources/international'

        try:
            html = self.browser.scrape_URL(url)
        except: # Could not get a good read from the website.
            self.logger.log(DEBUG_OBSESSIVE,'No HTML page for DigiKey configuration.')
            raise PartHtmlError
        html = BeautifulSoup(html, 'lxml')
        try:
            if currency_iso and not locale_iso:
                money = pycountry.currencies.get(alpha_3=currency_iso.upper())
                locale_iso = pycountry.countries.get(numeric=money.numeric).alpha_2
            if locale_iso:
                locale_iso = locale_iso.upper()
                country = pycountry.countries.get(alpha_2=locale_iso.upper())
                html = html.find('li', text=re.compile(country.name, re.IGNORECASE))
                url = html.find('a', id='linkcolor').get('href')

                # Store new localized url in distributor_dict.
                distributor_dict[self.name]['site']['url'] = url
                distributor_dict[self.name]['site']['currency'] = pycountry.currencies.get(numeric=country.numeric).alpha_3
                distributor_dict[self.name]['site']['locale'] = locale_iso

                # Fetch cookies for new URL.
                self.browser.scrape_URL(url)
        except:
            self.logger.log(DEBUG_OVERVIEW, 'Kept the last configuration {}, {} on {}.'.format(
github Ousret / pyTeliumManager / telium / payment.py View on Github external
def currency_numeric(self, currency):
        currency = currencies.get(alpha_3=currency.upper())
        if currency is None:
            raise KeyError('"{cur}" is not available in pyCountry currencies list.'.format(cur=currency))
        self._currency_numeric = str(currency.numeric).zfill(3)
github russss / python-emv / emv / protocol / data.py View on Github external
return format_bytes(value)
    if parse == Parse.ASCII:
        return '"' + "".join(map(chr, value)) + '"'
    if parse == Parse.DEC:
        return str(from_hex_int(value))
    if parse == Parse.DATE:
        return from_hex_date(value)
    if parse == Parse.INT:
        return str(decode_int(value))
    if parse == Parse.COUNTRY:
        try:
            return pycountry.countries.get(numeric=str(from_hex_int(value))).alpha_2
        except ValueError:
            return "" % value
    if parse == Parse.CURRENCY:
        return pycountry.currencies.get(numeric=str(from_hex_int(value))).alpha_3
    return format_bytes(value)
github xesscorp / KiCost / kicost / distributors / mouser / mouser.py View on Github external
# this behaviour within a session seems to be ignored so far
        # (you will be 302 redirected to your regional domain).

        # TODO:
        #   Switch locale via the following URL ignores currency settings!
        #   Switch to regions far away from your location is rejected!
        #   url = 'https://www.mouser.com/localsites.aspx'

        # The following approach works for selecting currency:
        # - Access "www.mouser.com" (done in constructor) and store local redirect URL.
        # - Manually set currency preference for your regional URL.
        # - Completely restart fake_browser session to apply currency settings.
        # Switching locale seems to be not possible yet.
        try:
            if currency_iso and not locale_iso:
                money = pycountry.currencies.get(alpha_3=currency_iso.upper())
                locale_iso = pycountry.countries.get(numeric=money.numeric).alpha_2
            if locale_iso:
                currency_iso = currency_iso.upper()
                country = pycountry.countries.get(alpha_2=locale_iso.upper())

                # TODO: Mouser uses either "USDe" or "USDu" to select USD as
                #   currency, depending on your location.
                if currency_iso == "USD" and locale_iso == "US":
                    currency_iso = "USDu"
                else:
                    currency_iso = "USDe"

                # Some mouser regions are subdomains from mouser.com, other
                # regions user their own top level domains, e.g. mouser.eu.
                # Extract the region specific part and suffix it to
                # the preferences cookie.
github silverapp / silver / silver / models.py View on Github external
from django.core.validators import MinValueValidator
from django.template import TemplateDoesNotExist
from django.template.loader import (select_template, get_template,
                                    render_to_string)
from django.core.urlresolvers import reverse
from annoying.functions import get_object_or_None
from livefield.models import LiveModel
from dateutil import rrule
from pyvat import is_vat_number_format_valid
from model_utils import Choices

from silver.utils import next_month, prev_month
from silver.validators import validate_reference

countries = [ (country.alpha2, country.name) for country in pycountry.countries ]
currencies = [ (currency.letter, currency.name) for currency in pycountry.currencies ]

logger = logging.getLogger(__name__)


PAYMENT_DUE_DAYS = getattr(settings, 'SILVER_DEFAULT_DUE_DAYS', 5)


_storage = getattr(settings, 'SILVER_DOCUMENT_STORAGE', None)
if _storage:
    _storage_klass = import_string(_storage[0])
    _storage = _storage_klass(*_storage[1], **_storage[2])


def documents_pdf_path(document, filename):
    path = '{prefix}{company}/{doc_name}/{date}/{filename}'.format(
        company=slugify(unicode(
github xesscorp / KiCost / kicost / distributors / mouser / mouser.py View on Github external
# Extract the region specific part and suffix it to
                # the preferences cookie.
                local_domains = re.search("https://(.+)\.mouser\.(.+)/", self.browser.ret_url)
                if local_domains.group(1).startswith("www"):
                    domain = local_domains.group(2)
                else:
                    domain = local_domains.group(1)

                # Store currency perference (pc_%localdomain)
                # for your regional domain.
                self.browser.add_cookie('.mouser.%s' % local_domains.group(2), \
                    'preferences', 'pc_%s=%s' % (domain, currency_iso))

                # Store new localized url in distributor_dict.
                distributor_dict[self.name]['site']['url'] = self.browser.ret_url.rstrip('/')
                distributor_dict[self.name]['site']['currency'] = pycountry.currencies.get(numeric=country.numeric).alpha_3
                distributor_dict[self.name]['site']['locale'] = locale_iso

                # Restarting complete session is required to apply
                # new locale and currency settings.
                self.browser.domain = distributor_dict[self.name]['site']['url']
                self.browser.start_new_session()

        except Exception as ex:
            self.logger.log(DEBUG_OBSESSIVE, "Exception was %s" % type(ex).__name__)
            self.logger.log(DEBUG_OVERVIEW, 'Kept the last configuration {}, {} on {}.'.format(
                    pycountry.currencies.get(alpha_3=distributor_dict[self.name]['site']['currency']).name,
                    pycountry.countries.get(alpha_2=distributor_dict[self.name]['site']['locale']).name,
                    distributor_dict[self.name]['site']['url']
                )) # Keep the current configuration.
        return
github DOAJ / doaj / portality / datasets.py View on Github external
def _generate_currency_options():
    currency_options_ = [(CURRENCY_DEFAULT, CURRENCY_DEFAULT)]

    for cu in sorted(pycountry.currencies, key=lambda x: x.alpha_3):
        try:
            currency_options_.append((cu.alpha_3, '{code} - {name}'.format(code=cu.alpha_3, name=cu.name)))
        except AttributeError:
            continue

    return currency_options_