How to use the pycountry.subdivisions function in pycountry

To help you get started, we’ve 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 scaleway / postal-address / test_address.py View on Github external
def test_subdivision_derived_fields(self):
        address = Address(
            line1='31, place du Théatre',
            postal_code='59000',
            city_name='Lille',
            subdivision_code='FR-59')

        self.assertEquals(
            address.subdivision, subdivisions.get(code='FR-59'))
        self.assertEquals(
            address.subdivision_code, 'FR-59')
        self.assertEquals(
            address.subdivision_name, 'Nord')
        self.assertEquals(
            address.subdivision_type_name, 'Metropolitan department')
        self.assertEquals(
            address.subdivision_type_id, 'metropolitan_department')

        self.assertEquals(
            address.metropolitan_department, subdivisions.get(code='FR-59'))
        self.assertEquals(
            address.metropolitan_department_code, 'FR-59')
        self.assertEquals(
            address.metropolitan_department_name, 'Nord')
        self.assertEquals(
github scaleway / postal-address / test_address.py View on Github external
def test_subdivision_type_id_collision(self):
        # The subdivision metadata IDs we derived from subdivision types should
        # not collide with Address class internals.
        simple_address = Address(
            line1='10, avenue des Champs Elysées',
            postal_code='75008',
            city_name='Paris',
            country_code='FR')

        # Check each subdivision metadata.
        for subdiv in subdivisions:

            # XXX ISO 3166-2 reuse the country type as subdivisions.
            # We really need to add proper support for these cases, as we did
            # for cities.
            if subdivision_type_id(subdiv) in ['country']:
                continue

            for metadata_id, metadata_value in subdivision_metadata(
                    subdiv).items():
                # Check collision with any atrribute defined on Address class.
                if metadata_id in Address.SUBDIVISION_METADATA_WHITELIST:
                    self.assertTrue(hasattr(simple_address, metadata_id))
                else:
                    self.assertFalse(hasattr(simple_address, metadata_id))
github scaleway / postal-address / test_address.py View on Github external
def test_country_code_reconciliation(self):
        # Test reconciliation of ISO 3166-2 and ISO 3166-1 country codes.
        for subdiv_code in SUBDIVISION_ALIASES.keys():
            target_code = SUBDIVISION_ALIASES[subdiv_code]
            if len(target_code) != 2:
                target_code = subdivisions.get(code=target_code).country_code
            self.assertEquals(
                normalize_country_code(subdiv_code), target_code)
        for subdiv_code in set(
                imap(attrgetter('code'), subdivisions)).difference(
                    SUBDIVISION_ALIASES):
            self.assertEquals(
                normalize_country_code(subdiv_code),
                subdivisions.get(code=subdiv_code).country_code)
github benbest86 / myewb2 / myewb / siteutils / models.py View on Github external
)
  
  # want a combo box for this -- choices/custom
  label = models.CharField(_('number type'), max_length=255, choices=PHONE_LABELS, null=True, blank=True)
  number = models.CharField(_('phone number'), max_length=255, null=True, blank=True)

  def __unicode__(self):
    return "%s: %s" % (self.label, self.number)

provinces = []
provincelist = list(pycountry.subdivisions.get(country_code='CA'))
for p in provincelist:
    provinces.append((p.code.split('-')[1], p.name))
provinces = sorted(provinces)
provinces2 = []
provincelist = pycountry.subdivisions.get(country_code='US')
for p in provincelist:
    provinces2.append((p.code.split('-')[1], p.name))
provinces2 = sorted(provinces2)
provinces += provinces2
provinces.append(('', 'None / Other'))
        
countries2 = list(pycountry.countries)
countries = []
for c in countries2:
    countries.append((c.alpha2, c.name))

class Address(models.Model):
  content_type = models.ForeignKey(ContentType)
  object_id = models.PositiveIntegerField()
  content_object = generic.GenericForeignKey()
github pretix / pretix / src / pretix / base / models / invoices.py View on Github external
def address_invoice_to(self):
        if self.invoice_to and not self.invoice_to_company and not self.invoice_to_name:
            return self.invoice_to

        state_name = ""
        if self.invoice_to_state:
            state_name = self.invoice_to_state
            if str(self.invoice_to_country) in COUNTRIES_WITH_STATE_IN_ADDRESS:
                if COUNTRIES_WITH_STATE_IN_ADDRESS[str(self.invoice_to_country)][1] == 'long':
                    state_name = pycountry.subdivisions.get(
                        code='{}-{}'.format(self.invoice_to_country, self.invoice_to_state)
                    ).name

        parts = [
            self.invoice_to_company,
            self.invoice_to_name,
            self.invoice_to_street,
            ((self.invoice_to_zipcode or "") + " " + (self.invoice_to_city or "") + " " + (state_name or "")).strip(),
            self.invoice_to_country.name if self.invoice_to_country else "",
        ]
        return '\n'.join([p.strip() for p in parts if p and p.strip()])
