美文网首页
GraphQL Clients 代码优化

GraphQL Clients 代码优化

作者: 林慕空 | 来源:发表于2018-12-14 12:09 被阅读0次

小布什微笑地讲了一句很沉重的话 :“我曾经听说,人最好趁年轻的时候就去世,当然,要越晚越好……”
I once heard it said of man that the idea is to die young as late as possible

如果把这句话,年迈的程序员用Python 语言翻译一下,就是:“写代码,要越年轻越好”
单位来了一位实习生,学习能力超强,写代码飞快,让我唏嘘不已,想起19岁就名校毕业的自己。
一个程序员如何带着尊严,幽默和善良而老去( As he aged he taught us how to grow with dignity, humor and kindness)

好,言归正传,我们的经验可以代码更简洁更好复用

一、 GraphQL 创建mutation create语句 (动态表名和字段)

def mutation_create(table_name, str_sql, str_status):
    table_name_camelCase = table_name[0].lower() + table_name[1:]
    strmutation = """
        mutation{
          create%s(%s){
            status
            %s{
                %s
            }
          }
        }
        """ % (table_name, str_sql, table_name_camelCase, str_status)

    return strmutation

二、 GraphQL 批量导入数据

def import_from_api(api_url, table_name, *args):
    with urllib.request.urlopen(api_url) as url:
        data = json.loads(url.read().decode())
        for obj in data:
            str_sql = ""
            str_status = ""
            for arg in args:
                # key name must be camelCased
                argCamel = camel(arg)
                str_sql += "%s:\"%s\"," % (argCamel, obj[arg])
                str_status += argCamel + '\n'
            # create graphql sql
            strmutation = mutation_create(table_name, str_sql, str_status)
            # execute graphql
            mutation_result = mutation_graphql(strmutation)

三、 GraphQL 清空整表数据


def truncate_table(table_name):
    query_str = "all%ss" % table_name
    strquery = """
    {
      %s{
        id

      }
    }
            """ % query_str
    query_result = query_graphql(strquery)
    for data in query_result["data"][query_str]:
        data_id = int(data["id"])
        strmutation = mutation_delete_table(table_name, data_id)
        mutation_result = mutation_graphql(strmutation)

相关文章

网友评论

      本文标题:GraphQL Clients 代码优化

      本文链接:https://www.haomeiwen.com/subject/efgwhqtx.html