示例#1
0
    def __init__(self, file_path):
        self.data = {}
        self.global_schemas = {}

        self._fix_schemas(file_path)
        api_raml = ramlfications.parse(file_path, "config.ini")

        self._extract_global_schemas(api_raml)

        # Iterate over each path+method defined in the API
        for resource in api_raml.resources:
            resource_data = {'method': resource.method,
                             'params': resource.uri_params,
                             'body': self._extract_body_schema(resource, file_path),
                             'responses': {}}

            # Add a list for the resource path if we don't have one yet
            if resource.path not in self.data:
                self.data[resource.path] = list()

            # Extract the schemas for the different response codes
            for response in resource.responses:
                # Note: Must check we don't overwrite an existing schema here by checking if it is None or not
                if response.code not in resource_data["responses"] or resource_data["responses"][response.code] is None:
                    resource_data["responses"][response.code] = self._extract_response_schema(response, file_path)

            # Register the collected data in the Specification object
            self.data[resource.path].append(resource_data)
示例#2
0
文件: api.py 项目: sinoroc/apiramid
 def __init__(self, document_path):
     self.raml = ramlfications.parse(document_path)
     self.base_path = urllib.parse.urlparse(self.raml.base_uri).path
     self.media_renderers = DEFAULT_MEDIA_RENDERERS
     self.deserializers = {}
     self.media_deserializers = {}
     return None
示例#3
0
 def __init__(self, apidef_path, args_transform_cb=None, convert_params=False):
     self.raml = ramlfications.parse(apidef_path)
     self.base_uri = self.raml.base_uri
     if self.base_uri.endswith('/'):
         self.base_uri = self.base_uri[:-1]
     self.base_path = urlparse(self.base_uri).path
     self.args_transform_cb = args_transform_cb
     self.convert_params = convert_params
示例#4
0
def build_wsgi_app(raml_file):
    # read raml, create router
    raml = ramlfications.parse(raml_file)
    resources = api.transform_resources(raml, raml.resources)
    resources = filter(filter_absent_method, resources)
    app = build_server(resources)
    print app.map
    app = TransLogger(app, setup_console_handler=False)
    return app
示例#5
0
def raml_from_file(filepath):
    """
    Load RAML object from filepath.

    @param filepath string: RAML specs file path.

    returns raml document root object.
    """
    with open(filepath) as fp:
        return r.parse(fp)
示例#6
0
def get_raml_resources():
    api = ramlfications.parse(RAML_FILE)
    resources = {}
    for resource in api.resources:
        if resource.path in resources:
            resources[resource.path].append(resource.method)
        else:
            resources[resource.path] = [resource.method]

    return resources
示例#7
0
def raml_from_string(ramlsource):
    """
    Load RAML object from string.
    @param ramlsource string: RAML specs string.

    returns raml document root object
    """
    sp = StringIO(ramlsource)
    root = r.parse(sp)
    return root
示例#8
0
def parse_raml(raml_file, data):
    print 'Parsing ' + raml_file
    api = ramlfications.parse(raml_file)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader('./_layouts'))
    env.filters['jsonify'] = json.dumps
    template = env.get_template(RAML_TEMPLATE)

    f = open(os.path.join('docs', raml_file.replace('.raml', '.md')), 'w')
    f.write(template.render(api=api, data=data))
    f.close()
示例#9
0
def parse_raml(raml_file, data):
    print 'Parsing ' + raml_file
    api = ramlfications.parse(raml_file)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader('./_layouts'))
    env.filters['jsonify'] = json.dumps
    template = env.get_template(RAML_TEMPLATE)

    f = open(os.path.join('docs', raml_file.replace('.raml', '.md')), 'w')
    f.write(template.render(api=api, data=data))
    f.close()
示例#10
0
文件: apidef.py 项目: stoer/pyramlson
 def __init__(self,
              apidef_path,
              args_transform_cb=None,
              convert_params=False):
     self.raml = ramlfications.parse(apidef_path)
     self.base_uri = self.raml.base_uri
     if self.base_uri.endswith('/'):
         self.base_uri = self.base_uri[:-1]
     self.base_path = urlparse(self.base_uri).path
     self.args_transform_cb = args_transform_cb
     self.convert_params = convert_params
示例#11
0
def create_context(ramlfile, ramlconfig=None):
    """
    Returns context to populate templates.

    :param str ramlfile:  RAML file to parse
    :param str ramlconfig: config file for RAML (see ``ramlfications`` \
        `docs <https://ramlfications.readthedocs.org/en/latest/config.html>`_)
    :rtype: :py:class:`.APIContext` object
    """
    api = ramlfications.parse(ramlfile, ramlconfig)

    return APIContext(api)
