APIDoc utilisation template jinja + lien samples

This commit is contained in:
Iziram 2024-07-24 10:38:56 +02:00
parent 71639606fa
commit 17233fb8c1
2 changed files with 47 additions and 61 deletions

31
app/templates/apidoc.j2 Normal file
View File

@ -0,0 +1,31 @@
#### **`{{doc.nom}}`**
{% if doc.routes %}
{% if doc.routes|length == 1 %}
* **Route:** `{{doc.routes[0]|safe}}`
{% else %}
* **Routes:**
{% for route in doc.routes %}
* `{{route|safe}}`
{% endfor %}
{% endif %}
{% endif %}
* **Méthode:** `{{doc.method}}`
* **Permission:** `{{doc.permission}}`
{% if doc.params %}
* **Paramètres:**
{% for param in doc.params %}
* `{{param.nom|safe}}` : {{param.description|safe}}
{% endfor %}
{% endif %}
{% if doc.description %}
* **Description:** {{doc.description|safe}}
{% endif %}
{% if doc.data %}
* **Data:** {{doc.data|safe}}
{% endif %}
{% if doc.sample %}
* **Exemple de résultat:** [{{doc.sample.nom}}](./samples/sample_{{doc.sample.href}})
{% else %}
{% endif %}

View File

@ -8,6 +8,7 @@ import xml.etree.ElementTree as ET
import re import re
from app.auth.models import Permission from app.auth.models import Permission
from flask import render_template
class COLORS: class COLORS:
@ -870,79 +871,33 @@ def _write_gen_table(table: str, filename: str = "/tmp/api_table.md"):
) )
if __name__ == "__main__":
# Exemple d'utilisation de la classe Token
# Exemple simple de création d'un arbre de Token
# root = Token("api")
# child1 = Token("assiduites", leaf=True)
# child1.func_name = "assiduites_get"
# child2 = Token("count")
# child22 = Token("all")
# child23 = Token(
# "query",
# query={
# "etat": "<string:etat>",
# "moduleimpl_id": "<int:moduleimpl_id>",
# "count": "<int:count>",
# "formsemestre_id": "<int:formsemestre_id>",
# },
# )
# child3 = Token("justificatifs", "POST")
# child3.func_name = "justificatifs_post"
# root.add_child(child1)
# child1.add_child(child2)
# child2.add_child(child22)
# child2.add_child(child23)
# root.add_child(child3)
# group_element = root.to_svg_group()
# generate_svg(group_element, "/tmp/api_map.svg")
dt: dict = parse_doctable_doc(parse_doctable_doc.__doc__)
md: str = "POST"
hf: str = "assiduites-query"
doc: dict = {
"doctable": dt,
"method": md,
"href": hf,
}
print(_gen_table([doc]))
def doc_route(doctable: dict) -> str: def doc_route(doctable: dict) -> str:
"""Generate markdown doc for a route""" """Generate markdown doc for a route"""
doc = f""" jinja_obj: dict = {}
#### **`{doctable['nom']}`** jinja_obj.update(doctable)
jinja_obj["nom"] = doctable["nom"].strip() # on retire les caractères blancs
"""
if doctable.get("routes"):
if len(doctable["routes"]) == 1:
doc += f"""* ** Route :** `{doctable["routes"][0]}`\n"""
else:
doc += "* ** Routes :**\n"
for route in doctable["routes"]:
doc += f""" * `{route}`\n"""
doc += f"""* **Méthode: {doctable['method']}**
* **Permission: `{doctable.get('permission', '')}`**
"""
if doctable.get("params"): if doctable.get("params"):
jinja_obj["params"] = []
for param in doctable["params"]: for param in doctable["params"]:
frags = param.split(":", maxsplit=1) frags = param.split(":", maxsplit=1)
if len(frags) == 2: if len(frags) == 2:
name, descr = frags name, descr = frags
jinja_obj["params"].append(
{"nom": name.strip(), "description": descr.strip()}
)
else: else:
print(f"Warning: {doctable['nom']} : invalid PARAMS {param}") print(f"Warning: {doctable['nom']} : invalid PARAMS {param}")
name, descr = param, ""
doc += f""" * `{name}`: {descr}\n"""
if doctable.get("data"):
doc += f"""* **Data:** {doctable['data']}\n"""
if doctable.get("description"): if doctable.get("description"):
descr = "\n".join(s for s in doctable["description"]) descr = "\n".join(s for s in doctable["description"])
doc += f"""* **Description:** {descr}\n""" jinja_obj["description"] = descr.strip()
return doc
jinja_obj["sample"] = {
"nom": f"{jinja_obj['nom']}.json",
"href": f"{jinja_obj['nom'].replace('_', '-')}.json.md",
}
return render_template("apidoc.j2", doc=jinja_obj)
def gen_api_doc(app, endpoint_start="api."): def gen_api_doc(app, endpoint_start="api."):