---
title: "심화 튜토리얼: 재사용 가능한 앱을 만드는 법"
version: 5.0
locale: ko
source: https://docs.djangoproject.com/ko/5.0/intro/reusable-apps/
canonical: https://djangodocs.dev/ko/5.0/intro/reusable-apps/
---
# 심화 튜토리얼: 재사용 가능한 앱을 만드는 법

This advanced tutorial begins where [Tutorial 8](/ko/5.0/intro/tutorial08/)
left off. We’ll be turning our web-poll into a standalone Python package
you can reuse in new projects and share with other people.

아직 튜토리얼 1~7장을 완료하지 않았다면, 읽어보고 당신의 예제 프로젝트를 아래에 설명하는 것과 일치시킬 것을 권장합니다.

## 재사용의 중요성

웹 어플리케이션을 설계, 빌드, 테스트, 유지하는 것은 꽤나 큰 일입니다. 수많은 Python과 Django 프로젝트들에는 공통적인 문제가 있습니다. 만약 우리가 이러한 반복적인 작업들 중에서 몇몇을 구해낼 수 있다면 정말 멋지지 않을까요?

재사용성은 Python의 핵심 가치입니다. [Python Package Index(PyPI)](https://pypi.org/)에는 여러분의 Python 프로그램에 사용할 수 있는 방대한 패키지가 있습니다. 여러분의 프로젝트에 활용할 수 있는 재사용 가능 앱을 [Django Packages](https://djangopackages.org)에서 확인하세요. Django는 그 자체로서 Python 패키지이기도 합니다. 이는 기존 Python 패키지 또는 Django 앱을 가져다가 당신의 웹 프로젝트에 이용할 수 있음을 의미합니다. 프로젝트만의 고유한 부분을 작성하기만 하면 됩니다.

이제 우리가 작업했던 것과 같은 설문조사 앱이 필요하여 새로운 프로젝트를 시작했다고 가정해봅시다. 어떻게 이 앱을 재사용할 수 있게 만들 수 있을까요? 운 좋게도, 여러분은 이미 방법을 알고 있습니다. [튜토리얼 1장](/ko/5.0/intro/tutorial01/) 에서, 우리는 `include` 를 이용하여 프로젝트 수준의 URLconf에서 설문조사를 분리하는 방법을 배웠습니다. 이 튜토리얼에서는, 새로운 프로젝트에서 사용하기 쉬운 앱을 만들고 이 앱을 설치하고 사용할 다른 사람들을 위해 게시할 준비를 하기 위한 추가적인 작업을 진행할 것입니다.

> **패키지? 앱?**
>
> Python [package](https://docs.python.org/3/glossary.html#term-package)는 재사용을 쉽게 하기 위해 연관된 Python 코드를 묶어 놓은 것입니다. 패키지에는 Python 코드가 들어있는 하나 이상의 파일(“모듈”이라고도 함)들이 포함되어  있습니다.
>
> `import foo.bar` 나 `from foo import bar` 로 패키지를 import 할 수 있습니다. 디렉토리(`polls`와 같은)는 패키지를 형성하기 위해, 특별한 파일 `__init__.py`를 포함하고 있습니다, 그 파일이 빈파일일 경우에도 포함하고 있습니다.
>
> Django *어플리케이션*은 Django 프로젝트에 사용하기 위한 파이썬 패키지일 뿐입니다. 애플리케이션은 `models`, `tests`, `urls`, `views` 서브모듈들을 포함하고 있는 공통적인 Django 규칙을 이용할 수 있습니다.
>
> 여기서는 다른 사람들이 Python 패키지를 쉽게 설치할 수 있게 만드는 과정을 이르는 데 *패키징*이라는 용어를 사용할 것입니다. 약간 혼동될 수도 있습니다.

## 프로젝트와 재사용가능한 앱

이전 튜토리얼을 마치면, 프로젝트는 다음과 같을 것입니다.

```text
mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        asgi.py
        wsgi.py
    polls/
        __init__.py
        admin.py
        apps.py
        migrations/
            __init__.py
            0001_initial.py
        models.py
        static/
            polls/
                images/
                    background.png
                style.css
        templates/
            polls/
                detail.html
                index.html
                results.html
        tests.py
        urls.py
        views.py
    templates/
        admin/
            base_site.html
```

여러분은 [튜토리얼 7](/ko/5.0/intro/tutorial07/) 에서 `mysite/templates`  나 [Tutorial 3](/ko/5.0/intro/tutorial03/) 에서 `polls/templates`  를 생성하였습니다. 이제 프로젝트와 어플리케이션으로 분리한 이유가 명확합니다. `polls` 어플리케이션의 부분들은 `polls`에 모두 있습니다.  It makes the application self-contained and easier to drop into a new project.

`polls` 디렉토리가 이제 새 Django 프로젝트로 복사되었고, 바로 재사용할 수 있습니다. 그래도 게시 할 준비가 되지 않았습니다. 이를 위해, 다른 사람들이 쉽게 설치할 수 있도록 앱을 패키지화해야합니다.

## 필수 구성 요소 설치

Python  패키징의 현재 상태는 다양한 도구들로 인해 약간 혼란스럽습니다. 이 튜토리얼에서는 패키지를 빌드하는데 [setuptools\`을 사용할 것입니다. 권장 패키징 도구(\`\`distribute\`](https://pypi.org/project/setuptools`을%20사용할%20것입니다.%20권장%20패키징%20도구(``distribute`/) 포크와 병합된)입니다. 설치하고 삭제하기 위해 [pip\`을 사용할 것입니다. 당신은 이제 두 패키지를 설치해야합니다. 도움이 필요하면 :ref:](https://pypi.org/project/pip`을%20사용할%20것입니다.%20당신은%20이제%20두%20패키지를%20설치해야합니다.%20도움이%20필요하면%20:ref:/) pip로 Django 설치하는 법 \<installing-official-release\>\`.을 참조할 수 있습니다. 같은 방법으로  setuptools\`\`도 설치할 수 있습니다.

## 앱 패키징하기

파이썬 *패키징* 은 쉽게 설치하고 사용할 수 있는 특별한 형식으로 앱을 준비하는 것을 의미합니다. 장고 자체도 이와 같이 패키지화되어 있습니다. 설문조사처럼 작은 앱은 이 과정이 어렵지 않습니다.

1. First, create a parent directory for the package, outside of your Django
   project. Call this directory `django-polls`.

   > **앱 이름 선택**
   >
   > When choosing a name for your package, check PyPI to avoid naming
   > conflicts with existing packages. We recommend using a `django-`
   > prefix for package names, to identify your package as specific to
   > Django, and a corresponding `django_` prefix for your module name. For
   > example, the `django-ratelimit` package contains the
   > `django_ratelimit` module.
   >
   > 어플리케이션 라벨(즉, 애플리케이션 패키지 경로의 마지막 부분)은 [`INSTALLED_APPS`](/ko/5.0/ref/settings/#std-setting-INSTALLED_APPS)에서 *유일한* 것이어야 합니다. `auth`, `admin`, `messages` 같은 Django [contrib 패키지](/ko/5.0/ref/contrib/)와 동일한 라벨을 사용하지 마세요.
2. Move the `polls` directory into `django-polls` directory, and rename it
   to `django_polls`.
3. Edit `django_polls/apps.py` so that [`name`](/ko/5.0/ref/applications/#django.apps.AppConfig.name) refers to the
   new module name and add [`label`](/ko/5.0/ref/applications/#django.apps.AppConfig.label) to give a short name for
   the app:

   *`django-polls/django_polls/apps.py`*

   ```python
   from django.apps import AppConfig

   class PollsConfig(AppConfig):
       default_auto_field = "django.db.models.BigAutoField"
       name = "django_polls"
       label = "polls"
   ```
4. 다음과 같은 내용으로 `django-polls/README.rst`를 생성합니다:

   *`django-polls/README.rst`*

   ```rst
   ============
   django-polls
   ============

   django-polls is a Django app to conduct web-based polls. For each
   question, visitors can choose between a fixed number of answers.

   Detailed documentation is in the "docs" directory.

   Quick start
   -----------

   1. Add "polls" to your INSTALLED_APPS setting like this::

       INSTALLED_APPS = [
           ...,
           "django_polls",
       ]

   2. Include the polls URLconf in your project urls.py like this::

       path("polls/", include("django_polls.urls")),

   3. Run ``python manage.py migrate`` to create the models.

   4. Start the development server and visit the admin to create a poll.

   5. Visit the ``/polls/`` URL to participate in the poll.
   ```
5. `django-polls/LICENSE` 파일을 생성합니다. 라이선스 선택은 이 튜토리얼의 범위를 벗어나므로, 라이선스 없이 공개된 코드는 *쓸모없음* 을 의미한다는 것만 말해두겠습니다.  Django와 많은 Django 호환 앱들이 BSD 라이센스로 배포되고 있습니다; 그러나 자신의 라이센스를 자유롭게 선택할 수 있습니다. 라이선스 선택이 누군가 여러분의 코드를 사용하는데 영향이 미칠수 있다는 사실은 알고 있어야합니다.
6. 이제 앱을 빌드하고 설치하는 방법을 자세히 설명하는 `pyproject.toml`, `setup.cfg`, `setup.py` 파일을 만들 것입니다. 이 파일에 대한 상세 설명은 해당 튜토리얼의 범위에서 벗어나지만, [setuptools documentation](https://setuptools.readthedocs.io/en/latest/) 에 잘 설명되어 있습니다. 다음 내용을 참고하여 `django-polls/pyproject.toml`, `django-polls/setup.cfg`, `django-polls/setup.py` 파일을 만드세요.

   *`django-polls/pyproject.toml`*

   ```toml
   [build-system]
   requires = ['setuptools>=40.8.0']
   build-backend = 'setuptools.build_meta'
   ```

   *`django-polls/setup.cfg`*

   ```ini
   [metadata]
   name = django-polls
   version = 0.1
   description = A Django app to conduct web-based polls.
   long_description = file: README.rst
   url = https://www.example.com/
   author = Your Name
   author_email = yourname@example.com
   license = BSD-3-Clause  # Example license
   classifiers =
       Environment :: Web Environment
       Framework :: Django
       Framework :: Django :: X.Y  # Replace "X.Y" as appropriate
       Intended Audience :: Developers
       License :: OSI Approved :: BSD License
       Operating System :: OS Independent
       Programming Language :: Python
       Programming Language :: Python :: 3
       Programming Language :: Python :: 3 :: Only
       Programming Language :: Python :: 3.10
       Programming Language :: Python :: 3.11
       Programming Language :: Python :: 3.12
       Topic :: Internet :: WWW/HTTP
       Topic :: Internet :: WWW/HTTP :: Dynamic Content

   [options]
   include_package_data = true
   packages = find:
   python_requires = >=3.10
   install_requires =
       Django >= X.Y  # Replace "X.Y" as appropriate
   ```

   *`django-polls/setup.py`*

   ```python
   from setuptools import setup

   setup()
   ```
7. Only Python modules and packages are included in the package by default. To
   include additional files, we’ll need to create a `MANIFEST.in` file. The
   `setuptools` docs referred to in the previous step discuss this file in
   more detail. To include the templates, the `README.rst` and our
   `LICENSE` file, create a file `django-polls/MANIFEST.in` with the
   following contents:

   *`django-polls/MANIFEST.in`*

   ```text
   include LICENSE
   include README.rst
   recursive-include django_polls/static *
   recursive-include django_polls/templates *
   ```
8. 선택사항이지만 앱에 세부 문서를 포함시키는 것을 권장합니다. 나중에 문서를 위해 빈 디렉토리 `django-polls/docs` 를 생성하십시오. django-polls/MANIFEST.in\`\`에 다음 한줄을 추가하십시오.

   ```text
   recursive-include docs *
   ```

   파일을 추가하지 않으면 `docs` 디렉토리는 패키지에 포함되지 않을 것입니다. 많은 Django 앱들이 [readthedocs.org](https://readthedocs.org) 같은 사이트들을 통해 온라인 문서를 제공합니다.
9. Try building your package by running `python setup.py sdist` inside
   `django-polls`. This creates a directory called `dist` and builds your
   new package, `django-polls-0.1.tar.gz`.

패키징에 관한 더 자세한 정보는 파이썬의 프로젝트 패키징 및 배포에 관한 튜토리얼 \<<https://packaging.python.org/distributing/>\>\`\_을 참조하십시오.

## 여러분의 패키지 사용하기

우리가 `polls` 디렉토리를 프로젝트 바깥으로 이동했으므로, 작동하지 않을것입니다. 우리의 새 `django-polls` 패키지를 설치하여 이 문제를 해결할 것입니다.

> **유저 라이브러리 설치하기**
>
> 다음 단계는 `django-polls` 를 사용자 라이브러리로 설치합니다. 사용자 단위 설치는  관리자권한 접근이 안되는 시스템 뿐만아니라 시스템 서비스나 다른 사용자들의 영향으로부터 패키지를 보호하는 것 같은 이점이 많습니다.
>
> 사용자별 설치는 여전히 해당 사용자로 실행되는 시스템 도구의 동작에 영향을 미칠 수 있으므로 가상 환경을 사용하는 것이 더 강력한 해결 방법입니다(아래 참조).

1. 패키지를 설치하기 위해 pip를 사용하세요 (당신은 이미 [설치하였습니다.](#installing-reusable-apps-prerequisites) 그렇죠?),

   ```shell
   python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
   ```
2. Update `mysite/settings.py` to point to the new module name:

   ```
   INSTALLED_APPS = [
       "django_polls.apps.PollsConfig",
       ...,
   ]
   ```
3. Update `mysite/urls.py` to point to the new module name:

   ```
   urlpatterns = [
       path("polls/", include("django_polls.urls")),
       ...,
   ]
   ```
4. Run the development server to confirm the project continues to work.

## 앱 퍼블리싱

우리는 `django-polls` 를 패키지화하고 테스트했기에, 세계와 공유할 준비가 되었습니다. 단순한 예제가 아니면, 여러분은 이제 아래와 같은 것들을 할 수 있습니다:

- 친구에게 패키지를 이메일로 보내기
- 웹사이트에 패키지 업로드
- [the Python Package Index (PyPI)](#the-python-package-index-pypi)와 같은 공용 저장소에 패키지를 게시하십시오. [packaging.python.org](https://packaging.python.org)에는 앱 퍼플리싱을 위한  [좋은 튜토리얼](https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives)이 있습니다.

## 파이썬 패키지를 가상 환경으로 설치하기

Earlier, we installed `django-polls` as a user library. This has some
disadvantages:

- 사용자 라이브러리를 수정하면 시스템의 다른 파이썬 소프트웨어에 영향을 미칠 수 있습니다.
- 이 패키지의 여러 버전 (또는 이름이 같은 다른 버전)을 실행할 수 없습니다.

일반적으로 이러한 상황들은 여러 Django 프로젝트를 유지보수할 때만 발생합니다. 이러한 경우, 최선의 해결책은 :doc:venv \<python:tutorial/venv\>\`를 사용하는 것입니다. 이 도구를 사용하면 각각 고유한 라이브러리 및 패키지 네임스페이스 복사본이 있는 다수의 분리된 Python 환경을 유지할 수 있습니다.
