심화 튜토리얼: 재사용 가능한 앱을 만드는 법Link to this heading
This advanced tutorial begins where Tutorial 8 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장을 완료하지 않았다면, 읽어보고 당신의 예제 프로젝트를 아래에 설명하는 것과 일치시킬 것을 권장합니다.
재사용의 중요성Link to this heading
웹 어플리케이션을 설계, 빌드, 테스트, 유지하는 것은 꽤나 큰 일입니다. 수많은 Python과 Django 프로젝트들에는 공통적인 문제가 있습니다. 만약 우리가 이러한 반복적인 작업들 중에서 몇몇을 구해낼 수 있다면 정말 멋지지 않을까요?
재사용성은 Python의 핵심 가치입니다. Python Package Index(PyPI)에는 여러분의 Python 프로그램에 사용할 수 있는 방대한 패키지가 있습니다. 여러분의 프로젝트에 활용할 수 있는 재사용 가능 앱을 Django Packages에서 확인하세요. Django는 그 자체로서 Python 패키지이기도 합니다. 이는 기존 Python 패키지 또는 Django 앱을 가져다가 당신의 웹 프로젝트에 이용할 수 있음을 의미합니다. 프로젝트만의 고유한 부분을 작성하기만 하면 됩니다.
이제 우리가 작업했던 것과 같은 설문조사 앱이 필요하여 새로운 프로젝트를 시작했다고 가정해봅시다. 어떻게 이 앱을 재사용할 수 있게 만들 수 있을까요? 운 좋게도, 여러분은 이미 방법을 알고 있습니다. 튜토리얼 1장 에서, 우리는 include 를 이용하여 프로젝트 수준의 URLconf에서 설문조사를 분리하는 방법을 배웠습니다. 이 튜토리얼에서는, 새로운 프로젝트에서 사용하기 쉬운 앱을 만들고 이 앱을 설치하고 사용할 다른 사람들을 위해 게시할 준비를 하기 위한 추가적인 작업을 진행할 것입니다.
프로젝트와 재사용가능한 앱Link to this heading
이전 튜토리얼을 마치면, 프로젝트는 다음과 같을 것입니다.
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.gif
style.css
templates/
polls/
detail.html
index.html
results.html
tests.py
urls.py
views.py
templates/
admin/
base_site.html
여러분은 튜토리얼 7 에서 mysite/templates 나 Tutorial 3 에서 polls/templates 를 생성하였습니다. 이제 프로젝트와 어플리케이션으로 분리한 이유가 명확합니다. polls 어플리케이션의 부분들은 polls에 모두 있습니다. It makes the application self-contained and easier to drop into a new project.
polls 디렉토리가 이제 새 Django 프로젝트로 복사되었고, 바로 재사용할 수 있습니다. 그래도 게시 할 준비가 되지 않았습니다. 이를 위해, 다른 사람들이 쉽게 설치할 수 있도록 앱을 패키지화해야합니다.
필수 구성 요소 설치Link to this heading
Python 패키징의 현재 상태는 다양한 도구들로 인해 약간 혼란스럽습니다. 이 튜토리얼에서는 패키지를 빌드하는데 setuptools`을 사용할 것입니다. 권장 패키징 도구(``distribute` 포크와 병합된)입니다. 설치하고 삭제하기 위해 pip`을 사용할 것입니다. 당신은 이제 두 패키지를 설치해야합니다. 도움이 필요하면 :ref: pip로 Django 설치하는 법 <installing-official-release>`.을 참조할 수 있습니다. 같은 방법으로 ``setuptools``도 설치할 수 있습니다.
앱 패키징하기Link to this heading
파이썬 패키징 은 쉽게 설치하고 사용할 수 있는 특별한 형식으로 앱을 준비하는 것을 의미합니다. 장고 자체도 이와 같이 패키지화되어 있습니다. 설문조사처럼 작은 앱은 이 과정이 어렵지 않습니다.
먼저, Django 프로젝트 외부에
polls의 상위 디렉토리를 만듭니다. 이 디렉토리를django-polls라 부르겠습니다.django-polls디렉토리의polls디렉토리로 이동하세요.다음과 같은 내용으로
django-polls/README.rst를 생성합니다:django-polls/README.rst===== Polls ===== 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 = [ ..., "polls", ] 2. Include the polls URLconf in your project urls.py like this:: path("polls/", include("polls.urls")), 3. Run ``python manage.py migrate`` to create the polls models. 4. Start the development server and visit http://127.0.0.1:8000/admin/ to create a poll (you'll need the Admin app enabled). 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.django-polls/LICENSE파일을 생성합니다. 라이선스 선택은 이 튜토리얼의 범위를 벗어나므로, 라이선스 없이 공개된 코드는 쓸모없음 을 의미한다는 것만 말해두겠습니다. Django와 많은 Django 호환 앱들이 BSD 라이센스로 배포되고 있습니다; 그러나 자신의 라이센스를 자유롭게 선택할 수 있습니다. 라이선스 선택이 누군가 여러분의 코드를 사용하는데 영향이 미칠수 있다는 사실은 알고 있어야합니다.Next we’ll create the
pyproject.tomlfile which details how to build and install the app. A full explanation of this file is beyond the scope of this tutorial, but the Python Packaging User Guide has a good explanation. Create thedjango-polls/pyproject.tomlfile with the following contents:django-polls/pyproject.toml[build-system] requires = ["setuptools>=69.3"] build-backend = "setuptools.build_meta" [project] name = "django-polls" version = "0.1" dependencies = [ "django>=X.Y", # Replace "X.Y" as appropriate ] description = "A Django app to conduct web-based polls." readme = "README.rst" requires-python = ">= 3.8" authors = [ {name = "Your Name", email = "yourname@example.com"}, ] 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.8", "Programming Language :: Python :: 3.9", "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", ] [project.urls] Homepage = "https://www.example.com/"Many common files and Python modules and packages are included in the package by default. To include additional files, we’ll need to create a
MANIFEST.infile. To include the templates and static files, create a filedjango-polls/MANIFEST.inwith the following contents:django-polls/MANIFEST.inrecursive-include polls/static * recursive-include polls/templates *It’s optional, but recommended, to include detailed documentation with your app. Create an empty directory
django-polls/docsfor future documentation.파일을 추가하지 않으면
docs디렉토리는 패키지에 포함되지 않을 것입니다. 많은 Django 앱들이 readthedocs.org 같은 사이트들을 통해 온라인 문서를 제공합니다.Check that the build package is installed (
python -m pip install build) and try building your package by runningpython -m buildinsidedjango-polls. This creates a directory calleddistand builds your new package into source and binary formats,django_polls-0.1.tar.gzanddjango_polls-0.1-py3-none-any.whl.
패키징에 관한 더 자세한 정보는 파이썬의 `프로젝트 패키징 및 배포에 관한 튜토리얼 <https://packaging.python.org/distributing/>`_을 참조하십시오.
여러분의 패키지 사용하기Link to this heading
우리가 polls 디렉토리를 프로젝트 바깥으로 이동했으므로, 작동하지 않을것입니다. 우리의 새 django-polls 패키지를 설치하여 이 문제를 해결할 것입니다.
패키지를 설치하기 위해 pip를 사용하세요 (당신은 이미 설치하였습니다. 그렇죠?),
python -m pip install --user django-polls/dist/django_polls-0.1.tar.gz운이 따라준다면, 여러분의 Django 프로젝트는 이제 잘 작동할 것입니다. 확인해보기위해 서버를 다시 실행하세요.
패키지를 삭제하기 위해 pip를 사용하시오.
python -m pip uninstall django-polls
앱 퍼블리싱Link to this heading
우리는 django-polls 를 패키지화하고 테스트했기에, 세계와 공유할 준비가 되었습니다. 단순한 예제가 아니면, 여러분은 이제 아래와 같은 것들을 할 수 있습니다:
친구에게 패키지를 이메일로 보내기
웹사이트에 패키지 업로드
the Python Package Index (PyPI)와 같은 공용 저장소에 패키지를 게시하십시오. packaging.python.org에는 앱 퍼플리싱을 위한 좋은 튜토리얼이 있습니다.
파이썬 패키지를 가상 환경으로 설치하기Link to this heading
앞에서, 우리는 설문 조사 앱을 사용자 라이브러리로 설치했습니다. 여기에는 몇 가지 단점이 있습니다:
사용자 라이브러리를 수정하면 시스템의 다른 파이썬 소프트웨어에 영향을 미칠 수 있습니다.
이 패키지의 여러 버전 (또는 이름이 같은 다른 버전)을 실행할 수 없습니다.
일반적으로 이러한 상황들은 여러 Django 프로젝트를 유지보수할 때만 발생합니다. 이러한 경우, 최선의 해결책은 :doc:`venv <python:tutorial/venv>`를 사용하는 것입니다. 이 도구를 사용하면 각각 고유한 라이브러리 및 패키지 네임스페이스 복사본이 있는 다수의 분리된 Python 환경을 유지할 수 있습니다.