Skip to content

Instantly share code, notes, and snippets.

@holly
Last active November 29, 2015 13:35
Show Gist options
  • Save holly/dcb1160b20f4e8a8e531 to your computer and use it in GitHub Desktop.
Save holly/dcb1160b20f4e8a8e531 to your computer and use it in GitHub Desktop.
output country data from https://restcountries.eu/ api
#!/usr/bin/env python3
# vim:fileencoding=utf-8
""" [NAME] script or package easy description
[DESCRIPTION] script or package description
"""
from datetime import datetime
from argparse import ArgumentParser, FileType
import pprint
import time
import warnings
import os, sys, io
import signal
import urllib
import urllib.request
import json
import inspect
import traceback
__author__ = 'holly'
__version__ = '1.0'
DESCRIPTION = 'this is description'
API_URL = 'https://restcountries.eu/rest/v1/all'
parser = ArgumentParser(description=DESCRIPTION)
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('--output', '-o', type=FileType('w'), default=sys.stdout, help='output file. default stdout')
parser.add_argument('--force', '-f', action='store_true', help='force execution')
args = parser.parse_args()
class CountryData(object):
LINE_FORMAT = "\t".join(["{0.name}","{0.translations_ja}","{0.capital}", "{0.lat}", "{0.lng}", "{0.region}", "{0.subregion}", "{0.alpha2code}", "{0.alpha3code}"])
def __init__(self, json_dict):
self.name = None
self.translations_ja = None
self.capital = None
self.nativename = None
self.lat = None
self.lng = None
self.region = None
self.subregion = None
self.alpha2code = None
self.alpha3code = None
# make line string
self.__initialize(json_dict)
def __initialize(self, json_dict):
self.name = json_dict["name"]
self.translations_ja = json_dict["translations"]["ja"]
self.capital = json_dict["capital"]
self.nativename = json_dict["nativeName"]
if len(json_dict["latlng"]) > 0:
self.lat = json_dict["latlng"][0]
self.lng = json_dict["latlng"][1]
self.region = json_dict["region"]
self.region = "None" if json_dict["region"] == "" else json_dict["region"]
self.subregion = "None" if json_dict["subregion"] == "" else json_dict["subregion"]
self.alpha2code = json_dict["alpha2Code"]
self.alpha3code = json_dict["alpha3Code"]
def __str__(self):
return self.__class__.LINE_FORMAT.format(self)
def restcountries2json():
req = urllib.request.Request(API_URL)
with urllib.request.urlopen(req) as res:
json_dicts = json.loads((res.read().decode("utf-8")))
for json_dict in json_dicts:
yield json_dict
def main():
""" [FUNCTIONS] method or functon description
"""
try:
# for header
header_dict = { "name": "name", "translations": {"ja": "translation_ja"}, "capital": "capital", "nativeName": "nativename", "latlng": ["lat", "lng"], "subregion": "subregion", "region": "region", "alpha2Code": "alpha2code", "alpha3Code": "alpha3code" }
print(CountryData(header_dict), file=args.output)
for json_dict in restcountries2json():
data = CountryData(json_dict)
print(data, file=args.output)
except urllib.error.HTTPError as e:
print('{0}: http error'.format(rir))
print(e.read().decode("utf-8").strip())
except Exception as e:
print(type(e))
print(traceback.format_exc())
else:
pass
#print('completed')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment