#19.1 converting data using dynamic properties
"""
#栗子19-2 osconfeed.py: Download Osconfeed.json
From urllib.request import Urlopen
Import OS
Import warnings
Import JSON
Import Sys
URL = ' Http://www.oreilly.com/pub/sc/osconfeed '
JSON = ' Data/osconfeed.json '
Path = Os.path.join (Sys.path[0],json)
Path = path.replace (' \ \ ', '/')
def load ():
If not os.path.exists (path):
msg = ' Downloading {} to {} '. Format (Url,path)
Warnings.warn (msg)
With Urlopen (URL) as Remote,open (path, ' WB ') as Local:
Local.write (Remote.read ())
With open (path, ' RB ') as FP:
return Json.load (FP)
feed = Load ()
Print (sorted (feed[' Schedule '].keys ())) #[' conferences ', ' events ', ' speakers ', ' venues ']
For Key,value in sorted (feed[' Schedule '].items ()):
Print (' {: 3} {} '. Format (len (value), key))
‘‘‘
1 Conferences
494 Events
357 Speakers
Venues
‘‘‘
Print (feed[' Schedule ' [' Speakers '][-1][' name ']) #Carina C. Zona
Print (feed[' Schedule ' [' Speakers '][-1][' serial ']) #141590
Print (feed[' Schedule ' [' Events '][40][' name ']) #There *will* be Bugs
Print (feed[' Schedule ' [' Events '][40][' speakers ']) #[3471, 5199]
"""
#栗子19-5 Calling properties by "Dot"
From urllib.request import Urlopen
Import OS
Import warnings
Import JSON
Import Sys
URL = ' Http://www.oreilly.com/pub/sc/osconfeed '
JSON = ' Data/osconfeed.json '
Path = Os.path.join (Sys.path[0],json)
Path = path.replace (' \ \ ', '/')
JSON1 = ' Data/osconfeed1.json '
path1 = Os.path.join (sys.path[0],json1)
path1 = path1.replace (' \ \ ', '/')
def load ():
If not os.path.exists (path):
msg = ' Downloading {} to {} '. Format (Url,path)
Warnings.warn (msg)
With Urlopen (URL) as Remote,open (path, ' WB ') as Local:
Local.write (Remote.read ())
With open (path1, ' RB ') as FP:
return Json.load (FP)
From collections Import ABC
Class Frozenjson:
def __init__ (self, mapping):
Self.__data = dict (mapping)
def __getattr__ (self, name):
If Hasattr (Self.__data, name):
Return GetAttr (self.__data, name)
Else
Return Frozenjson.build (Self.__data[name])
@classmethod
def build (CLS, obj):
If Isinstance (obj, ABC. Mapping):
Return CLS (obj)
Elif isinstance (obj, ABC. Mutablesequence):
return [Cls.build (item) for item in obj]
Else
return obj
Raw_feed = Load ()
feed = Frozenjson (raw_feed)
Print (len (feed). Schedule.speakers))
"Python" "meta-programming" "One" Dynamic properties and attributes