小布什微笑地講了一句很沉重的話 :“我曾經(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)