示例#12
0
def main(region, profile='default'):
    project_details = json.load(open('project.json'))
    boto3.setup_default_session(
        profile_name=profile,
        region_name=region
    )
    client = boto3.client('apigateway', region_name=region)
    raml = ramlfications.parse('api_schema.raml')
    api_name = raml.title
    api_gateway = get_api_by_name(client, api_name)
    if api_gateway is None:
        api_gateway = client.create_rest_api(name=api_name)
    aws_resources = client.get_resources(restApiId=api_gateway['id'])['items']
    root = grab_root_resource(aws_resources)
    resources = api.transform_resources(raml, raml.resources)
    # resources = parse_annotations(raml.resources)
    # resources = transform_resources(resources)
    resources = associate_resources(aws_resources, resources)
    aws_authorizers = client.get_authorizers(restApiId=api_gateway['id'])['items']  # NOQA
    authorizers = associate_authorizers(aws_authorizers, raml.security_schemes)
    create_authorizer = functools.partial(
        create_security_scheme,
        client,
        api_gateway['id'],
        project_details['name']
    )
    authorizers = map(create_authorizer, authorizers)

    for resource in resources:
        print 'Creating Resource'
        create_resource(
            client,
            api_gateway['id'],
            root['id'],
            resource,
            project_details['name'],
            authorizers
        )
    deployment = client.create_deployment(
        restApiId=api_gateway['id'],
        stageName=raml.base_uri
    )
    data = {
        'deployment': deployment['id'],
        'api': api_gateway['id'],
        'uri': 'https://{}.execute-api.{}.amazonaws.com/{}/'.format(
            api_gateway['id'],
            region,
            raml.base_uri
        )
    }
    print data
示例#13
0
def includeme(config):
    raml_file = config.get_settings()["ramlrest.raml_file"]
    api = ramlfications.parse(raml_file)
    root = RootRamlResource(api)
    root.dump_tree()

    def root_factory(request):
        return root

    config.add_renderer('yaml', YAMLRenderer())

    config.add_route('raml', '/raml/*traverse', factory=root_factory)
    config.add_view(default_view, route_name='raml', renderer='yaml')
示例#14
0
def _load_raml(config):
    api_config = config["api"]
    raml_file = api_config["raml"]
    logger.debug("Reading RAML file %s", raml_file)
    raml = ramlfications.parse(api_config["raml"])

    conf_version = _get_major_api_version(config)
    if raml.version != conf_version:
        raise ValueError(
            "API version in RAML {} does not match API version in config {}".
            format(raml.version, conf_version))

    return raml
示例#15
0
def main(region, profile='default'):
    session = boto3.Session(profile_name=profile, region_name=region)
    apex_json = json.load(open('project.json'))
    raml = ramlfications.parse('api_schema.raml')
    gateway = ApiGateway(raml, apex_json, session)
    print 'Creating Api Gateway'
    gateway.create()
    gateway.load()
    print 'Creating Authorizers'
    gateway.create_authorizers()
    print 'Creating Resources'
    gateway.create_resources()
    print 'Deploying Stage'
    print gateway.create_deployment()
示例#16
0
    def __init__(self, file_path):
        self.data = {}
        self.global_schemas = {}

        self._fix_schemas(file_path)
        api_raml = ramlfications.parse(file_path, "config.ini")

        self._extract_global_schemas(api_raml)

        # Iterate over each path+method defined in the API
        for resource in api_raml.resources:
            resource_data = {
                'method': resource.method,
                'params': resource.uri_params,
                'body': self._extract_body_schema(resource, file_path),
                'responses': {}
            }

            # Add a list for the resource path if we don't have one yet
            if resource.path not in self.data:
                self.data[resource.path] = list()

            # Extract the schemas for the different response codes
            for response in resource.responses:
                # Note: Must check we don't overwrite an existing schema here by checking if it is None or not
                if response.code not in resource_data[
                        "responses"] or resource_data["responses"][
                            response.code] is None:
                    resource_data["responses"][
                        response.code] = self._extract_response_schema(
                            response, file_path)

            # Register the collected data in the Specification object
            self.data[resource.path].append(resource_data)

            # Record if parent resource GET method should provide a "child resources" response
            path_components = resource.path.split("/")
            # only need the parent "child resources" response if the last path segment is a parameter
            if path_components[-1].startswith('{'):
                parent_path = "/".join(path_components[0:-1])
                # if the API doesn't support the parent path, won't be able to determine parameter values
                if parent_path in self.data:
                    for method_def in self.data[parent_path]:
                        # if the parent doesn't support GET, won't be able to determine parameter values
                        if method_def['method'] == 'get':
                            method_def['child_resources'] = True
