GraphQL Clients 代碼優(yōu)化

小布什微笑地講了一句很沉重的話 :“我曾經(jīng)聽說,人最好趁年輕的時候就去世,當(dāng)然,要越晚越好……”
I once heard it said of man that the idea is to die young as late as possible

如果把這句話,年邁的程序員用Python 語言翻譯一下,就是:“寫代碼,要越年輕越好”
單位來了一位實習(xí)生,學(xué)習(xí)能力超強(qiáng),寫代碼飛快,讓我唏噓不已,想起19歲就名校畢業(yè)的自己。
一個程序員如何帶著尊嚴(yán),幽默和善良而老去( As he aged he taught us how to grow with dignity, humor and kindness)

好,言歸正傳,我們的經(jīng)驗可以代碼更簡潔更好復(fù)用

一、 GraphQL 創(chuàng)建mutation create語句 (動態(tài)表名和字段)

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 批量導(dǎo)入數(shù)據(jù)

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 清空整表數(shù)據(jù)


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)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容