Я унаследовал проект и впервые использую Sphinx. У меня есть файл app.py, в котором есть все конечные точки API, и когда вы создаете документацию, все api.add_resources заключены в функцию.
from resources.recipes import GetRecipes, RecipeList,
from resources.employees import Chefs, Servers, Admin
def make_port():
api = Api(app)
api.add_resource(GetRecipes, '/getrecipes/<:string:recipetype>')
api.add_resource(RecipeList, '/allrecipes/<:string:recipetype>')
api.add_resource(Chefs, '/chefs/<:string:name>')
api.add_resource(Servers, '/servers/<:string:name>')
api.add_resource(Admin, '/admin/<:string:name>')
return app
тогда у меня есть app.rst в папке документов
API Documentation
=================
Summary
-------
.. qrefflask:: app:make_port()
:undoc-static:
API Details
-----------
.. autoflask:: app:make_port()
:endpoints: getRecipes, RecipeList, Chefs, Servers, Admin
:undoc-static
Когда я создаю документ, он создает только одну страницу со всеми конечными точками на ней. Я попробовал просто импортировать папку «ресурсы/сотрудники, ресурсы/рецепты» в файл elements.rst.
.. toctree::
: maxdepth: 4
app
resources/employees
resources/recipes
но получается совсем не так.
Я хотел бы организовать конечные точки вручную, поскольку некоторые конечные точки достаточно похожи, чтобы их можно было сгруппировать вместе.
Я новичок в этом проекте и сфинксе, и мне не удалось разобраться в документации Sphinx.
У меня была совершенно неправильная структура.
Первое, что мне нужно было сделать, это создать папку. Я назвал его API. Я переместил app.rst в папку API, хотя он работает и без него.
Затем я создал нужные страницы в папке api/...
docs
|_api
|_recipes.rst
|_employees.rst
затем я структурировал первую папку так, чтобы в ней были конечные точки, которые мне нужны для этой страницы.
Employee API
=========
.. qrefflask:: app:make_port()
:endpoints: Chefs, Servers, Admin
:undoc-static:
Chefs Endpoints
^^^^^^^^^^^^^^^
.. autoflask:: app:make_port()
:endpoints: Chefs
----
Servers Endpoints
^^^^^^^^^^^^^^^^^^^
.. autoflask:: app:make_port()
:endpoints: servers
----
Admin Employee Endpoints
^^^^^^^^^^^^^^^^^^^^^
.. autoflask:: app:make_port()
:endpoints: admin
----
Поскольку у меня было так много конечных точек, я написал скрипт Python, который брал текстовый файл и создавал для меня первые файлы.
Я создал папку под названием scripts с подкаталогом конечных точек и поместил туда свои txt-файлы.
docs
|_api
|_recipes.rst
|_employees.rst
|_scripts
|_endpoints
|_employees.txt
|_recipes.txt
|_endpoint_generator.py
текстовый файл просто должен иметь конечные точки на разных строках
employees.txt
Chefs
Servers
Admin
Вот endpoint_generator.py, если он кому-нибудь понадобится.
import os
# Directory containing input text files
input_dir = "endpoints"
# Directory to save generated RST files
output_dir = "../api"
# Check if the input directory exists
if not os.path.exists(input_dir):
print(f"Error: Directory '{input_dir}' does not exist.")
exit()
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Get a list of all .txt files in the input directory
input_files = [f for f in os.listdir(input_dir) if f.endswith('.txt')]
# Process each input file
for input_filename in input_files:
# Construct full path to input file
input_filepath = os.path.join(input_dir, input_filename)
# Determine output file name (without extension)
output_filename = os.path.splitext(input_filename)[0]
# Read endpoint names from the input file
endpoints = []
with open(input_filepath, "r") as f:
for line in f:
endpoint = line.strip()
if endpoint: # Skip empty lines
endpoints.append(endpoint.lower())
# Start building the RST content
rst_content = ""
rst_content += f"{output_filename.capitalize()} API\n"
rst_content += " = " * len(output_filename) + "====\n\n"
api_table_list = ",".join(str(x) for x in endpoints)
rst_content += f".. qrefflask:: app:make_port()\n :endpoints: {api_table_list} \n :undoc-static:\n\n"
# Loop through each endpoint
for endpoint in endpoints:
# Add section title for the endpoint
rst_content += f"{endpoint.capitalize()} Endpoints\n"
rst_content += "^" * len(f"{endpoint} Endpoints") + "\n\n"
# Add autoflask directive with the endpoint
rst_content += ".. autoflask:: app:make_port()\n"
rst_content += f" :endpoints: {endpoint}\n\n"
# Add separator after each endpoint except the last one
if endpoint != endpoints[-1]:
rst_content += "----\n\n"
# Construct output file path in the output directory
output_file_path = os.path.join(output_dir, f"{output_filename}.rst")
# Write the generated content to the output file
with open(output_file_path, "w") as f:
f.write(rst_content)
print(f"Endpoints RST file '{output_file_path}' generated successfully!")
print("All endpoints RST files generated in directory 'api/'.")
и, наконец, мне пришлось отредактировать файл index.rst, добавив его на страницы.
.. toctree::
:maxdepth: 4
api/employees
api/recipes
Надеюсь, это поможет кому-то в будущем!