示例#1
0
def render_type_resolver(disambiguations, typename):
    code = f"""
    @TypeResolver('{typename}')
    def resolve_type(result, context, info, abstract_type):
        x = result
    """
    yield indent_to('', code) + '    '
    for (i, typename, expr) in zip_pluck(disambiguations,
                                         ['type_name', 'expression'],
                                         enumerate=True):
        code = f"""
        {'if' if i == 0 else 'elif'} ({expr}):
            return '{typename}'
        """
        yield indent_to('    ', code)
示例#2
0
 def object(self, children):
     types = "\n".join([x for x, _, _ in children]) + "\n"
     arguments = ",\n".join([x for _, x, _ in children])
     initializers = ",\n".join([x for _, _, x in children])
     template = indent_to(
         "",
         """
         class $key(dictlike):
             $annotation
             ${{indent_to('    ', types)}}
             
             def __init__(
                 self,
                 *, 
                 ${{indent_to('        ', arguments)}}, 
                 **kwargs
             ):
                 super().__init__(
                     ${{indent_to('            ', initializers)}},
                     **kwargs
                 )
         """,
     )
     return populate_string(
         template,
         dict(
             types=types,
             arguments=arguments,
             initializers=initializers,
             indent_to=indent_to,
         ),
     )
示例#3
0
def parse(string):
    string = "\n".join([l for l in string.split("\n") if l.strip()])
    string = indent_to('', string)
    logger.debug(string)
    t = parser.parse(string + "\n")
    logger.debug(t.pretty())
    return t
示例#4
0
def get_types_schema(config, here='./'):
    if "schema_path" in config:
        path = here + config["schema_path"]
        with open(path) as f:
            return f.read()
    if config.get("schema"):
        return indent_to('', config.get("schema"))
    if config.get("schema_url"):
        return download_file(config.get("schema_url"))
示例#5
0
def repr_guards_checks(guards, indentation):
    for expr, fields in zip_pluck(guards, ['expression', 'excluded']):
        code = f"""
        if not ({expr}):
            raise Exception({json.dumps('guard `' + str(expr) + '` not satisfied')})
        else:
            fields += {fields}
        """
        yield indent_to(indentation, code)
示例#6
0
def repr_disambiguations(disambiguations, indentation):
    for (i, typename, expr) in zip_pluck(disambiguations,
                                         ['type_name', 'expression'],
                                         enumerate=True):
        code = f"""
        {'if' if i == 0 else 'elif'} ({expr}):
            x['_typename'] = '{typename}'
        """
        yield indent_to(indentation, code)
示例#7
0
def repr_eval_dict(obj, indentation=''):
    dumped = json.dumps(obj, indent=4)
    # dumped = populate_string(dumped, do_eval=False)
    dumped = dumped.replace(': false', ': False')
    dumped = dumped.replace(': true', ': True')
    dumped = dumped.replace(': null', ': None')
    dumped = dumped.replace('"' + EXPR_START, '').replace(EXPR_END + '"', '')
    dumped = bytes(dumped, 'utf-8').decode('unicode_escape')
    dumped = indent_to(indentation, dumped)
    return dumped.lstrip()
示例#8
0
def repr_node_filterer(guards_after):
    code = f'''
    def filter_nodes_by_guard(nodes, fields, jwt):
        for x in nodes:
            try:
                {repr_guards_checks(guards_after, '                ')}
                yield omit(x or dict(), fields)
            except Exception:
                pass
    '''
    return indent_to('', code)
示例#9
0
def get_types_schema(config, here='./'):
    if "schema_path" in config:
        path = here + config["schema_path"]
        with open(path) as f:
            return f.read()
    if config.get("schema"):
        return indent_to('', config.get("schema"))
    if config.get("schema_url"):
        r = requests.get(config.get("schema_url"), stream=True)
        skema = ""
        while 1:
            buf = r.raw.read(16 * 1024)
            if not buf:
                break
            skema += buf.decode()
        return skema
示例#10
0
def repr_many_disambiguations(disambiguations, indentation):
    code = f'''
    for x in data['nodes']:
        {repr_disambiguations(disambiguations, '        ')}
    '''
    return indent_to(indentation, code)