示例#17
0
def main(region, profile='default'):
    session = boto3.Session(
        profile_name=profile,
        region_name=region
    )
    apex_json = json.load(open('project.json'))
    raml = ramlfications.parse('api_schema.raml')
    gateway = ApiGateway(raml, apex_json, session)
    print 'Creating Api Gateway'
    gateway.create()
    gateway.load()
    print 'Creating Authorizers'
    gateway.create_authorizers()
    print 'Creating Resources'
    gateway.create_resources()
    print 'Deploying Stage'
    print gateway.create_deployment()
示例#18
0
def convert(source, template, destination):
    if not source:
        raise IOError('Source RAML file must be specified')

    if not template:
        raise IOError('Template file or name must be specified')

    if not destination:
        raise IOError('Destination file must be specified')

    api = ramlfications.parse(source)

    base_template_dir, template_file = resolve_template(template)
    env = Environment(loader=FileSystemLoader(base_template_dir))
    template_instance = env.get_template(template_file)

    with open(destination, 'w') as f:
        f.write(template_instance.render(api=api))
示例#19
0
def parse_raml(template_path):
    api = ramlfications.parse(RAML_FILE)

    data = {}
    data['collection_event_types'] = []
    with open('taxonomies/collection_event_types.csv', 'rb') as csvfile:
        spamreader = csv.DictReader(csvfile)
        # header = spamreader.read()
        for row in spamreader:
            data['collection_event_types'].append(row)

    env = jinja2.Environment(loader=jinja2.FileSystemLoader('./templates'))
    env.filters['jsonify'] = json.dumps
    template = env.get_template(template_path)


    f = open(os.path.join('docs', template_path), 'w')
    f.write(template.render(api=api, data=data))
    f.close()
示例#20
0
def old(region, profile='default'):
    project_details = json.load(open('project.json'))
    boto3.setup_default_session(profile_name=profile, region_name=region)
    client = boto3.client('apigateway', region_name=region)
    raml = ramlfications.parse('api_schema.raml')
    api_name = raml.title
    api_gateway = get_api_by_name(client, api_name)
    if api_gateway is None:
        api_gateway = client.create_rest_api(name=api_name)
    aws_resources = client.get_resources(restApiId=api_gateway['id'])['items']
    root = grab_root_resource(aws_resources)
    resources = api.transform_resources(raml, raml.resources)
    resources = associate_resources(aws_resources, resources)
    aws_authorizers = client.get_authorizers(
        restApiId=api_gateway['id'])['items']  # NOQA
    authorizers = associate_authorizers(aws_authorizers, raml.security_schemes
                                        or [])  # NOQA
    create_authorizer = functools.partial(create_security_scheme, client,
                                          api_gateway['id'],
                                          project_details['name'])
    authorizers = map(create_authorizer, authorizers)

    for resource in resources:
        print 'Creating Resource'
        create_resource(client, api_gateway['id'], root['id'], resource,
                        project_details['name'], authorizers)
    deployment = client.create_deployment(restApiId=api_gateway['id'],
                                          stageName=raml.base_uri)
    data = {
        'deployment':
        deployment['id'],
        'api':
        api_gateway['id'],
        'uri':
        'https://{}.execute-api.{}.amazonaws.com/{}/'.format(
            api_gateway['id'], region, raml.base_uri)
    }
    print data
示例#21
0
    def __init__(self, raml_file):
        PARSER_CONFIG = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resources", "parser_config.ini")
        self.raml = ramlfications.parse(raml_file, PARSER_CONFIG)
        self.generated_directory = os.path.join('generated')
        self.routes_directory = os.path.join('routes')
        self.delegates_directory = os.path.join('delegates')

        # Initializes the list of mime types
        self.mime_types = []

        # Resources to test
        self.test_res = []

        # Initializes the placeholder for comparisons
        self.file_name = ''
        self.new_dict = {}
        self.new_dict2 = {}

        # Determines whether classes will return Success or Failure codes without further implementation
        self.rs = True

        # Allows to set if return parameters are enforced
        self.enre = False
示例#22
0
def test_load_nonexistant_file():
    raml_file = "/tmp/non-existant-raml-file.raml"
    with pytest.raises(LoadRAMLError):
        parse(raml_file)