github oasis-open / cti-stix-elevator / elevator / convert_stix.py View on Github external
def convert_ciq_addresses(addresses, identity_instance):
    identity_instance["country"] = []
    identity_instance["regions"] = []
    for add in addresses:
        if hasattr(add, "country"):
            for name in add.country.name_elements:
                iso = pycountry.countries.get(name=name.value)
                if iso is not None:
                    identity_instance["country"].append(iso.alpha2)
                else:
                    warn("No ISO code for {val}".format(val=name.value))
                    identity_instance["country"].append(name.value)
        if hasattr(add, "administrative_area"):
            for name in add.administrative_area.name_elements:
                # bug in pycountry - need to make sure that subdivisions are indexed using "name"
                iso = pycountry.subdivisions.get(name=name.value)
                if iso is not None:
                    identity_instance["regions"].append(iso.code)
                else:
                    identity_instance["regions"].append(name.value)
github hbz / oerworldmap / import / hewlett / import.py View on Github external
def fill_subdivision_list():
    global subdivisions_by_countries
    current_country = ''
    current_subdiv_list = []
    for subdivision in pycountry.subdivisions:
        if not subdivision.country_code.__eq__(current_country):
            subdivisions_by_countries[current_country] = current_subdiv_list
            current_country = str(subdivision.country_code)
            current_subdiv_list = []
        current_subdiv_list.append(str(subdivision.code))
github Harmon758 / Harmonbot / Discord / cogs / lichess.py View on Github external
profile.get("bio"), False))
		else:
			description = profile.get("bio")
		fields.append(("Online", "Yes" if user_data["online"] else "No"))
		fields.append(("Patron", "Yes" if user_data.get("patron") else "No"))
		if "fideRating" in profile:
			fields.append(("FIDE Rating", profile["fideRating"]))
		if "uscfRating" in profile:
			fields.append(("USCF Rating", profile["uscfRating"]))
		# TODO: Add ECF Rating
		if "country" in profile:
			country = profile["country"]
			country_name = pycountry.countries.get(alpha_2 = country[:2]).name
			country_flag = emoji.emojize(f":{country_name.replace(' ', '_')}:")
			if len(country) > 2:  # Subdivision
				country_name = pycountry.subdivisions.get(code = country).name
			# Wait for subdivision flag emoji support from Discord
			# From Unicode 10.0/Emoji 5.0/Twemoji 2.3
			# For England, Scotland, and Wales
			fields.append(("Location", f"{profile.get('location', '')}\n{country_flag} {country_name}"))
		elif "location" in profile:
			fields.append(("Location", profile["location"]))
		created_at = datetime.datetime.utcfromtimestamp(user_data["createdAt"] / 1000.0)
		fields.append(("Member Since", created_at.strftime("%b %#d, %Y")))
		# %#d for removal of leading zero on Windows with native Python executable
		if "completionRate" in user_data:
			fields.append(("Game Completion Rate", f"{user_data['completionRate']}%"))
		fields.append(("Followers", user_data["nbFollowers"]))
		fields.append(("Following", user_data["nbFollowing"]))
		playtime = user_data.get("playTime", {})
		if "total" in playtime:
			fields.append(("Time Spent Playing",
github jhpyle / docassemble / docassemble_base / docassemble / base / functions.py View on Github external
def subdivision_type(country_code):
    """Returns the name of the most common country subdivision type for
    the given country code."""
    counts = dict()
    for subdivision in pycountry.subdivisions.get(country_code=country_code):
        if subdivision.parent_code is not None:
            continue
        if subdivision.name not in counts:
            counts[subdivision.type] = 1
        else:
            counts[subdivision.type] += 1
    counts_ordered = sorted(counts.keys(), key=lambda x: counts[x], reverse=True)
    if len(counts_ordered) > 1 and counts[counts_ordered[1]] > 1:
        return counts_ordered[0] + '/' + counts_ordered[1]
    elif len(counts_ordered) > 0:
        return counts_ordered[0]
    else:
        return None
github scaleway / postal-address / postal_address / territory.py View on Github external
if include_country:
            tree.append(countries.get(alpha_2=territory_code))
        return tree

    # Else, resolve the territory as if it's a subdivision code.
    subdivision_code = territory_code
    while subdivision_code:
        subdiv = subdivisions.get(code=subdivision_code)
        tree.append(subdiv)
        if not subdiv.parent_code:
            break
        subdivision_code = subdiv.parent_code

    # Return country
    if include_country:
        tree.append(subdivisions.get(code=subdivision_code).country)

    return tree