#python #json #python-sphinx #restructuredtext
Вопрос:
Допустим, у меня есть JSON / YAML / XML и т.д. животных зоопарка, и я хочу создать некоторую документацию для всех животных в зоопарке. Итак, у меня есть JSON, подобный:
{
"zooName": "C town's Zoo",
"animals": [
"tiger": {
"species":"some_species_name_here",
"weight": 120
},
"bear":{
"species":"some_other_species_name",
"weight": 100
}
]
}
В другом SSG я мог бы сделать что-то вроде
> Bring in a JSON file from /data/myfile.json
> Access some index of that file like [animals][tiger], etc...
> Show that data as a part of the HTML template that is made by, say, `tiger.rst`
Как я мог бы сделать это в Sphinx? Допустим, у меня есть animals.rst
с деревом оглавлений для всех моих животных, а затем такой файл для каждого отдельного.
Tiger
=======================================
Tiger info here.
Species:
[[ Access my json here and show content from jsonfile[animals][tiger][species] ]]
Weight:
[[ Access my json here and show content from jsonfile[animals][tiger][weight] ]]
Комментарии:
1. Будет ли doctest делать то, что вы хотите?
Ответ №1:
Вы могли бы создать расширение Sphinx (например, datatemplates от dhellmann)… но грубый update.py
сценарий предварительной обработки, вероятно, подойдет:
#!/usr/bin/env python
"""To launch: ``$ python update.py > animals.rst`` """
import json
def headline(text, adorn='='):
return text 'n' adorn*len(text)
def main():
header = headline('Animals') 'nnAnimal info here.n'
footer = 'n.. End of documentn'
mask = '* {name} -- {species}'
with open('animals.json', 'r') as infile:
data = json.load(infile)
print(header)
for beast in data['animals']:
print(mask.format(**beast))
print(footer)
if __name__ == '__main__':
main()
Для любого более продвинутого макета перейдите с Python string format
на шаблоны Jinja2.
animals.json
немного отличается от вашего примера:
{
"zooName": "C town's Zoo",
"animals": [
{"name": "tiger", "species": "some_species_name_here", "weight": 120},
{"name": "bear", "species": "some_other_species_name", "weight": 100}
]
}
наконец, добавьте правило в Make-файл Sphinx, которое запускает скрипт при изменении содержимого JSON.