reusable-apps.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. =============================================
  2. Advanced tutorial: How to write reusable apps
  3. =============================================
  4. This advanced tutorial begins where :doc:`Tutorial 8 </intro/tutorial08>`
  5. left off. We'll be turning our web-poll into a standalone Python package
  6. you can reuse in new projects and share with other people.
  7. If you haven't recently completed Tutorials 1–7, we encourage you to review
  8. these so that your example project matches the one described below.
  9. Reusability matters
  10. ===================
  11. It's a lot of work to design, build, test and maintain a web application. Many
  12. Python and Django projects share common problems. Wouldn't it be great if we
  13. could save some of this repeated work?
  14. Reusability is the way of life in Python. `The Python Package Index (PyPI)
  15. <https://pypi.org/>`_ has a vast range of packages you can use in your own
  16. Python programs. Check out `Django Packages <https://djangopackages.org>`_ for
  17. existing reusable apps you could incorporate in your project. Django itself is
  18. also a normal Python package. This means that you can take existing Python
  19. packages or Django apps and compose them into your own web project. You only
  20. need to write the parts that make your project unique.
  21. Let's say you were starting a new project that needed a polls app like the one
  22. we've been working on. How do you make this app reusable? Luckily, you're well
  23. on the way already. In :doc:`Tutorial 1 </intro/tutorial01>`, we saw how we
  24. could decouple polls from the project-level URLconf using an ``include``.
  25. In this tutorial, we'll take further steps to make the app easy to use in new
  26. projects and ready to publish for others to install and use.
  27. .. admonition:: Package? App?
  28. A Python :term:`package` provides a way of grouping related Python code for
  29. easy reuse. A package contains one or more files of Python code (also known
  30. as "modules").
  31. A package can be imported with ``import foo.bar`` or ``from foo import
  32. bar``. For a directory (like ``polls``) to form a package, it must contain
  33. a special file ``__init__.py``, even if this file is empty.
  34. A Django *application* is a Python package that is specifically intended
  35. for use in a Django project. An application may use common Django
  36. conventions, such as having ``models``, ``tests``, ``urls``, and ``views``
  37. submodules.
  38. Later on we use the term *packaging* to describe the process of making a
  39. Python package easy for others to install. It can be a little confusing, we
  40. know.
  41. Your project and your reusable app
  42. ==================================
  43. After the previous tutorials, our project should look like this:
  44. .. code-block:: text
  45. mysite/
  46. manage.py
  47. mysite/
  48. __init__.py
  49. settings.py
  50. urls.py
  51. asgi.py
  52. wsgi.py
  53. polls/
  54. __init__.py
  55. admin.py
  56. apps.py
  57. migrations/
  58. __init__.py
  59. 0001_initial.py
  60. models.py
  61. static/
  62. polls/
  63. images/
  64. background.png
  65. style.css
  66. templates/
  67. polls/
  68. detail.html
  69. index.html
  70. results.html
  71. tests.py
  72. urls.py
  73. views.py
  74. templates/
  75. admin/
  76. base_site.html
  77. You created ``mysite/templates`` in :doc:`Tutorial 7 </intro/tutorial07>`,
  78. and ``polls/templates`` in :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps
  79. it is clearer why we chose to have separate template directories for the
  80. project and application: everything that is part of the polls application is in
  81. ``polls``. It makes the application self-contained and easier to drop into a
  82. new project.
  83. The ``polls`` directory could now be copied into a new Django project and
  84. immediately reused. It's not quite ready to be published though. For that, we
  85. need to package the app to make it easy for others to install.
  86. .. _installing-reusable-apps-prerequisites:
  87. Installing some prerequisites
  88. =============================
  89. The current state of Python packaging is a bit muddled with various tools. For
  90. this tutorial, we're going to use :pypi:`setuptools` to build our package. It's
  91. the recommended packaging tool (merged with the ``distribute`` fork). We'll
  92. also be using :pypi:`pip` to install and uninstall it. You should install these
  93. two packages now. If you need help, you can refer to :ref:`how to install
  94. Django with pip<installing-official-release>`. You can install ``setuptools``
  95. the same way.
  96. Packaging your app
  97. ==================
  98. Python *packaging* refers to preparing your app in a specific format that can
  99. be easily installed and used. Django itself is packaged very much like
  100. this. For a small app like polls, this process isn't too difficult.
  101. #. First, create a parent directory for the package, outside of your Django
  102. project. Call this directory ``django-polls``.
  103. .. admonition:: Choosing a name for your app
  104. When choosing a name for your package, check PyPI to avoid naming
  105. conflicts with existing packages. We recommend using a ``django-``
  106. prefix for package names, to identify your package as specific to
  107. Django, and a corresponding ``django_`` prefix for your module name. For
  108. example, the ``django-ratelimit`` package contains the
  109. ``django_ratelimit`` module.
  110. Application labels (that is, the final part of the dotted path to
  111. application packages) *must* be unique in :setting:`INSTALLED_APPS`.
  112. Avoid using the same label as any of the Django :doc:`contrib packages
  113. </ref/contrib/index>`, for example ``auth``, ``admin``, or
  114. ``messages``.
  115. #. Move the ``polls`` directory into ``django-polls`` directory, and rename it
  116. to ``django_polls``.
  117. #. Edit ``django_polls/apps.py`` so that :attr:`~.AppConfig.name` refers to the
  118. new module name and add :attr:`~.AppConfig.label` to give a short name for
  119. the app:
  120. .. code-block:: python
  121. :caption: ``django-polls/django_polls/apps.py``
  122. from django.apps import AppConfig
  123. class PollsConfig(AppConfig):
  124. default_auto_field = "django.db.models.BigAutoField"
  125. name = "django_polls"
  126. label = "polls"
  127. #. Create a file ``django-polls/README.rst`` with the following contents:
  128. .. code-block:: rst
  129. :caption: ``django-polls/README.rst``
  130. ============
  131. django-polls
  132. ============
  133. django-polls is a Django app to conduct web-based polls. For each
  134. question, visitors can choose between a fixed number of answers.
  135. Detailed documentation is in the "docs" directory.
  136. Quick start
  137. -----------
  138. 1. Add "polls" to your INSTALLED_APPS setting like this::
  139. INSTALLED_APPS = [
  140. ...,
  141. "django_polls",
  142. ]
  143. 2. Include the polls URLconf in your project urls.py like this::
  144. path("polls/", include("django_polls.urls")),
  145. 3. Run ``python manage.py migrate`` to create the models.
  146. 4. Start the development server and visit the admin to create a poll.
  147. 5. Visit the ``/polls/`` URL to participate in the poll.
  148. #. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
  149. scope of this tutorial, but suffice it to say that code released publicly
  150. without a license is *useless*. Django and many Django-compatible apps are
  151. distributed under the BSD license; however, you're free to pick your own
  152. license. Just be aware that your licensing choice will affect who is able
  153. to use your code.
  154. #. Next we'll create ``pyproject.toml``, ``setup.cfg``, and ``setup.py`` files
  155. which detail how to build and install the app. A full explanation of these
  156. files is beyond the scope of this tutorial, but the `setuptools
  157. documentation <https://setuptools.pypa.io/en/latest/>`_ has a good
  158. explanation. Create the ``django-polls/pyproject.toml``,
  159. ``django-polls/setup.cfg``, and ``django-polls/setup.py`` files with the
  160. following contents:
  161. .. code-block:: toml
  162. :caption: ``django-polls/pyproject.toml``
  163. [build-system]
  164. requires = ['setuptools>=40.8.0']
  165. build-backend = 'setuptools.build_meta'
  166. .. code-block:: ini
  167. :caption: ``django-polls/setup.cfg``
  168. [metadata]
  169. name = django-polls
  170. version = 0.1
  171. description = A Django app to conduct web-based polls.
  172. long_description = file: README.rst
  173. url = https://www.example.com/
  174. author = Your Name
  175. author_email = yourname@example.com
  176. license = BSD-3-Clause # Example license
  177. classifiers =
  178. Environment :: Web Environment
  179. Framework :: Django
  180. Framework :: Django :: X.Y # Replace "X.Y" as appropriate
  181. Intended Audience :: Developers
  182. License :: OSI Approved :: BSD License
  183. Operating System :: OS Independent
  184. Programming Language :: Python
  185. Programming Language :: Python :: 3
  186. Programming Language :: Python :: 3 :: Only
  187. Programming Language :: Python :: 3.10
  188. Programming Language :: Python :: 3.11
  189. Programming Language :: Python :: 3.12
  190. Topic :: Internet :: WWW/HTTP
  191. Topic :: Internet :: WWW/HTTP :: Dynamic Content
  192. [options]
  193. include_package_data = true
  194. packages = find:
  195. python_requires = >=3.10
  196. install_requires =
  197. Django >= X.Y # Replace "X.Y" as appropriate
  198. .. code-block:: python
  199. :caption: ``django-polls/setup.py``
  200. from setuptools import setup
  201. setup()
  202. #. Only Python modules and packages are included in the package by default. To
  203. include additional files, we'll need to create a ``MANIFEST.in`` file. The
  204. ``setuptools`` docs referred to in the previous step discuss this file in
  205. more detail. To include the templates, the ``README.rst`` and our
  206. ``LICENSE`` file, create a file ``django-polls/MANIFEST.in`` with the
  207. following contents:
  208. .. code-block:: text
  209. :caption: ``django-polls/MANIFEST.in``
  210. include LICENSE
  211. include README.rst
  212. recursive-include django_polls/static *
  213. recursive-include django_polls/templates *
  214. #. It's optional, but recommended, to include detailed documentation with your
  215. app. Create an empty directory ``django-polls/docs`` for future
  216. documentation. Add an additional line to ``django-polls/MANIFEST.in``:
  217. .. code-block:: text
  218. recursive-include docs *
  219. Note that the ``docs`` directory won't be included in your package unless
  220. you add some files to it. Many Django apps also provide their documentation
  221. online through sites like `readthedocs.org <https://readthedocs.org>`_.
  222. #. Try building your package by running ``python setup.py sdist`` inside
  223. ``django-polls``. This creates a directory called ``dist`` and builds your
  224. new package, ``django-polls-0.1.tar.gz``.
  225. For more information on packaging, see Python's `Tutorial on Packaging and
  226. Distributing Projects
  227. <https://packaging.python.org/tutorials/packaging-projects/>`_.
  228. Using your own package
  229. ======================
  230. Since we moved the ``polls`` directory out of the project, it's no longer
  231. working. We'll now fix this by installing our new ``django-polls`` package.
  232. .. admonition:: Installing as a user library
  233. The following steps install ``django-polls`` as a user library. Per-user
  234. installs have a lot of advantages over installing the package system-wide,
  235. such as being usable on systems where you don't have administrator access
  236. as well as preventing the package from affecting system services and other
  237. users of the machine.
  238. Note that per-user installations can still affect the behavior of system
  239. tools that run as that user, so using a virtual environment is a more robust
  240. solution (see below).
  241. #. To install the package, use pip (you already :ref:`installed it
  242. <installing-reusable-apps-prerequisites>`, right?):
  243. .. code-block:: shell
  244. python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
  245. #. Update ``mysite/settings.py`` to point to the new module name::
  246. INSTALLED_APPS = [
  247. "django_polls.apps.PollsConfig",
  248. ...,
  249. ]
  250. #. Update ``mysite/urls.py`` to point to the new module name::
  251. urlpatterns = [
  252. path("polls/", include("django_polls.urls")),
  253. ...,
  254. ]
  255. #. Run the development server to confirm the project continues to work.
  256. Publishing your app
  257. ===================
  258. Now that we've packaged and tested ``django-polls``, it's ready to share with
  259. the world! If this wasn't just an example, you could now:
  260. * Email the package to a friend.
  261. * Upload the package on your website.
  262. * Post the package on a public repository, such as `the Python Package Index
  263. (PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
  264. tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
  265. for doing this.
  266. Installing Python packages with a virtual environment
  267. =====================================================
  268. Earlier, we installed ``django-polls`` as a user library. This has some
  269. disadvantages:
  270. * Modifying the user libraries can affect other Python software on your system.
  271. * You won't be able to run multiple versions of this package (or others with
  272. the same name).
  273. Typically, these situations only arise once you're maintaining several Django
  274. projects. When they do, the best solution is to use :doc:`venv
  275. <python:tutorial/venv>`. This tool allows you to maintain multiple isolated
  276. Python environments, each with its own copy of the libraries and package
  277. namespace.