Python get country
60 Python code examples are found related to "
get country".
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.
Example 1
Source File: noaa.py From noaa with MIT License | 6 votes |
def get_lat_lon_by_postalcode_country(self, postalcode, country): """Get latitude and longitude coordinate from postalcode and country code. Args: postalcode (str): postal code. country (str): 2 letter country code. Returns: tuple: tuple of latitude and longitude. """ res = self.make_get_request( '/search?postalcode={}&country={}&format=json'.format( postalcode, country), end_point=self.OSM_ENDPOINT) if len(res) == 0 or 'lat' not in res[0] or 'lon' not in res[0]: raise Exception( 'Postalcode and Country: {}, {} does not exist.'.format( postalcode, country)) return float(res[0]['lat']), float(res[0]['lon'])
Example 2
Source File: noaa.py From noaa with MIT License | 6 votes |
def get_postalcode_country_by_lan_lon(self, lat, lon): """Get postalcode and country code by latitude and longitude. Args: lat (float): latitude. lon (float): longitude. Returns: tuple: tuple of postalcode and country code. """ res = self.make_get_request( '/reverse?lat={}&lon={}&addressdetails=1&format=json'.format( lat, lon), end_point=self.OSM_ENDPOINT) if 'address' not in res: raise Exception('No address found.') if 'country_code' not in res['address']: raise Exception('No country code found.') if 'postcode' not in res['address']: raise Exception('No postal code found.') return res['address']['postcode'], res['address']['country_code']
Example 3
Source File: GetLocal.py From crawler_examples with Apache License 2.0 | 6 votes |
def getCountry(ipAddress): ''' 判断一个IP的所在地 ''' try: response = urlopen("http://freegeoip.net/json/" + ipAddress).read().decode('utf-8') except URLError: print("Sleeping!") time.sleep(URLERROR_SLEEP_TIME) response = urlopen("http://freegeoip.net/json/" + ipAddress).read().decode('utf-8') except: return 'Unknown' responseJson = json.loads(response) return responseJson.get("country_code") # 返回国家代号
Example 4
Source File: countryinfo.py From Jarvis with MIT License | 6 votes |
def get_country(self, jarvis): """ function creates request to api and fetches the corresponding data """ while True: country = jarvis.input( "Enter the name of the country or type exit to leave: ") if country == '': jarvis.say("Please enter valid input.") elif country == 'exit': return else: url = "https://restcountries.eu/rest/v2/name/%s?fullText=true" % country r = requests.get(url) if isinstance(r.json(), dict): jarvis.say("Country not found.") else: return r.json()
Example 5
Source File: models.py From pasportaservo with GNU Affero General Public License v3.0 | 6 votes |
def get_for_country(cls, country_code, is_active=True): """ Extracts advices indicated for a specific country, i.e., those applicable to a list of countries among which is the queried country, or those applicable to any country. If `is_active` is True or None, also verifies whether the advice is current or just applicable, correspondingly. However, if `is_active` is False, only advices for this specific country which are not anymore or not yet valid are returned. """ lookups = Q(countries__regex=r'(^|,){}(,|$)'.format(country_code)) if is_active is False: lookups = lookups & Q(is_active=False) else: lookups = lookups | Q(countries='') if is_active is not None: lookups = lookups & Q(is_active=True) return cls.objects.filter(lookups).order_by('-active_until', '-id')
Example 6
Source File: config_utils.py From Retropie-CRT-Edition with GNU General Public License v3.0 | 6 votes |
def get_country(self): if not self.m_sCountry: os.system('cp %s %s > /dev/null 2>&1' % (self.WPA_FILE, self.TMP_FILE)) ctry = ini_get(self.TMP_FILE, "country") os.system("sudo rm %s > /dev/null 2>&1" % self.TMP_FILE) if not ctry: ctry = ini_get(CRT_UTILITY_FILE, "wifi_country") if not ctry: ctry = "ES" for item in self.COUNTRY: if self.COUNTRY[item] == ctry: self.m_sCountry = item break if not self.m_sCountry: self.m_sCountry = "Spain" self.country(self.m_sCountry) return self.m_sCountry
Example 7
Source File: logic.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def get_iso_country_code(ip): db_path = os.path.join( settings.BASE_DIR, 'metrics', 'geolocation', 'GeoLite2-Country.mmdb', ) reader = geoip2.database.Reader(db_path) try: response = reader.country(ip) return response.country.iso_code if response.country.iso_code else 'OTHER' except AddressNotFoundError: if ip == '127.0.0.1': return "GB" return 'OTHER'
Example 8
Source File: country_shapes.py From emissions-api with MIT License | 6 votes |
def get_country_wkt(country): '''Get wkt for country. :param country: alpha 2 or 3 country code. :type country: str :raises CountryNotFound: Country is not found in the country codes. :return: WKT defining the country. :rtype: str ''' if not __country_shapes__: __load_country_shapes__() try: return __country_shapes__[country].wkt except KeyError: raise CountryNotFound
Example 9
Source File: model.py From photonix with GNU Affero General Public License v3.0 | 6 votes |
def get_country(self, lon, lat): # Using country border polygons, returns the country that contains the # given point. location = [[lat, lon]] for shape_rec in self.world: shape = shape_rec.shape record = shape_rec.record points = shape.points if shape.shapeTypeName == 'POLYGON': polygons = self.split_country_points(points) for polygon in polygons: path = mpltPath.Path(polygon) inside = path.contains_points(location)[0] if inside: return { 'name': record[4], 'code': record[1], } return None
Example 10
Source File: Malicious-Proxy-Scanner.py From maliciousProxyScanner with GNU General Public License v2.0 | 6 votes |
def get_country_code(self, proxyip): ''' Get the 3 letter country code of the proxy using geoiptool.com Would use the geoip library, but it requires a local DB and what is the point of that hassle other than marginal speed improvement ''' cc_line_found = False cc = 'N/A' try: r = requests.get('http://www.geoiptool.com/en/?IP=%s' % proxyip, headers=self.headers) html = r.text html_lines = html.splitlines() for l in html_lines: if cc_line_found == True: cc = l.split('(', 1)[1].split(')', 1)[0] break if 'country code:' in l.lower(): cc_line_found = True except: pass return cc
Example 11
Source File: geolocation.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def get_country_name(self, ip_address, debug_message=None): """ Find country name for a given IP address. The ip address might not provide a country name, so return UNKNOWN_COUNTRY in those cases. """ try: name = self.geoip.country_name_by_addr(ip_address) except Exception: # pylint: disable=broad-except if debug_message: log.exception("Encountered exception getting country name for ip_address '%s': %s.", ip_address, debug_message) name = UNKNOWN_COUNTRY if name is None or len(name.strip()) <= 0: if debug_message: log.error("No country name found for ip_address '%s': %s.", ip_address, debug_message) name = UNKNOWN_COUNTRY return name
Example 12
Source File: geolocation.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 6 votes |
def get_country_code(self, ip_address, debug_message=None): """ Find country code for a given IP address. The ip address might not provide a country code, so return UNKNOWN_CODE in those cases. """ try: code = self.geoip.country_code_by_addr(ip_address) except Exception: # pylint: disable=broad-except if debug_message: log.exception("Encountered exception getting country code for ip_address '%s': %s.", ip_address, debug_message) code = UNKNOWN_CODE if code is None or len(code.strip()) <= 0: if debug_message: log.error("No country code found for ip_address '%s': %s.", ip_address, debug_message) code = UNKNOWN_CODE return code
Example 13
Source File: relay_country.py From OrangeAssassin with Apache License 2.0 | 6 votes |
def get_country(self, ipaddr): """Return the country corresponding to an IP based on the network range database. """ if ipaddr.is_private: return "**" if ipaddr.version == 4: reader = self["ipv4"] else: reader = self["ipv6"] if not reader: self.ctxt.log.warning("Database not loaded.") return "XX" response = reader.country_code_by_addr(str(ipaddr)) if not response: self.ctxt.log.info("Can't locate IP '%s' in database", ipaddr) # Cant locate the IP in database. return "XX" return response
Example 14
Source File: lambda_function.py From Course_Alexa_Skill_Builder with MIT License | 6 votes |
def get_user_country(handler_input): base_uri = handler_input.request_envelope.context.system.api_endpoint device_id = handler_input.request_envelope.context.system.device.device_id api_access_token = handler_input.request_envelope.context.system.api_access_token response = requests.get(base_uri + "/v1/devices/" + device_id + "/settings/address/countryAndPostalCode", headers = { 'Accept': 'application/json', 'Authorization': 'Bearer {}'.format(api_access_token) } ) data = json.loads(response.text) return data["countryCode"] # The SkillBuilder object acts as the entry point for your skill, routing all request and response # payloads to the handlers above. Make sure any new handlers or interceptors you've # defined are included below. The order matters - they're processed top to bottom. # Skill Builder object
Example 15
Source File: stats.py From FalconGate with GNU General Public License v3.0 | 6 votes |
def get_country_stats(self): for k in country_stats.keys(): nstats = HourStats() country_stats[k].hourly_stats[self.ctime] = nstats for k in homenet.hosts.keys(): if homenet.hosts[k].mac != homenet.mac: for cid in homenet.hosts[k].conns.keys(): if homenet.hosts[k].conns[cid].ts > (self.ctime - 3600) and homenet.hosts[k].conns[cid].direction == "outbound": ccode = homenet.hosts[k].conns[cid].dst_country_code cname = homenet.hosts[k].conns[cid].dst_country_name try: if ccode: country_stats[ccode].hourly_stats[self.ctime].data_sent += homenet.hosts[k].conns[cid].client_bytes country_stats[ccode].hourly_stats[self.ctime].data_received += homenet.hosts[k].conns[cid].server_bytes country_stats[ccode].hourly_stats[self.ctime].pqt_sent += homenet.hosts[k].conns[cid].client_packets country_stats[ccode].hourly_stats[self.ctime].pqt_received += homenet.hosts[k].conns[cid].server_packets country_stats[ccode].hourly_stats[self.ctime].nconn += homenet.hosts[k].conns[cid].counter else: pass except Exception as e: log.debug('FG-ERROR: ' + str(e.__doc__) + " - " + str(e))
Example 16
Source File: CountryCodes.py From caller-lookup with GNU General Public License v3.0 | 6 votes |
def get_country_data(country_id=None, country_code=None, country_int_dial_code=None): results = [] if country_id is not None: for entry in CallerLookupCountryCodes.COUNTRY_DATA: if country_id.upper() == entry["COUNTRY_ID"]: results.append(entry) if country_code is not None: for entry in CallerLookupCountryCodes.COUNTRY_DATA: if country_code.upper() == entry["COUNTRY_CODE"]: results.append(entry) if country_int_dial_code is not None: for entry in CallerLookupCountryCodes.COUNTRY_DATA: if country_int_dial_code == entry["COUNTRY_INT_DIAL_CODE"]: results.append(entry) return results
Example 17
Source File: util.py From ctf-gameserver with ISC License | 6 votes |
def get_country_names(): """ Returns a list of (English) country names from the OKFN/Core Datasets "List of all countries with their 2 digit codes" list, which has to be available as a file called "countries.csv" in the same directory as this source file. """ csv_file_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'countries.csv') with open(csv_file_name, encoding='utf8') as csv_file: csv_reader = csv.reader(csv_file) # Skip header line next(csv_reader) countries = [row[0] for row in csv_reader] # Some teams have members in multiple countries countries.append('International') return sorted(countries, key=locale.strxfrm)
Example 18
Source File: api.py From akshare with MIT License | 6 votes |
def get_country(country_id=None, incomelevel=None, lendingtype=None, cache=True): """ Retrieve information on a country or regional aggregate. Can specify either country_id, or the aggregates, but not both :country_id: a country id or sequence thereof. None returns all countries and aggregates. :incomelevel: desired incomelevel id or ids. :lendingtype: desired lendingtype id or ids. :cache: use the cache :returns: WBSearchResult containing dictionary objects representing each country """ if country_id: if incomelevel or lendingtype: raise ValueError("Can't specify country_id and aggregates") return id_only_query(COUNTRIES_URL, country_id, cache=cache) args = {} if incomelevel: args["incomeLevel"] = parse_value_or_iterable(incomelevel) if lendingtype: args["lendingType"] = parse_value_or_iterable(lendingtype) return WBSearchResult(fetcher.fetch(COUNTRIES_URL, args, cache=cache))
Example 19
Source File: base.py From asm3 with GNU General Public License v3.0 | 6 votes |
def getLocaleForCountry(self, c): """ Some third party sites only accept a locale in their country field rather than a name. This is most common in the US where some shelters have dealings with people over the border in Mexico and Canada. """ c2l = { "United States of America": "US", "United States": "US", "USA": "US", "Mexico": "MX", "Canada": "CA" } if c is None or c == "": return "US" # Assume US as this is only really used by US publishers if len(c) == 2: return c # Already a country code for k in c2l.keys(): if c.lower() == k.lower(): return c2l[k] return "US" # Fall back to US if no match
Example 20
Source File: proxylib.py From arkc-client with GNU General Public License v2.0 | 6 votes |
def get_country_code(self, hostname, dnsservers): """http://dev.maxmind.com/geoip/legacy/codes/iso3166/""" try: return self.region_cache[hostname] except KeyError: pass try: if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname: iplist = [hostname] elif dnsservers: iplist = dnslib_record2iplist(dnslib_resolve_over_udp(hostname, dnsservers, timeout=2)) else: iplist = socket.gethostbyname_ex(hostname)[-1] if iplist[0].startswith(('127.', '192.168.', '10.')): country_code = 'LOCAL' else: country_code = self.geoip.country_code_by_addr(iplist[0]) except StandardError as e: logging.warning('DirectRegionFilter cannot determine region for hostname=%r %r', hostname, e) country_code = '' self.region_cache[hostname] = country_code return country_code
Example 21
Source File: utils.py From astrobin with GNU Affero General Public License v3.0 | 6 votes |
def get_client_country_code(request): try: DEBUG_COUNTRY = request.GET.get('DEBUG_COUNTRY', None) if DEBUG_COUNTRY is not None: return DEBUG_COUNTRY except AttributeError: pass geoip2 = GeoIP2() try: return geoip2.country_code(get_client_ip(request)) except: return "UNKNOWN" ################################# # TODO: move to affiliation app # #################################
Example 22
Source File: common.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_country(self): try: return TIMEZONE_COUNTRY[self.timezone] except KeyError: return 'FI'
Example 23
Source File: device.py From Servo with BSD 2-Clause "Simplified" License | 5 votes |
def get_purchase_country(self): """ Return legacy stored country name. Or name corresponding to country code """ pc = self.purchase_country if len(pc) > 2: return pc return countries.name(pc)
Example 24
Source File: geolocation.py From normandy with Mozilla Public License 2.0 | 5 votes |
def get_country_code(ip_address): if geoip_reader and ip_address: try: return geoip_reader.country(ip_address).country.iso_code except AddressNotFoundError: pass except GeoIP2Error as exc: logger.warning(exc, extra={"code": WARNING_UNKNOWN_GEOIP_ERROR}) pass return None
Example 25
Source File: network.py From kano-toolset with GNU General Public License v2.0 | 5 votes |
def get_wireless_country(enable_driver=False): ''' Support for Wireless channel 13, by using a country code. You can force it by setting KANO_WIFI_COUNTRY envvar to the ISO/IEC alpha2 country code format ("ES", "US", etc). Otherwise it is currently set automatically if ES locales are detected, in the form "es_AR.UTF-8" through the LANG envvar, translated to "ES". enable_driver allows to set the country to the driver, needed for scanning more frequencies. Returns the country code or None if not found TODO: expect to have more mappings, i.e. en_US.UTF-8 => US Query current wireless country with "sudo iw reg get" ''' country_code = None try: cc = os.getenv('KANO_WIFI_COUNTRY') if not cc: cc = os.getenv('LANG') cc = cc.split('_')[1][:2] if cc and cc not in ('US',): country_code = cc.upper() except Exception: pass # Tell the wireless driver to operate on this country # Allows to scan for more channels where available if country_code and enable_driver: run_cmd('iw reg set %s' % country_code) return country_code
Example 26
Source File: default.py From bugatsinho.github.io with GNU General Public License v3.0 | 5 votes |
def get_country(url): #4 r = client.request(url, headers=headers) r = client.parseDOM(r, 'li', attrs={'class': 'dropdown'})[0] r = zip(client.parseDOM(r, 'a', attrs={'class': 'menu-item'}), client.parseDOM(r, 'a', attrs={'class': 'menu-item'}, ret='href')) for name, link in r: name = re.sub('<.+?>', '', name).replace(' ', ' ') name = client.replaceHTMLCodes(name) name = name.encode('utf-8') link = client.replaceHTMLCodes(link) link = link.encode('utf-8') link = base_url + link if link.startswith('/') else link addDir('[B][COLOR white]%s[/COLOR][/B]' % name, link, 5, ICON, FANART, '') xbmcplugin.setContent(int(sys.argv[1]), 'movies')
Example 27
Source File: dot11.py From CVE-2017-7494 with GNU General Public License v3.0 | 5 votes |
def get_country(self): "Get the 802.11 Management Country element." \ "Returnes a tuple containing Country code, frist channel number, "\ "number of channels and maximum transmit power level" s = self._get_element(DOT11_MANAGEMENT_ELEMENTS.COUNTRY) if s is None: return None code, first, num, max = struct.unpack('3sBBB',s) code = code.strip(' ') return code, first, num, max
Example 28
Source File: flags3_threadpool.py From concurrency2017 with MIT License | 5 votes |
def get_country(base_url, cc): url = '{}/{cc}/metadata.json'.format(base_url, cc=cc.lower()) res = requests.get(url) if res.status_code != 200: res.raise_for_status() return res.json()['country']
Example 29
Source File: geoiputils.py From ivre with GNU General Public License v3.0 | 5 votes |
def get_ranges_by_country(code): return get_ranges_by_data( "GeoLite2-Country.dump-IPv4.csv", lambda line: line[2] == code, )
Example 30
Source File: region.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def get_regions_by_country(self, country_id): db_request = self._build_db_request( sql_file_name='get_regions_by_country.sql', args=dict(country_id=country_id) ) db_result = self.cursor.select_all(db_request) return [Region(**row) for row in db_result]
Example 31
Source File: timezone.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def get_timezones_by_country(self, country_id): db_request = self._build_db_request( sql_file_name='get_timezones_by_country.sql', args=dict(country_id=country_id) ) db_result = self.cursor.select_all(db_request) return [Timezone(**row) for row in db_result]
Example 32
Source File: city.py From selene-backend with GNU Affero General Public License v3.0 | 5 votes |
def get_biggest_city_in_country(self, country_name): """Return the geolocation of the most populous city in a country.""" return self._select_one_into_dataclass( GeographicLocation, sql_file_name='get_biggest_city_in_country.sql', args=dict(country=country_name.lower()) )
Example 33
Source File: gateways.py From bitmask-dev with GNU General Public License v3.0 | 5 votes |
def get_gateways_country_code(self): country_codes = {} locations = self.locations if not locations: return gateways = self.gateways for idx, gateway in enumerate(gateways): gateway_location = gateway.get('location') ip = self._eipconfig.get_gateway_ip(idx) if gateway_location is not None: ccode = locations[gateway['location']]['country_code'] country_codes[ip] = ccode return country_codes
Example 34
Source File: countries_ops.py From mrz with GNU General Public License v3.0 | 5 votes |
def get_country(code: str) -> object: """Get the country string of a valid 3-letter code, None otherwise Parameter: 3-letter code string, conform to ICAO specifications. Note: case insensitive. Returns: Country name string, denominated in English, of the 3-letter code given as parameter, None otherwise. """ for country, value in dictionary.items(): if value == code.upper(): return country return None
Example 35
Source File: ChannelApplicationProvidedService.py From LineVodka with GNU General Public License v3.0 | 5 votes |
def getUserCountryForBilling(self, country, remoteIp): """ Parameters: - country - remoteIp """ pass
Example 36
Source File: base.py From idunn with Apache License 2.0 | 5 votes |
def get_country_codes(self): """ The list of codes is ordered from the least specific to the most specific For example for a placed located in La Réunion: ["FR","RE","RE"] for the country, the state ("région") and the state_district ("département") :return: List of ISO 3166-1 alpha-2 country codes """ ordered_admins = sorted( self.get_raw_admins(), key=lambda a: ZONE_TYPE_ORDER_KEY.get(a.get("zone_type"), 0), reverse=True, ) return [c.upper() for admin in ordered_admins for c in admin.get("country_codes", [])]
Example 37
Source File: ptt_gossiping_ip.py From web-crawler-tutorial with MIT License | 5 votes |
def get_country(ip): if ip: data = json.loads(requests.get('http://freegeoip.net/json/' + ip).text) country_name = data['country_name'] if data['country_name'] else None return country_name return None
Example 38
Source File: ptt_gossiping_ip.py From web-crawler-tutorial with MIT License | 5 votes |
def get_country_ipstack(ip): if ip: url = 'http://api.ipstack.com/{}?access_key={}'.format(ip, API_KEY) data = requests.get(url).json() country_name = data['country_name'] if data['country_name'] else None return country_name return None
Example 39
Source File: manual_meta_funcs.py From ibeis with Apache License 2.0 | 5 votes |
def get_contributor_country(ibs, contributor_rowid_list): r""" Returns: contributor_country_list (list): a contributor's location - country RESTful: Method: GET URL: /api/contributor/location/country/ """ contributor_country_list = ibs.db.get(const.CONTRIBUTOR_TABLE, ('contributor_location_country',), contributor_rowid_list) return contributor_country_list
Example 40
Source File: rules.py From wagtail-personalisation with MIT License | 5 votes |
def get_geoip_country(self, request): GeoIP2 = get_geoip_module() if GeoIP2 is None: return False return GeoIP2().country_code(get_client_ip(request)).lower()
Example 41
Source File: rules.py From wagtail-personalisation with MIT License | 5 votes |
def get_cloudfront_country(self, request): try: return request.META['HTTP_CLOUDFRONT_VIEWER_COUNTRY'].lower() except KeyError: pass
Example 42
Source File: rules.py From wagtail-personalisation with MIT License | 5 votes |
def get_country(self, request): # Prioritise CloudFlare and CloudFront country detection over GeoIP. functions = ( self.get_cloudflare_country, self.get_cloudfront_country, self.get_geoip_country, ) for function in functions: result = function(request) if result: return result
Example 43
Source File: rules.py From wagtail-personalisation with MIT License | 5 votes |
def get_cloudflare_country(self, request): """ Get country code that has been detected by Cloudflare. Guide to the functionality: https://support.cloudflare.com/hc/en-us/articles/200168236-What-does-Cloudflare-IP-Geolocation-do- """ try: return request.META['HTTP_CF_IPCOUNTRY'].lower() except KeyError: pass
Example 44
Source File: account.py From LibrERP with GNU Affero General Public License v3.0 | 5 votes |
def get_country_code(self, cr, uid, partner): if release.major_version == '6.1': address_id = self.pool['res.partner'].address_get( cr, uid, [partner.id])['default'] address = self.pool['res.partner.address'].browse( cr, uid, address_id, context=None) else: address = partner code = partner.vat and partner.vat[0:2].upper() return address.country_id.code or code
Example 45
Source File: device_utils.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def GetCountry(self, cache=False): """Returns the country setting on the device. Args: cache: Whether to use cached properties when available. """ return self.GetProp('persist.sys.country', cache=cache)
Example 46
Source File: data.py From pyvin with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_country(c): qi = get_index(c) for country in VIN_COUNTRIES: i = get_index(country[0]) j = get_index(country[1]) if qi >= i and qi <= j: return country[2] return "Not assigned"
Example 47
Source File: filter.py From repository.evgen_dev.xbmc-addons with GNU General Public License v2.0 | 5 votes |
def get_country_list(self): html = self.ajax('%s/engine/ajax/get_filter.php' % SITE_URL, {'scope':'search', 'type':'countries'}) result = {'name' : [xbmcup.app.lang[30136]], 'href': ['']} if not html: return None, result genres = json.loads(html, 'utf-8') for genre in genres: result['name'].append(genres[genre].strip().encode('utf-8').decode('utf-8')) result['href'].append(self.clear_filter_key(genre, 'c')) #print result return CACHE_TIME, result
Example 48
Source File: api.py From openpyn-nordvpn with GNU General Public License v3.0 | 5 votes |
def get_country_code(full_name: str) -> str: url = "https://api.nordvpn.com/server" json_response = get_json(url) for res in json_response: if res["country"].lower() == full_name.lower(): code = res["domain"][:2].lower() return code logger.error("Country Name Not Correct") sys.exit(1)
Example 49
Source File: net.py From kf2-magicked-admin with MIT License | 5 votes |
def get_country(ip): url = "https://freegeoip.app" + "/json/" + ip unknown = (_("Unknown"), "??") try: geo_data = requests.get(url).json() except Exception: return unknown if 'country_name' not in geo_data: return unknown country = geo_data['country_name'] country_code = geo_data['country_code'] return country, country_code
Example 50
Source File: config_utils.py From Retropie-CRT-Edition with GNU General Public License v3.0 | 5 votes |
def get_country_list(self): if not self.status(): list = [] for item in self.COUNTRY: list.append(item) list.sort() return list return None
Example 51
Source File: utils.py From CHN-Server with GNU Lesser General Public License v2.1 | 5 votes |
def get_country_ip(ipaddr): if is_private_addr(ipaddr): return constants.DEFAULT_COUNTRY_NAME name = country_cache.get(ipaddr) if not name: name = _get_country_ip(ipaddr) country_cache.set(ipaddr, name) return name
Example 52
Source File: api.py From Learning-Object-Oriented-Python with GNU General Public License v3.0 | 5 votes |
def get_country(name: str) -> dict: """ API Controlled method to retrieve country details for specified country Arguements: - name <str> name of the country Returns a dict with information about the requested city """ return db.Country.where('Name', '=', name.capitalize()).get().serialize()
Example 53
Source File: api.py From Learning-Object-Oriented-Python with GNU General Public License v3.0 | 5 votes |
def get_country_all() -> dict: """ API Controlled method to retrieve country details for all available countries Returns a dict with information about all available countries """ return db.Country.all().serialize() # Country info calls
Example 54
Source File: __init__.py From pyTSon_plugins with GNU General Public License v3.0 | 5 votes |
def getCountryNamebyID(self, cid): try: return [c for c in self.countries if c[0]==cid][0][1] except: return 'Unknown ('+cid+')'
Example 55
Source File: wikidata.py From followthemoney with MIT License | 5 votes |
def get_country(uri): if uri not in COUNTRIES: for key, value in crawl_node(uri): if key in ['P901', 'P297']: COUNTRIES[uri] = value.get('value') break return COUNTRIES.get(uri)
Example 56
Source File: ip2country.py From ExtAnalysis with GNU General Public License v3.0 | 5 votes |
def get_country(ip): ''' Gets Country and country code from given IP. Parameters = ip = ip address for lookup Response = [True, {country_code}, {country_name}] or [False, {ERR_MSG}] Needs maxminddb for fast performance ''' core.updatelog('Getting country from IP: ' + ip) try: # If maxminddb module is installed we don't have to query online services to get the country code hence saving a lot of time import maxminddb try: core.updatelog('Getting country from local DB') reader = maxminddb.open_database(helper.fixpath(core.path + '/db/geoip.mmdb')) ip_info = reader.get(ip) iso_code = ip_info['country']['iso_code'].lower() country = ip_info['country']['names']['en'] return [True, iso_code, country] except Exception as e: core.updatelog('Something went wrong while getting country from ip {0}! Error: {1}'.format(ip, str(e))) logging.error(traceback.format_exc()) return [False, str(e)] except: core.updatelog('maxminddb module not installed! Using online service to get Country from IP') core.updatelog('To save time in future analysis; install maxminddb by: pip3 install maxminddb') import core.scans as scan gip = scan.geoip(ip) if gip[0]: geoip = gip[1] return [True, geoip['country'].lower(), geoip['country_name']] else: return [False, gip[1]]
Example 57
Source File: movies.py From jellyfin-kodi with GNU General Public License v3.0 | 5 votes |
def get_country(self, *args): try: self.cursor.execute(QU.get_country, args) return self.cursor.fetchone()[0] except TypeError: return self.add_country(*args)
Example 58
Source File: item.py From python-shopee with MIT License | 5 votes |
def get_category_by_country(self, **kwargs): """ Use this api to get categories list filtered by country and cross border without using shopID. :param kwargs: : country(String) - Two-digit country code. : is_cb(uint8) - Is cross border or not. 1: cross border; 0: not cross border @@Significant OpenAPI Updates (2018-09-15/2018-07-18) """ return self.client.execute("item/categories/get_by_country", "POST", kwargs)
Example 59
Source File: public.py From python-shopee with MIT License | 5 votes |
def get_categories_by_country(self, **kwargs): """ Use this api to get categories list filtered by country and cross border without using shopID. :param kwargs - country - is_cb - language :return """ return self.client.execute("item/categories/get_by_country", "POST", kwargs)