def load_db(db): raw_data = osconfeed.load() for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] for record in rec_list: key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn(f'loading {DB_NAME}') for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # remove plural s for record in rec_list: key = f'{record_type}.{record["serial"]}' # build key record['serial'] = key # update the record with the full key db[key] = Record(**record)
def load_db(db: object) -> object: raw_data = osconfeed.load() # <3> warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): # <4> record_type = collection[:-1] # <5> for record in rec_list: key = '{}.{}'.format(record_type, record['serial']) # <6> record['serial'] = key # <7> db[key] = Record(**record) # <8>
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] for record in rec_list: key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn("loading " + DB_NAME) for collection, rec_list in raw_data["Schedule"].items(): record_type = collection[:-1] for record in rec_list: key = "{}.{}".format(record_type, record["serial"]) record["serial"] = key db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading '+DB_NAME) for collection,res_list in raw_data['Schedule'].items(): record_type = collection[:-1] for record in res_list: key = '{}.{}'.format(record_type,record['serial'])#定义key值 record['serial'] = key db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # 컬렉션 명에서 s 제거 for record in rec_list: key = '{}.{}'.format(record_type, record['serial']) # record_type 과 'serial' 필드로부터 key 생성 record['serial'] = key # 'serial' 필드를 새로 생성한 key 로 설정 db[key] = Record(**record) # Record 객체 생성 후 해당 key 로 저장
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] cls_name = record_type.capitalize() cls = globals().get(cls_name, DbRecord) if inspect.isclass(cls) and issubclass(cls, DbRecord): factory = DbRecord for record in rec_list: key = '{}.{}'.format(record_type, record['serial'])
def load_db(db): # 데이터베이스가 없을 떄 실행되는데 raw_data = osconfeed.load() # <3> json파일을 불러와서 warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items( ): # <4> 스케쥴의 아이템들(리스트인데 원소는 딕셔너리임)별로 record_type = collection[:-1] # <5> s제거 for record in rec_list: # record는 딕셔너리임; rec_list는 딕셔너리들의 리스트임 key = '{}.{}'.format( record_type, record['serial'] ) # <6> conference.id, event.id, speaker.id, venue.id record['serial'] = key # <7> 키 변경 db[key] = Record(**record) # <8> 변경한 키에 아이템은 키만 살짝바꾼 키워드매개변수로 전달
def load_db(db): # this may fetch the JSON feed from the Web, if there's no local copy raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) # iterate over the collections (ie. 'conferences', 'events' etc.) for collection, rec_list in raw_data['Schedule'].items(): # record_type is set to the collection name without the trailing 's', i.e. 'events' becomes 'event' record_type = collection[:-1] for record in rec_list: # build key from the record_type and the 'serial' field key = '{}.{}'.format(record_type, record['serial']) # update 'serial' field with the full key record['serial'] = key # build Record instance and save it to the database under the key db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # <1> cls_name = record_type.capitalize() # <2> cls = globals().get(cls_name, DbRecord) # <3> if inspect.isclass(cls) and issubclass(cls, DbRecord): # <4> factory = cls # <5> else: factory = DbRecord # <6> for record in rec_list: # <7> key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = factory(**record) # <8>
def load_db(db): raw_data = osconfeed.load() warnings.warn(f'loading {DB_NAME}') for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] cls_name = record_type.capitalize() cls = globals().get(cls_name, DbRecord) if inspect.isclass(cls) and issubclass(cls, DbRecord): factory = cls else: factory = DbRecord for record in rec_list: key = f'{record_type}.{record["serial"]}' record['serial'] = key db[key] = factory(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, records in raw_data['Schedule'].items(): record_type = collection[:-1] cls_name = record_type.capitalize() cls = globals().get(cls_name, DbRecord) if inspect.isclass(cls) and issubclass(cls, DbRecord): factory = cls else: factory = DbRecord for record in records: key = f"{record_type}.{record['serial']}" record['serial'] = key print(record) db[key] = factory(**record)
def load_db(db): raw_data = osconfeed.load() for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # 1 cls_name = record_type.capitalize() # 2 首字母大写,获取可能的类名 cls = globals().get(cls_name, DbRecord) # 3 从全局作用域中获取那个名称对应的对象,默认使用DbRecord if inspect.isclass(cls) and issubclass( cls, DbRecord): # 4 获取的对象是类 且是DbRecord的子类 factory = cls # 5 把对象复制给factory变量。因此,factory的值可能是DbRecord的任何一个子类,具体取决域record_type else: factory = DbRecord # 6 for record in rec_list: # 7 key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = factory(**record) # 8
def load_db(db): raw_data = osconfeed.load() warnings.warn("loading " + DB_NAME) for collection, rec_list in raw_data["Schedule"].items(): record_type = collection[:-1] cls_name = record_type.capitalize() cls = globals().get(cls_name, DBRecord) if inspect.isclass(cls) and issubclass(cls, DBRecord): factory = cls else: factory = DBRecord for record in rec_list: key = "{}.{}".format(record_type, record["serial"]) record["serial"] = key db[key] = factory(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # <1> "events" => "event" cls_name = record_type.capitalize() # <2> # globals(): Return the dictionary containing the current scope's global variables. # dict.get(k, d): D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. cls = globals().get(cls_name, DbRecord) # <3> if inspect.isclass(cls) and issubclass(cls, DbRecord): # <4> factory = cls # <5> else: factory = DbRecord # <6> for record in rec_list: # <7> key = '{}.{}'.format(record_type, record['serial']) # "event.33950" record['serial'] = key db[key] = factory(**record) # <8>
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): record_type = collection[:-1] # <1> cls_name = record_type.capitalize() # 首字母大写 cls = globals().get(cls_name, DbRecord) # 从全局对象中获取名称对应的对象,找不到就用DbRecord if inspect.isclass(cls) and issubclass(cls, DbRecord): # 判断是否是派生类或者子类 factory = cls # <5> else: factory = DbRecord # 因为如果叫json里面叫event,已经有Event继承DbRecord,就可以用class Event for record in rec_list: # <7> key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = factory(**record) # 不过创建的class不太一样了 pass pass
def load_db(db): """ >>> import shelve >>> db = shelve.open(DB_NAME) >>> if CONFERENCE not in db: ... load_db(db) >>> speaker = db['speaker.3471'] >>> type(speaker) <class 'schedule.Record'> >>> speaker.name, speaker.twitter ('Anna Ravenscroft', 'annaraven') >>> db.close() """ raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, records in raw_data['Schedule'].items(): record_type = collection[:-1] for record in records: key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key db[key] = Record(**record)
def load_db(db): ''' >>> import shelve >>> db = shelve.open(DB_NAME) >>> if CONFERENCE not in db: ... load_db(db) >>> event = db["event.33451"] >>> type(event) <class 'schedule1.Record'> >>> event.name, event.event_type ('Migrating to the Web Using Dart and Polymer - A Guide for Legacy OOP Developers', '40-minute conference session') ''' raw_data = osconfeed.load() warnings.warn("loading " + DB_NAME) for collection, rec_list in raw_data["Schedule"].items(): record_type = collection[:-1] # print("record_type:", record_type) for record in rec_list: key = "{}.{}".format(record_type, record["serial"]) record["serial"] = key # print("serial:", record["serial"]) db[key] = Record(**record)
def load_db(db): raw_data = osconfeed.load() warnings.warn('loading ' + DB_NAME) for collection, rec_list in raw_data['Schedule'].items(): # so far, no changes from the load_db in schedule1.py record_type = collection[:-1] # capitalize the record_type to get a potential class name; e.g 'event' becomes 'Event' cls_name = record_type.capitalize() # get an object by that name from the module global scope; get DbRecord if there's no such object cls = globals().get(cls_name, DbRecord) # if the object just retrieved is a class and is a subclass of DbRecord ... if inspect.isclass(cls) and issubclass(cls, DbRecord): # ... bind the factory name to it. This means factory may be any subclass of DbRecord, depending on the record_type factory = cls else: # otherwise, bind the factory name to DbRecord factory = DbRecord # the for loop which creates the key and saves the records is the same as before, except that ... for record in rec_list: key = '{}.{}'.format(record_type, record['serial']) record['serial'] = key # ... the object stored in the database is constructed by factory, which may be DbRecord or a subclass selected according to the record_type db[key] = factory(**record)
else: return FrozenJSON.build(self.__data[item]) # KeyError will happen here if item is not in the keys @classmethod def build(cls, obj): if isinstance(obj, abc.Mapping): return FrozenJSON(obj) elif isinstance(obj, abc.MutableSequence): return [FrozenJSON.build(item) for item in obj] else: return obj if __name__ == '__main__': from osconfeed import load feed = load() fj = FrozenJSON(feed) print(len(fj.Schedule.speakers)) print(sorted(fj.Schedule.keys())) for key, value in sorted(fj.Schedule.items()): print('{:3} {}'.format(len(value), key)) print(fj.Schedule.speakers[-1].name) talk = fj.Schedule.events[40] print(type(talk)) print(talk.name) print(talk.speakers) # print(talk.flavor) # this one will has a KeyError
return super().__new__(cls) elif isinstance(arg, abc.MutableSequence): return [cls(item) for item in arg] return arg def __init__(self, mapping): self.__data = {} for k, v in mapping.items(): if keyword.iskeyword(k): k += '_' self.__data[k] = v def __getattr__(self, name): if hasattr(self.__data, name): return getattr(self.__data, name) else: return FrozenJson.build(self.__data[name]) if __name__ == '__main__': raw_feed = load() feed = FrozenJson(raw_feed) print(len(feed.Schedule.speakers)) talk = feed.Schedule.events[40] print(type(talk)) print(talk.name) print(talk.speakers) print(talk.flavor)
class FrozenJSON: '''一个只读接口,使用属性访问JSON类对象 ''' def __new__(cls, arg): if isinstance(arg, abc.Mapping): return super().__new__(cls) elif isinstance(arg, abc.MutableSequence): return [cls(item) for item in arg] else: return arg def __init__(self, mapping): self.__data = {} #构建字典,创建副本 for key, value in mapping.items(): if iskeyword(key): key += '_' self.__data[key] = value def __getattr__(self, name): if hasattr(self.__data, name): #检查本身是否有此属性 return getattr(self.__data, name) #如果是那就返回此属性 else: return FrozenJSON(self.__data[name]) from osconfeed import load some_thing = load() feed_item = FrozenJSON(some_thing) a = feed_item.Schedule.venues[0].name print(a)