Debian Codegraph @

docs/intro/reusable-apps.txt

raw
1 =============================================
2 Advanced tutorial: How to write reusable apps
3 =============================================
4
5 This advanced tutorial begins where :doc:`Tutorial 8 </intro/tutorial08>`
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–8, 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 .. code-block:: text
59
60 djangotutorial/
61 manage.py
62 mysite/
63 __init__.py
64 settings.py
65 urls.py
66 asgi.py
67 wsgi.py
68 polls/
69 __init__.py
70 admin.py
71 apps.py
72 migrations/
73 __init__.py
74 0001_initial.py
75 models.py
76 static/
77 polls/
78 images/
79 background.png
80 style.css
81 templates/
82 polls/
83 detail.html
84 index.html
85 results.html
86 tests.py
87 urls.py
88 views.py
89 templates/
90 admin/
91 base_site.html
92
93 You created ``djangotutorial/templates`` in :doc:`Tutorial 7
94 </intro/tutorial07>`, and ``polls/templates`` in
95 :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps it is clearer why we chose
96 to have separate template directories for the project and application:
97 everything that is part of the polls application is in ``polls``. It makes the
98 application self-contained and easier to drop into a new project.
99
100 The ``polls`` directory could now be copied into a new Django project and
101 immediately reused. It's not quite ready to be published though. For that, we
102 need to package the app to make it easy for others to install.
103
104 .. _installing-reusable-apps-prerequisites:
105
106 Installing some prerequisites
107 =============================
108
109 The current state of Python packaging is a bit muddled with various tools. For
110 this tutorial, we're going to use :pypi:`setuptools` to build our package. It's
111 the recommended packaging tool (merged with the ``distribute`` fork). We'll
112 also be using :pypi:`pip` to install and uninstall it. You should install these
113 two packages now. If you need help, you can refer to :ref:`how to install
114 Django with pip<installing-official-release>`. You can install ``setuptools``
115 the same way.
116
117 Packaging your app
118 ==================
119
120 Python *packaging* refers to preparing your app in a specific format that can
121 be easily installed and used. Django itself is packaged very much like
122 this. For a small app like polls, this process isn't too difficult.
123
124 #. First, create a parent directory for the package, outside of your Django
125 project. Call this directory ``django-polls``.
126
127 .. admonition:: Choosing a name for your app
128
129 When choosing a name for your package, check PyPI to avoid naming
130 conflicts with existing packages. We recommend using a ``django-``
131 prefix for package names, to identify your package as specific to
132 Django, and a corresponding ``django_`` prefix for your module name. For
133 example, the ``django-ratelimit`` package contains the
134 ``django_ratelimit`` module.
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 ``django-polls`` directory, and rename it
143 to ``django_polls``.
144
145 #. Edit ``django_polls/apps.py`` so that :attr:`~.AppConfig.name` refers to the
146 new module name and add :attr:`~.AppConfig.label` to give a short name for
147 the app:
148
149 .. code-block:: python
150 :caption: ``django-polls/django_polls/apps.py``
151
152 from django.apps import AppConfig
153
154
155 class PollsConfig(AppConfig):
156 default_auto_field = "django.db.models.BigAutoField"
157 name = "django_polls"
158 label = "polls"
159
160 #. Create a file ``django-polls/README.rst`` with the following contents:
161
162 .. code-block:: rst
163 :caption: ``django-polls/README.rst``
164
165 ============
166 django-polls
167 ============
168
169 django-polls is a Django app to conduct web-based polls. For each
170 question, visitors can choose between a fixed number of answers.
171
172 Detailed documentation is in the "docs" directory.
173
174 Quick start
175 -----------
176
177 1. Add "polls" to your INSTALLED_APPS setting like this::
178
179 INSTALLED_APPS = [
180 ...,
181 "django_polls",
182 ]
183
184 2. Include the polls URLconf in your project urls.py like this::
185
186 path("polls/", include("django_polls.urls")),
187
188 3. Run ``python manage.py migrate`` to create the models.
189
190 4. Start the development server and visit the admin to create a poll.
191
192 5. Visit the ``/polls/`` URL to participate in the poll.
193
194 #. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
195 scope of this tutorial, but suffice it to say that code released publicly
196 without a license is *useless*. Django and many Django-compatible apps are
197 distributed under the BSD license; however, you're free to pick your own
198 license. Just be aware that your licensing choice will affect who is able
199 to use your code.
200
201 #. Next we'll create the ``pyproject.toml`` file which details how to build and
202 install the app. A full explanation of this file is beyond the scope of this
203 tutorial, but the `Python Packaging User Guide
204 <https://packaging.python.org/guides/writing-pyproject-toml/>`_ has a good
205 explanation. Create the ``django-polls/pyproject.toml`` file with the
206 following contents:
207
208 .. code-block:: toml
209 :caption: ``django-polls/pyproject.toml``
210
211 [build-system]
212 requires = ["setuptools>=77.0.3"]
213 build-backend = "setuptools.build_meta"
214
215 [project]
216 name = "django-polls"
217 version = "0.1"
218 dependencies = [
219 "django>=X.Y", # Replace "X.Y" as appropriate
220 ]
221 description = "A Django app to conduct web-based polls."
222 readme = "README.rst"
223 license = "BSD-3-Clause"
224 requires-python = ">= 3.10"
225 authors = [
226 {name = "Your Name", email = "[email protected]"},
227 ]
228 classifiers = [
229 "Environment :: Web Environment",
230 "Framework :: Django",
231 "Framework :: Django :: X.Y", # Replace "X.Y" as appropriate
232 "Intended Audience :: Developers",
233 "Operating System :: OS Independent",
234 "Programming Language :: Python",
235 "Programming Language :: Python :: 3",
236 "Programming Language :: Python :: 3 :: Only",
237 "Programming Language :: Python :: 3.10",
238 "Programming Language :: Python :: 3.11",
239 "Programming Language :: Python :: 3.12",
240 "Programming Language :: Python :: 3.13",
241 "Programming Language :: Python :: 3.14",
242 "Topic :: Internet :: WWW/HTTP",
243 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
244 ]
245
246 [project.urls]
247 Homepage = "https://www.example.com/"
248
249 #. Many common files and Python modules and packages are included in the
250 package by default. To include additional files, we'll need to create a
251 ``MANIFEST.in`` file. To include the templates and static files, create a
252 file ``django-polls/MANIFEST.in`` with the following contents:
253
254 .. code-block:: text
255 :caption: ``django-polls/MANIFEST.in``
256
257 recursive-include django_polls/static *
258 recursive-include django_polls/templates *
259
260 #. It's optional, but recommended, to include detailed documentation with your
261 app. Create an empty directory ``django-polls/docs`` for future
262 documentation.
263
264 Note that the ``docs`` directory won't be included in your package unless
265 you add some files to it. Many Django apps also provide their documentation
266 online through sites like `readthedocs.org <https://readthedocs.org>`_.
267
268 Many Python projects, including Django and Python itself, use `Sphinx
269 <https://www.sphinx-doc.org/en/master/usage/quickstart.html>`_ to build
270 their documentation. If you choose to use Sphinx you can link back to the
271 Django documentation by configuring `Intersphinx
272 <https://www.sphinx-doc.org/en/master/usage/quickstart.html#intersphinx>`_
273 and including a value for Django in your project's ``intersphinx_mapping``
274 value::
275
276 intersphinx_mapping = {
277 # ...
278 "django": (
279 "https://docs.djangoproject.com/en/stable/",
280 None,
281 ),
282 }
283
284 With that in place, you can then cross-link to specific entries, in the
285 same way as in the Django docs, such as
286 "``:attr:`django.test.TransactionTestCase.databases```".
287
288 #. Check that the :pypi:`build` package is installed (``python -m pip install
289 build``) and try building your package by running ``python -m build`` inside
290 ``django-polls``. This creates a directory called ``dist`` and builds your
291 new package into source and binary formats, ``django_polls-0.1.tar.gz`` and
292 ``django_polls-0.1-py3-none-any.whl``.
293
294 For more information on packaging, see Python's `Tutorial on Packaging and
295 Distributing Projects
296 <https://packaging.python.org/tutorials/packaging-projects/>`_.
297
298 Using your own package
299 ======================
300
301 Since we moved the ``polls`` directory out of the project, it's no longer
302 working. We'll now fix this by installing our new ``django-polls`` package.
303
304 .. admonition:: Installing as a user library
305
306 The following steps install ``django-polls`` as a user library. Per-user
307 installs have a lot of advantages over installing the package system-wide,
308 such as being usable on systems where you don't have administrator access
309 as well as preventing the package from affecting system services and other
310 users of the machine.
311
312 Note that per-user installations can still affect the behavior of system
313 tools that run as that user, so using a virtual environment is a more robust
314 solution (see below).
315
316 #. To install the package, use pip (you already :ref:`installed it
317 <installing-reusable-apps-prerequisites>`, right?):
318
319 .. code-block:: shell
320
321 python -m pip install --user django-polls/dist/django_polls-0.1.tar.gz
322
323 #. Update ``mysite/settings.py`` to point to the new module name::
324
325 INSTALLED_APPS = [
326 "django_polls.apps.PollsConfig",
327 ...,
328 ]
329
330 #. Update ``mysite/urls.py`` to point to the new module name::
331
332 urlpatterns = [
333 path("polls/", include("django_polls.urls")),
334 ...,
335 ]
336
337 #. Run the development server to confirm the project continues to work.
338
339 Publishing your app
340 ===================
341
342 Now that we've packaged and tested ``django-polls``, it's ready to share with
343 the world! If this wasn't just an example, you could now:
344
345 * Email the package to a friend.
346
347 * Upload the package on your website.
348
349 * Post the package on a public repository, such as `the Python Package Index
350 (PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
351 tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_
352 for doing this.
353
354 Installing Python packages with a virtual environment
355 =====================================================
356
357 Earlier, we installed ``django-polls`` as a user library. This has some
358 disadvantages:
359
360 * Modifying the user libraries can affect other Python software on your system.
361
362 * You won't be able to run multiple versions of this package (or others with
363 the same name).
364
365 Typically, these situations only arise once you're maintaining several Django
366 projects. When they do, the best solution is to use :doc:`venv
367 <python:tutorial/venv>`. This tool allows you to maintain multiple isolated
368 Python environments, each with its own copy of the libraries and package
369 namespace.