예제 #1
0
파일: schema.py 프로젝트: mbarkhau/lightbus
    def load_local(self, source: Union[str, Path, TextIO] = None):
        """Load schemas from a local file

        These files will be treated as local schemas, and will not be sent to the bus.
        This can be useful for validation during development and testing.
        """
        if isinstance(source, str):
            source = Path(source)

        def _load_schema(path, file_data):
            try:
                return json.loads(file_data)
            except JSONDecodeError as e:
                raise InvalidSchema(
                    "Could not parse schema file {}: {}".format(path, e.msg))

        if source is None:
            # No source, read from stdin
            schema = _load_schema("[stdin]", sys.stdin.read())
        elif hasattr(source, "is_dir") and source.is_dir():
            # Read each json file in directory
            schemas = []
            for file_path in source.glob("*.json"):
                schemas.append(
                    _load_schema(file_path,
                                 file_path.read_text(encoding="utf8")))
            schema = ChainMap(*schemas)
        elif hasattr(source, "read"):
            # Read file handle
            schema = _load_schema(source.name, source.read())
        elif hasattr(source, "read_text"):
            # Read pathlib Path
            schema = _load_schema(source.name, source.read_text())
        else:
            raise InvalidSchema(
                "Did not recognise provided source as either a "
                "directory path, file path, or file handle: {}".format(source))

        for api_name, api_schema in schema.items():
            self.local_schemas[api_name] = api_schema

        return schema
    "country": "US"
}
print("Default command line args :")
print(defaults)

parser = argparse.ArgumentParser(
    description="Test reading command line arguments.")
parser.add_argument("-c", "--color", help="Specifies the preferred color.")
parser.add_argument("-u", "--user", help="Specifies the current user.")
parser.add_argument("-o",
                    "--os",
                    help="Specifies the preferred Operating System.")
parser.add_argument("-l", "--language", help="Specifies the user language.")
parser.add_argument("-n", "--country", help="Specifies the current country.")
namespace = parser.parse_args()

actual_command_line_args = {k: v for k, v in vars(namespace).items() if v}
# vars(obj) :   returns the __dict__ attribute for an object (if present).
print("actual_command_line_args:", actual_command_line_args)

# Dont't link them together like this, it will copy all the data:
# result = defaults.copy()
# result.update(os.environ)
# result.update(actual_command_line_args)

# use this instead, doesn't copy but itterates :
result = ChainMap(actual_command_line_args, defaults)
print("Resulting command line args :")
for k, v in result.items():
    print(k, "-->", v)