Python pycountry.countries() Examples
The following are 25
code examples of pycountry.countries().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pycountry
, or try the search function
.
Example #1
Source File: cli.py From invenio-app-ils with MIT License | 7 votes |
def countries(output): """Generate JSON file containing all countries.""" import pycountry results = [] for country in pycountry.countries: results.append({ "type": "country", "key": country.alpha_2, "text": "{} ({})".format(country.name, country.alpha_2), }) with open(output, "w+") as f: json.dump(results, f, sort_keys=True, indent=2) click.echo("stored {} countries in {}".format(len(results), output))
Example #2
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 6 votes |
def test_lookup(): c = pycountry.countries g = c.get(alpha_2='DE') assert g == c.lookup('de') assert g == c.lookup('DEU') assert g == c.lookup('276') assert g == c.lookup('germany') assert g == c.lookup('Federal Republic of Germany') # try a generated field bqaq = pycountry.historic_countries.get(alpha_4='BQAQ') assert bqaq == pycountry.historic_countries.lookup('atb') german = pycountry.languages.get(alpha_2='de') assert german == pycountry.languages.lookup('De') euro = pycountry.currencies.get(alpha_3='EUR') assert euro == pycountry.currencies.lookup('euro') latin = pycountry.scripts.get(name='Latin') assert latin == pycountry.scripts.lookup('latn') al_bu = pycountry.subdivisions.get(code='AL-BU') assert al_bu == pycountry.subdivisions.lookup('al-bu') with pytest.raises(LookupError): pycountry.countries.lookup('bogus country') with pytest.raises(LookupError): pycountry.countries.lookup(12345)
Example #3
Source File: column.py From AnyBlok with Mozilla Public License 2.0 | 6 votes |
def _coerce(self, value): if value is not None and not isinstance(value, self.python_type): return pycountry.countries.get(alpha_3=value) return value
Example #4
Source File: column.py From AnyBlok with Mozilla Public License 2.0 | 6 votes |
def __init__(self, mode='alpha_2', *args, **kwargs): self.mode = mode if pycountry is None: raise FieldException( "'pycountry' package is required for use 'CountryType'") self.choices = {getattr(country, mode): country.name for country in pycountry.countries} super(Country, self).__init__(*args, **kwargs)
Example #5
Source File: column.py From AnyBlok with Mozilla Public License 2.0 | 6 votes |
def setter_format_value(self, value): """Return formatted country value :param value: :return: """ if value and not isinstance(value, self.sqlalchemy_type.python_type): value = pycountry.countries.get( **{ self.mode: value, 'default': pycountry.countries.lookup(value) }) return value
Example #6
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 6 votes |
def test_country_list(): assert len(pycountry.countries) == 249 assert isinstance(list(pycountry.countries)[0], pycountry.db.Data)
Example #7
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 6 votes |
def test_country_fuzzy_search(): results = pycountry.countries.search_fuzzy(u'England') assert len(results) == 1 assert results[0] == pycountry.countries.get(alpha_2='GB') # Match alternative names exactly and thus GB ends up with Wales # before Australia. results = pycountry.countries.search_fuzzy(u'Wales') assert len(results) == 2 assert results[0] == pycountry.countries.get(alpha_2='GB') assert results[1] == pycountry.countries.get(alpha_2='AU') # Match with accents removed, first a country with a partial match in the # country name, then a country with multiple subdivision partial matches, # and then a country with a single subdivision match. results = pycountry.countries.search_fuzzy(u'Cote') assert len(results) == 3 assert results[0] == pycountry.countries.get(alpha_2='CI') assert results[1] == pycountry.countries.get(alpha_2='FR') assert results[2] == pycountry.countries.get(alpha_2='HN') # A somewhat carefully balanced point system allows for a (bias-based) # graceful sorting of common substrings being used in multiple matches: results = pycountry.countries.search_fuzzy(u'New') assert results[0] == pycountry.countries.get(alpha_2='NC') assert results[1] == pycountry.countries.get(alpha_2='NZ') assert results[2] == pycountry.countries.get(alpha_2='PG') assert results[3] == pycountry.countries.get(alpha_2='GB') assert results[4] == pycountry.countries.get(alpha_2='US') assert results[5] == pycountry.countries.get(alpha_2='CA') assert results[6] == pycountry.countries.get(alpha_2='AU') assert results[7] == pycountry.countries.get(alpha_2='MH') # bug #34, likely about capitalization that was broken results = pycountry.countries.search_fuzzy(u'united states of america') assert len(results) == 1 assert results[0] == pycountry.countries.get(alpha_2='US')
Example #8
Source File: forms.py From ecommerce with GNU Affero General Public License v3.0 | 6 votes |
def country_choices(): # TODO: Remove pycountry library once White Label ends, country list is done on Payment MFE. """ Returns a tuple of tuples, each containing an ISO 3166 country code and the country name. """ countries = sorted( [(country.alpha_2, country.name) for country in pycountry.countries], key=lambda x: x[1] ) # Inserting a placeholder here so that the first option # when rendering the dropdown isn't a valid country. countries.insert(0, ('', '<{}>'.format(_('Choose country')))) return countries
Example #9
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 5 votes |
def test_repr(): assert re.match("Country\\(alpha_2=u?'DE', " "alpha_3=u?'DEU', " "name=u?'Germany', " "numeric=u?'276', " "official_name=u?'Federal Republic of Germany'\\)", repr(pycountry.countries.get(alpha_2='DE')))
Example #10
Source File: functions.py From docassemble with MIT License | 5 votes |
def countries_list(): """Returns a list of countries, suitable for use in a multiple choice field.""" return [{country.alpha_2: country.name} for country in sorted(pycountry.countries, key=lambda x: x.name)]
Example #11
Source File: functions.py From docassemble with MIT License | 5 votes |
def country_name(country_code): """Given a two-digit country code, returns the country name.""" ensure_definition(country_code) return pycountry.countries.get(alpha_2=country_code).name
Example #12
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 5 votes |
def test_dir(): germany = pycountry.countries.get(alpha_2='DE') for n in 'alpha_2', 'alpha_3', 'name', 'numeric', 'official_name': assert n in dir(germany)
Example #13
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 5 votes |
def test_repr(): assert re.match("Country\\(alpha_2=u?'DE', " "alpha_3=u?'DEU', " "name=u?'Germany', " "numeric=u?'276', " "official_name=u?'Federal Republic of Germany'\\)", repr(pycountry.countries.get(alpha_2='DE')))
Example #14
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 5 votes |
def test_subdivisions_directly_accessible(): assert len(pycountry.subdivisions) == 4835 assert isinstance(list(pycountry.subdivisions)[0], pycountry.db.Data) de_st = pycountry.subdivisions.get(code='DE-ST') assert de_st.code == u'DE-ST' assert de_st.name == u'Sachsen-Anhalt' assert de_st.type == u'State' assert de_st.parent is None assert de_st.parent_code is None assert de_st.country is pycountry.countries.get(alpha_2='DE')
Example #15
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 5 votes |
def test_germany_has_all_attributes(): germany = pycountry.countries.get(alpha_2='DE') assert germany.alpha_2 == u'DE' assert germany.alpha_3 == u'DEU' assert germany.numeric == u'276' assert germany.name == u'Germany' assert germany.official_name == u'Federal Republic of Germany'
Example #16
Source File: test_general.py From bazarr with GNU General Public License v3.0 | 5 votes |
def test_country_list(): assert len(pycountry.countries) == 249 assert isinstance(list(pycountry.countries)[0], pycountry.db.Data)
Example #17
Source File: test_forms.py From ecommerce with GNU Affero General Public License v3.0 | 5 votes |
def test_countries_sorting(self): """ Verify the country choices are sorted by country name. """ data = self._generate_data() form = PaymentForm(user=self.user, data=data, request=self.request) expected = sorted([(country.alpha_2, country.name) for country in pycountry.countries], key=lambda x: x[1]) actual = list(form.fields['country'].choices) actual.pop(0) # Remove the "Choose country" placeholder self.assertEqual(actual, expected)
Example #18
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 5 votes |
def test_lookup(): c = pycountry.countries g = c.get(alpha_2='DE') assert g == c.get(alpha_2='de') assert g == c.lookup('de') assert g == c.lookup('DEU') assert g == c.lookup('276') assert g == c.lookup('germany') assert g == c.lookup('Federal Republic of Germany') # try a generated field bqaq = pycountry.historic_countries.get(alpha_4='BQAQ') assert bqaq == pycountry.historic_countries.lookup('atb') german = pycountry.languages.get(alpha_2='de') assert german == pycountry.languages.lookup('De') euro = pycountry.currencies.get(alpha_3='EUR') assert euro == pycountry.currencies.lookup('euro') latin = pycountry.scripts.get(name='Latin') assert latin == pycountry.scripts.lookup('latn') al_bu = pycountry.subdivisions.get(code='AL-BU') assert al_bu == pycountry.subdivisions.lookup('al-bu') with pytest.raises(LookupError): pycountry.countries.lookup('bogus country') with pytest.raises(LookupError): pycountry.countries.lookup(12345) with pytest.raises(LookupError): pycountry.countries.get(alpha_2=12345)
Example #19
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 5 votes |
def test_get(): c = pycountry.countries with pytest.raises(TypeError): c.get(alpha_2='DE', alpha_3='DEU') assert c.get(alpha_2='DE') == c.get(alpha_3='DEU') assert c.get(alpha_2='Foo') is None tracer = object() assert c.get(alpha_2='Foo', default=tracer) is tracer
Example #20
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 5 votes |
def test_subdivisions_directly_accessible(): assert len(pycountry.subdivisions) == 4883 assert isinstance(list(pycountry.subdivisions)[0], pycountry.db.Data) de_st = pycountry.subdivisions.get(code='DE-ST') assert de_st.code == u'DE-ST' assert de_st.name == u'Sachsen-Anhalt' assert de_st.type == u'State' assert de_st.parent is None assert de_st.parent_code is None assert de_st.country is pycountry.countries.get(alpha_2='DE')
Example #21
Source File: test_general.py From pycountry with GNU Lesser General Public License v2.1 | 5 votes |
def test_germany_has_all_attributes(): germany = pycountry.countries.get(alpha_2='DE') assert germany.alpha_2 == u'DE' assert germany.alpha_3 == u'DEU' assert germany.numeric == u'276' assert germany.name == u'Germany' assert germany.official_name == u'Federal Republic of Germany'
Example #22
Source File: column.py From AnyBlok with Mozilla Public License 2.0 | 5 votes |
def update_table_args(self, registry, Model): """Return check constraints to limit the value :param registry: :param Model: :return: list of checkConstraint """ if self.encrypt_key: # dont add constraint because the state is crypted and nobody # can add new entry return [] if sgdb_in(registry.engine, ['MariaDB', 'MsSQL']): # No Check constraint in MariaDB return [] enum = [country.alpha_3 for country in pycountry.countries] constraint = """"%s" in ('%s')""" % (self.fieldname, "', '".join(enum)) enum.sort() key = md5() key.update(str(enum).encode('utf-8')) name = self.fieldname + '_' + key.hexdigest() + '_types' return [CheckConstraint(constraint, name=name)]
Example #23
Source File: column.py From AnyBlok with Mozilla Public License 2.0 | 5 votes |
def process_result_value(self, value, dialect): if value: return pycountry.countries.get(alpha_3=value) return value
Example #24
Source File: advanced.py From kano-settings with GNU General Public License v2.0 | 5 votes |
def make_safesearch_config_file(config_file, opendns): new_config = {"port": 53, "host": "127.0.0.1", "rules": []} if opendns: servers = ', '.join(opendns_servers) else: # use google servers servers = ', '.join(google_servers) import pycountry import json rule_google = "cname ^(?:www.google.)(?:{}) to forcesafesearch.google.com using " + servers rule_youtube = "cname ^(?:www.youtube.|m.youtube.|youtubei.googleapis.|youtube.googleapis.|www.youtube-nocookie.)(?:{}) " \ "to restrict.youtube.com using " + servers country_names = [country.alpha2.lower() for country in pycountry.countries] country_names.extend(second_level_domains) country_names_re = '|'.join(country_names) new_config['rules'].append(rule_google.format(country_names_re)) new_config['rules'].append(rule_youtube.format(country_names_re)) new_config['rules'].append("resolve ^(.*) using " + servers) logger.debug("new safesearch parental control config: {}".format(new_config)) g = open(config_file, 'w+') json.dump(new_config, g) g.close() logger.debug("finished writing new safesearch parental control to {}".format(config_file))
Example #25
Source File: advanced.py From kano-settings with GNU General Public License v2.0 | 4 votes |
def add_safesearch_blacklist(hosts): ''' Prevents surfing to generic search engine sites by adding them to the blacklist ''' # import pycountry here as it takes a long time to import. import pycountry logger.debug("Applying safesearch settings") # Block search sites search_sites = [ 'google.com', 'bing.com', 'search.yahoo.com', 'uk.search.yahoo.com', 'ask.com', 'uk.ask.com', # pycountry does not return "uk", but "gb" 'search.aol.com', 'aolsearch.com', 'search.com', 'uk.search.com', 'wow.com', 'webcrawler.com', 'zoo.com', # Webcrawler sometimes redirects to zoo.com 'mywebsearch.com', 'home.mywebsearch.com', 'infospace.com', 'info.com', 'duckduckgo.com', 'blekko.com', 'contenko.com', 'dogpile.com', 'alhea.com', 'uk.alhea.com'] # Blacklist major search engines for site in search_sites: add_blacklist_host(hosts, site) # Add subdomains only to those search engines that need it for country in pycountry.countries: add_blacklist_host(hosts, 'google.{}'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.ask.com'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.search.yahoo.com'.format(country.alpha2.lower())) add_blacklist_host(hosts, 'search.yahoo.{}'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.search.com'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.wow.com'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.webcrawler.com'.format(country.alpha2.lower())) # Some search engines are redirecting to zoo.com and possibly [country] add_blacklist_host(hosts, 'zoo.{}'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.info.com'.format(country.alpha2.lower())) add_blacklist_host(hosts, '{}.alhea.com'.format(country.alpha2.lower())) for subdomain in second_level_domains: add_blacklist_host(hosts, 'google.{}'.format(subdomain)) return hosts