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