示例#23
0
def includeme(config):
    from .generators import generate_server, generate_models
    Settings = dictset(config.registry.settings)
    config.include('nefertari.engine')

    config.registry.database_acls = Settings.asbool('database_acls')
    if config.registry.database_acls:
        config.include('nefertari_guards')

    config.include('nefertari')
    config.include('nefertari.view')
    config.include('nefertari.json_httpexceptions')

    # Process nefertari settings
    if Settings.asbool('enable_get_tunneling'):
        config.add_tween('nefertari.tweens.get_tunneling')

    if Settings.asbool('cors.enable'):
        config.add_tween('nefertari.tweens.cors')

    if Settings.asbool('ssl_middleware.enable'):
        config.add_tween('nefertari.tweens.ssl')

    if Settings.asbool('request_timing.enable'):
        config.add_tween('nefertari.tweens.request_timing')

    # Set root factory
    config.root_factory = NefertariRootACL

    # Process auth settings
    root = config.get_root_resource()
    root_auth = getattr(root, 'auth', False)

    log.info('Parsing RAML')
    raml_root = ramlfications.parse(Settings['ramses.raml_schema'])

    log.info('Starting models generation')
    generate_models(config, raml_resources=raml_root.resources)

    if root_auth:
        from .auth import setup_auth_policies, get_authuser_model
        if getattr(config.registry, 'auth_model', None) is None:
            config.registry.auth_model = get_authuser_model()
        setup_auth_policies(config, raml_root)

    config.include('nefertari.elasticsearch')

    log.info('Starting server generation')
    generate_server(raml_root, config)

    log.info('Running nefertari.engine.setup_database')
    from nefertari.engine import setup_database
    setup_database(config)

    from nefertari.elasticsearch import ES
    ES.setup_mappings()

    if root_auth:
        config.include('ramses.auth')

    log.info('Server succesfully generated\n')
示例#24
0
文件: raml.py 项目: postatum/ra
def parse(raml_path_or_string):
    root = ramlfications.parse(raml_path_or_string)
    return RootNode(root)
示例#25
0
 def __init__(self, apidef_path):
     self.raml = ramlfications.parse(apidef_path)
     self.base_uri = self.raml.base_uri
     self.base_path = urlparse(self.base_uri).path
     if self.base_path.endswith('/'):
         self.base_path = self.base_path[:-1]
示例#26
0
def parse(raml_path_or_string):
    root = ramlfications.parse(raml_path_or_string)
    return RootNode(root)
示例#27
0
def resource_types():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.resource_types
示例#28
0
def sec_schemes():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.security_schemes
示例#29
0
def test_parse(raml):
    config = os.path.join(EXAMPLES + "test-config.ini")
    result = parse(raml, config)
    assert result
    assert isinstance(result, RootNode)
示例#30
0
def resource_types():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.resource_types
示例#31
0
 def get_raml_data(self, url):
     api = ramlfications.parse(
         'http://git.gyyx.cn/doc/raml-apis/raw/master/cospower/external-gateway/bak-cos-power-account.raml'
     )
     print(api)
示例#32
0
def create():
    api = ramlfications.parse(os.path.dirname(__file__) + "/raml/myce.raml")
    return APIClient(api)
示例#33
0
def includeme(config):
    from .generators import generate_server, generate_models
    Settings = dictset(config.registry.settings)
    config.include('nefertari.engine')

    config.registry.database_acls = Settings.asbool('database_acls')
    if config.registry.database_acls:
        config.include('nefertari_guards')

    config.include('nefertari')
    config.include('nefertari.view')
    config.include('nefertari.json_httpexceptions')

    # Process nefertari settings
    if Settings.asbool('enable_get_tunneling'):
        config.add_tween('nefertari.tweens.get_tunneling')

    if Settings.asbool('cors.enable'):
        config.add_tween('nefertari.tweens.cors')

    if Settings.asbool('ssl_middleware.enable'):
        config.add_tween('nefertari.tweens.ssl')

    if Settings.asbool('request_timing.enable'):
        config.add_tween('nefertari.tweens.request_timing')

    # Set root factory
    config.root_factory = NefertariRootACL

    # Process auth settings
    root = config.get_root_resource()
    root_auth = getattr(root, 'auth', False)

    log.info('Parsing RAML')
    raml_root = ramlfications.parse(Settings['ramses.raml_schema'])

    log.info('Starting models generation')
    generate_models(config, raml_resources=raml_root.resources)

    if root_auth:
        from .auth import setup_auth_policies, get_authuser_model
        if getattr(config.registry, 'auth_model', None) is None:
            config.registry.auth_model = get_authuser_model()
        setup_auth_policies(config, raml_root)

    config.include('nefertari.elasticsearch')

    log.info('Starting server generation')
    generate_server(raml_root, config)

    log.info('Running nefertari.engine.setup_database')
    from nefertari.engine import setup_database
    setup_database(config)

    from nefertari.elasticsearch import ES
    ES.setup_mappings()

    if root_auth:
        config.include('ramses.auth')

    log.info('Server succesfully generated\n')
示例#34
0
def ramlfications_parser(fpath):
    return ramlfications.parse(fpath)
示例#35
0
def traits():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.traits
示例#36
0
def traits():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.traits
示例#37
0
def sec_schemes():
    raml_file = os.path.join(EXAMPLES, "github.raml")
    config = os.path.join(EXAMPLES, "github-config.ini")
    api = parse(raml_file, config)
    return api.security_schemes