개발 이슈,해결법

[sphinx] 스핑크스를 사용해 django 문서화

난쏘공돌이 2022. 6. 16. 18:11

스핑크스는 파이썬 문서화 패키지이다. 

상당히 오래되었고, 블로그 글만 보더라도 많이 쓰는 것처럼 보이지만.. Django 기준으로 작성된 글은 찾기 어려웠고, 작성된 글도 간단하게 되어있어 사용법을 파악하기 힘들었다.

이번 글에서는 django 로 개발된 프로젝트를 한번 문서화 하는 방법을 소개하겠다.

 

1. 먼저 설치는 다음과 같다.

$ pip install sphinx 

(python version 이 3.x 라면 pip3) conda는 conda install 써도 무방

 

설치가 되었다면 프로젝트의 부모 폴더에서

2. docs/ 라는 이름의 폴더를 만들어주자. (mkdir docs)

왜 하는가? 이후 명령을 걍 쳐버리면 부모폴더에 이것저것 생기게 된다. 
상당히 지저분해지기 때문에 폴더 하나를 만들어서 넣어두는것.

이름은 상관없다. 본인이 필요한 이름으로 할 것. 

 

3. 명령어 실행

먼저 docs 폴더로 들어가서,

sphinx-quickstart

를 실행해 주자.

요런 질문이 나올텐데 필자는 n 했을때 더 이해하기 힘들었다.

먼저 이 글을 통해 y를 눌러 개념을 파악하고 진행하길 추천한다.

이후 답변들은 적절하게 눌러주면 되겠다. 이하 답변들은 접은글로 적어두겠다.

 

더보기

Welcome to the Sphinx 5.0.1 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

The project name will occur in several places in the built documentation.
> Project name: rest
> Author name(s): dongd
> Project release []: 1.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.
> Project language [en]: ko

Creating file /mnt/c/Users/ccom1384/restproject/docs/source/conf.py.
Creating file /mnt/c/Users/ccom1384/restproject/docs/source/index.rst.
Creating file /mnt/c/Users/ccom1384/restproject/docs/Makefile.
Creating file /mnt/c/Users/ccom1384/restproject/docs/make.bat.
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

이 시점에서 docs 이하 폴더구조는 다음과 같다.

여기서 makefile, make.bat은 이후 html 파일을 생성할때 필요하다. 리눅스와 윈도우용 각각 make를 위한 파일이다.

build는 완성된 파일들이 들어갈 폴더.

source 의 경우에는 rst파일들이 들어가는데 지금은 스핑크스에서 문서구조를 정하는 파일이라고 생각하자.

여기서 make html을 치면 source에 있는 rst를 읽어서 build에 만들어주는 거다.

한번 쳐서 잘 되는지 확인 해보기 바란다.

이래 생긴게 나온다

4.  conf.py 수정

이제 기본적인 명령어 실행은 끝났으니,  django 기준으로 스핑크스가 코드를 읽고 문서를 생성 할 수 있도록 수정해 주어야 한다.

먼저 위의 사진을 아래사진과 같이 바꾸어 주도록 하자.

이렇게 되어있는 부분을

아래사진처럼

