我很喜歡nik_m的回答,我寫了一些代碼來從Django shell內部生成模板結構。我希望強制執行一些一致性,因爲我一遍又一遍地創建這些文件。我將代碼放在這裏以防其他人發現它有用。
import os
from django.conf import settings
def schema_setup(app_name):
"""
Sets up a default schema file structure.
"""
SCHEMA_DIRECTORY_NAME = 'schema'
app_directory = os.path.join(settings.PROJECT_DIR, app_name)
if not os.path.exists(app_directory):
raise Exception("Can't find app directory {}".format(app_directory))
schema_directory = os.path.join(app_directory, SCHEMA_DIRECTORY_NAME)
if os.path.exists(schema_directory):
raise Exception("Schema directory {} already exists.".format(schema_directory))
os.makedirs(schema_directory)
mutation_class = "{}Mutation".format(app_name.title())
query_class = "{}Query".format(app_name.title())
init_txt = "from .mutations import {}\nfrom .queries import {}\n".format(mutation_class, query_class)
fields_txt = "# Insert common fields here.\nimport graphene\n"
inputs_txt = "# Insert graphene.InputObjectType classes.\nimport graphene\n"
mutations_txt = "# Insert graphql mutations here.\nimport graphene\n\nclass {}(graphene.AbstractType):\n pass\n".format(mutation_class)
queries_txt = "# Insert graphql queries here.\nimport graphene\n\nclass {}(graphene.AbstractType):\n pass\n".format(query_class)
types_txt = "# Insert DjangoObjectType classes here.\nimport graphene\nfrom graphene_django.types import DjangoObjectType\n"
for fname, file_text in [("__init__.py", init_txt),
("fields.py", fields_txt),
("inputs.py", inputs_txt),
("mutations.py", mutations_txt),
("queries.py", queries_txt),
("types.py", types_txt),
]:
with open(os.path.join(schema_directory, fname), "w") as output_file:
output_file.write(file_text)
print("Created {}".format(fname))
從Django的外殼內,運行像schema_setup("my_app")
注:
- 這裏假設你在你的設置中設置
PROJECT_DIR
像PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
- 在您的頂層架構,進口喜歡
from my_app.schema import MyAppQuery, MyAppMutation
- 我在「查詢」與「查詢」和「突變」之間來回回顧「突變」 - 截至此刻,石墨烯文件並不一致
如果您覺得下面的答案是正確的,請接受它。這在StackOverflow中是一個很好的練習:) –