reusable-apps.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. =============================================
  2. Advanced tutorial: How to write reusable apps
  3. =============================================
  4. This advanced tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>`
  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. mysite/
  45. manage.py
  46. mysite/
  47. __init__.py
  48. settings.py
  49. urls.py
  50. asgi.py
  51. wsgi.py
  52. polls/
  53. __init__.py
  54. admin.py
  55. apps.py
  56. migrations/
  57. __init__.py
  58. 0001_initial.py
  59. models.py
  60. static/
  61. polls/
  62. images/
  63. background.gif
  64. style.css
  65. templates/
  66. polls/
  67. detail.html
  68. index.html
  69. results.html
  70. tests.py
  71. urls.py
  72. views.py
  73. templates/
  74. admin/
  75. base_site.html
  76. You created ``mysite/templates`` in :doc:`Tutorial 7 </intro/tutorial07>`,
  77. and ``polls/templates`` in :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps
  78. it is clearer why we chose to have separate template directories for the
  79. project and application: everything that is part of the polls application is in
  80. ``polls``. It makes the application self-contained and easier to drop into a
  81. new project.
  82. The ``polls`` directory could now be copied into a new Django project and
  83. immediately reused. It's not quite ready to be published though. For that, we
  84. need to package the app to make it easy for others to install.
  85. .. _installing-reusable-apps-prerequisites:
  86. Installing some prerequisites
  87. =============================
  88. The current state of Python packaging is a bit muddled with various tools. For
  89. this tutorial, we're going to use setuptools_ to build our package. It's the
  90. recommended packaging tool (merged with the ``distribute`` fork). We'll also be
  91. using `pip`_ to install and uninstall it. You should install these
  92. two packages now. If you need help, you can refer to :ref:`how to install
  93. Django with pip<installing-official-release>`. You can install ``setuptools``
  94. the same way.
  95. .. _setuptools: https://pypi.org/project/setuptools/
  96. .. _pip: https://pypi.org/project/pip/
  97. Packaging your app
  98. ==================
  99. Python *packaging* refers to preparing your app in a specific format that can
  100. be easily installed and used. Django itself is packaged very much like
  101. this. For a small app like polls, this process isn't too difficult.
  102. #. First, create a parent directory for ``polls``, outside of your Django
  103. project. Call this directory ``django-polls``.
  104. .. admonition:: Choosing a name for your app
  105. When choosing a name for your package, check resources like PyPI to avoid
  106. naming conflicts with existing packages. It's often useful to prepend
  107. ``django-`` to your module name when creating a package to distribute.
  108. This helps others looking for Django apps identify your app as Django
  109. specific.
  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 the ``django-polls`` directory.
  116. #. Create a file ``django-polls/README.rst`` with the following contents:
  117. .. code-block:: rst
  118. :caption: django-polls/README.rst
  119. =====
  120. Polls
  121. =====
  122. Polls is a Django app to conduct Web-based polls. For each question,
  123. visitors can choose between a fixed number of answers.
  124. Detailed documentation is in the "docs" directory.
  125. Quick start
  126. -----------
  127. 1. Add "polls" to your INSTALLED_APPS setting like this::
  128. INSTALLED_APPS = [
  129. ...
  130. 'polls',
  131. ]
  132. 2. Include the polls URLconf in your project urls.py like this::
  133. path('polls/', include('polls.urls')),
  134. 3. Run ``python manage.py migrate`` to create the polls models.
  135. 4. Start the development server and visit http://127.0.0.1:8000/admin/
  136. to create a poll (you'll need the Admin app enabled).
  137. 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
  138. #. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
  139. scope of this tutorial, but suffice it to say that code released publicly
  140. without a license is *useless*. Django and many Django-compatible apps are
  141. distributed under the BSD license; however, you're free to pick your own
  142. license. Just be aware that your licensing choice will affect who is able
  143. to use your code.
  144. #. Next we'll create ``setup.cfg`` and ``setup.py`` files which detail how to
  145. build and install the app. A full explanation of these files is beyond the
  146. scope of this tutorial, but the `setuptools documentation
  147. <https://setuptools.readthedocs.io/en/latest/>`_ has a good explanation.
  148. Create the files ``django-polls/setup.cfg`` and ``django-polls/setup.py``
  149. with the following contents:
  150. .. code-block:: ini
  151. :caption: django-polls/setup.cfg
  152. [metadata]
  153. name = django-polls
  154. version = 0.1
  155. description = A Django app to conduct Web-based polls.
  156. long_description = file: README.rst
  157. url = https://www.example.com/
  158. author = Your Name
  159. author_email = yourname@example.com
  160. license = BSD-3-Clause # Example license
  161. classifiers =
  162. Environment :: Web Environment
  163. Framework :: Django
  164. Framework :: Django :: X.Y # Replace "X.Y" as appropriate
  165. Intended Audience :: Developers
  166. License :: OSI Approved :: BSD License
  167. Operating System :: OS Independent
  168. Programming Language :: Python
  169. Programming Language :: Python :: 3
  170. Programming Language :: Python :: 3 :: Only
  171. Programming Language :: Python :: 3.6
  172. Programming Language :: Python :: 3.7
  173. Programming Language :: Python :: 3.8
  174. Topic :: Internet :: WWW/HTTP
  175. Topic :: Internet :: WWW/HTTP :: Dynamic Content
  176. [options]
  177. include_package_data = true
  178. packages = find:
  179. python_requires = >=3.6
  180. install_requires =
  181. Django >= X.Y # Replace "X.Y" as appropriate
  182. .. code-block:: python
  183. :caption: django-polls/setup.py
  184. from setuptools import setup
  185. setup()
  186. #. Only Python modules and packages are included in the package by default. To
  187. include additional files, we'll need to create a ``MANIFEST.in`` file. The
  188. setuptools docs referred to in the previous step discuss this file in more
  189. details. To include the templates, the ``README.rst`` and our ``LICENSE``
  190. file, create a file ``django-polls/MANIFEST.in`` with the following
  191. contents:
  192. .. code-block:: text
  193. :caption: django-polls/MANIFEST.in
  194. include LICENSE
  195. include README.rst
  196. recursive-include polls/static *
  197. recursive-include polls/templates *
  198. #. It's optional, but recommended, to include detailed documentation with your
  199. app. Create an empty directory ``django-polls/docs`` for future
  200. documentation. Add an additional line to ``django-polls/MANIFEST.in``::
  201. recursive-include docs *
  202. Note that the ``docs`` directory won't be included in your package unless
  203. you add some files to it. Many Django apps also provide their documentation
  204. online through sites like `readthedocs.org <https://readthedocs.org>`_.
  205. #. Try building your package with ``python setup.py sdist`` (run from inside
  206. ``django-polls``). This creates a directory called ``dist`` and builds your
  207. new package, ``django-polls-0.1.tar.gz``.
  208. For more information on packaging, see Python's `Tutorial on Packaging and
  209. Distributing Projects
  210. <https://packaging.python.org/tutorials/packaging-projects/>`_.
  211. Using your own package
  212. ======================
  213. Since we moved the ``polls`` directory out of the project, it's no longer
  214. working. We'll now fix this by installing our new ``django-polls`` package.
  215. .. admonition:: Installing as a user library
  216. The following steps install ``django-polls`` as a user library. Per-user
  217. installs have a lot of advantages over installing the package system-wide,
  218. such as being usable on systems where you don't have administrator access
  219. as well as preventing the package from affecting system services and other
  220. users of the machine.
  221. Note that per-user installations can still affect the behavior of system
  222. tools that run as that user, so using a virtual environment is a more robust
  223. solution (see below).
  224. #. To install the package, use pip (you already :ref:`installed it
  225. <installing-reusable-apps-prerequisites>`, right?)::
  226. python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
  227. #. With luck, your Django project should now work correctly again. Run the
  228. server again to confirm this.
  229. #. To uninstall the package, use pip::
  230. python -m pip uninstall django-polls
  231. Publishing your app
  232. ===================
  233. Now that we've packaged and tested ``django-polls``, it's ready to share with
  234. the world! If this wasn't just an example, you could now:
  235. * Email the package to a friend.
  236. * Upload the package on your website.
  237. * Post the package on a public repository, such as `the Python Package Index
  238. (PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
  239. tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
  240. for doing this.
  241. Installing Python packages with a virtual environment
  242. =====================================================
  243. Earlier, we installed the polls app as a user library. This has some
  244. disadvantages:
  245. * Modifying the user libraries can affect other Python software on your system.
  246. * You won't be able to run multiple versions of this package (or others with
  247. the same name).
  248. Typically, these situations only arise once you're maintaining several Django
  249. projects. When they do, the best solution is to use :doc:`venv
  250. <python:tutorial/venv>`. This tool allows you to maintain multiple isolated
  251. Python environments, each with its own copy of the libraries and package
  252. namespace.