코드는 첨부할게요.

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
import django
sys.path.insert(0, os.path.abspath('../..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'
django.setup()

여기서 잠시 코드설명을 들어가자면 sys.path~~ 이 코드는 본인의 장고 프로젝트의 최상위 폴더를 잡아주면 됩니다.

제 경우에 현재 conf.py 파일이 있는 경로가 (메인프로젝트폴더)/docs/source 폴더거든요.
그러니 ../..를 써서 두단계를 올라가야 메인 프로젝트가 나오는 거죠.

다음 코드도 크게 다를 것은 없이 

os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings'

에선 본인의 settings.py의 경로를 최상위 폴더 기준으로 잡아주시면 됩니다.

제 경우에는 메인 프로젝트 폴더/ config/ settings.py 가 잡혀있기 때문에 저렇게 작성해 주었구요. 
settings.py를 분리하셨다면 저부분은 달라질수 있겠죠

두번째는 general config 부분을 다음 사진과 같이 바꿔주세요

extensions = ['sphinx.ext.viewcode','sphinx.ext.autodoc']

extenstions 부분이 추가 되었는데, 이 부분은 이후 앱별로 자동으로 rst 생성 명령을 사용할때에 필요하다.

 

5. sphinx -apidoc 사용하기

sphinx-apidoc은 자동으로 패키지를읽어 sphinx 문서화 파일을 만들어 주는 도구입니다.

https://www.sphinx-doc.org/en/master/man/sphinx-apidoc.html

 

sphinx-apidoc — Sphinx documentation

sphinx-apidoc is a tool for automatic generation of Sphinx sources that, using the autodoc extension, document a whole package in the style of other automatic API documentation tools. MODULE_PATH is the path to a Python package to document, and OUTPUT_PATH

www.sphinx-doc.org

sphinx-apidoc -f -o docs/source user

해당 명령은 user라는 앱을 읽고 docs/source 이하에 sphinx 소스파일로 저장해라.  라는 뜻입니다.

이 명령은 반드시 앱을 읽을 수 있는 프로젝트 최상위 폴더에서 실행되어야 하며, 이 명령이 잘 실행되고 나면 
다시금 docs 폴더로 들어가 make html을 진행해 주시면 됩니다.

정리하면 다음과 같습니다

sphinx-apidoc -f -o docs/source [앱이름]
cd docs/
make html

잘 진행이 되었다면 docs/build 이하에  있는 index.html 파일을 확인해 보시기 바랍니다.

여기서 색인을 한번 눌러보세요.

이런식으로 스핑크스가 자동으로 앱을 읽어 문서화 해주는 모습을 보실 수 있습니다.

 

6. 마지막 코드에 주석달기

이런느낌으로 달아보겠습니다.

이후 다시 아까 프로젝트 메인폴더로 돌아가서

sphinx-api~~ 명령을 실행해 주고, 이번엔 docs 폴더에 가서 source 폴더에 있는 index.rst 파일을 수정해 주겠습니다.

이렇게요. 그런다음 다시 docs 폴더로 와서 make html을 돌려주겠습니다.

그럼 이젠 index.html이 이렇게 바뀌었고, user package를 누른다음 맨 아래로 내려보면..

우리가 방금 추가한 코드주석이 나오는 모습을 보실 수 있습니다.

 

일단 여기서 이 글은 마무리를 하려고합니다.

RST문법 관련해서도 설명을 할까 했는데, 너무 길어질 것 같기도하고 제 지식이 정확하지도 못해 튜토리얼식으로만 이런글을 작성하는점 양해 부탁드립니다.

문서화를 편하게하자고 쓰는건데 오히려 이걸 배우기위해 힘들어하시는 분들이 좀더 편해지시길 바라겠습니다.

RST 관련해서는 어느 한분의 블로그내용이 괜찮은것 같아 추천드리려 합니다.

https://soma0sd.tistory.com/130

 

Python 패키지 개발일지 05: 주석을 이용한 문서화

특정한 위치에 있는 블록 주석은 요소의 __doc__ 속성이 되어 IntelliSense나 Sphinx등이 자동으로 설명을 붙일 수 있도록 해줍니다. 개발자가 아닌 사용자를 위한 이 주석은 별도로 docstring이라고 부르

soma0sd.tistory.com



출처 : https://www.freecodecamp.org/news/sphinx-for-django-documentation-2454e924b3bc/

 

How to document your Django project using the Sphinx tool

I recently visited a company where I had a nice talk with one of its employees. We talked about technology and programming. Then we touched the subject of project documentation. Specifically how React does it automatically but Django doesn’t. That made m

www.freecodecamp.org

https://hooni-playground.com/1101/