Tutorial Avanzado: Cómo escribir aplicaciones reutilizablesLink 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.
Si recientemente no ha completado los Tutoriales 1-7, le recomendamos que los revise para que su proyecto de ejemplo coincida con el que se describe abajo.
La reusabilidad importaLink to this heading
Requiere mucho trabajo diseñar, crear, probar y mantener una aplicación web. Muchos proyectos de Python y Django comparten problemas comunes. ¿No sería genial si pudiéramos ahorrarnos algo de este trabajo repetido?
Reusability is the way of life in Python. The Python Package Index (PyPI) has a vast range of packages you can use in your own Python programs. Check out Django Packages for existing reusable apps you could incorporate in your project. Django itself is also a normal Python package. This means that you can take existing Python packages or Django apps and compose them into your own web project. You only need to write the parts that make your project unique.
Digamos que ha empezado un nuevo proyecto que necesitaba una aplicación de encuestas como la que hemos estado trabajando. ¿Cómo hace que esta aplicación sea reutilizable? Por suerte va bien encaminado. En el Tutorial 1, vimos como podíamos separar las encuestas de la URLconf a nivel de proyecto utilizando un include. En este tutorial, adoptaremos las medidas para hacer que la aplicación sea fácil de utilizar en nuevos proyectos y quede lista para su publicación de manera que otros la instalen y usen.
Su proyecto y su aplicación reutilizableLink to this heading
After the previous tutorials, our project should look like this:
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.png
style.css
templates/
polls/
detail.html
index.html
results.html
tests.py
urls.py
views.py
templates/
admin/
base_site.html
Ha creado mysite/templates en Tutorial 7, y polls/templates en Tutorial 3. Ahora quizá queda más claro por qué se separan los directorios de plantillas en el proyecto y la aplicación: todo lo que forma parte de la applicación de encuestas está en polls. Esto hace que la aplicación esté auto-contenida y sea más sencillo incluirla en un nuevo proyecto.
El directorio polls ahora se podría copiar en un nuevo proyecto de Django e inmediatamente ser reutilizado. Sin embargo, no está listo para ser publicado. Para ello, necesitamos empaquetar la aplicación para hacer más fácil que otros la instalen.
Instalación de algunos requisitos previosLink to this heading
The current state of Python packaging is a bit muddled with various tools. For
this tutorial, we’re going to use setuptools to build our package. It’s
the recommended packaging tool (merged with the distribute fork). We’ll
also be using pip to install and uninstall it. You should install these
two packages now. If you need help, you can refer to how to install
Django with pip. You can install setuptools
the same way.
Empaquetando su aplicaciónLink to this heading
El empaquetamiento en Python se refiere a la preparación de su aplicación en un formato específico que pueda ser fácilmente instalado y utilizado. Django mismo está empaquetado de forma muy similar a esta. Para una aplicación pequeña como polls este proceso no es muy complejo.
First, create a parent directory for the package, outside of your Django project. Call this directory
django-polls.Move the
pollsdirectory intodjango-pollsdirectory, and rename it todjango_polls.Edit
django_polls/apps.pyso thatnamerefers to the new module name and addlabelto give a short name for the app:django-polls/django_polls/apps.pyfrom django.apps import AppConfig class PollsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "django_polls" label = "polls"Cree un archivo
django-polls/README.rstcon el siguiente contenido:django-polls/README.rst============ django-polls ============ django-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 = [ ..., "django_polls", ] 2. Include the polls URLconf in your project urls.py like this:: path("polls/", include("django_polls.urls")), 3. Run ``python manage.py migrate`` to create the models. 4. Start the development server and visit the admin to create a poll. 5. Visit the ``/polls/`` URL to participate in the poll.Cree un archivo
django-polls/LICENSE. Elegir una licencia está fuera del alcance de este tutorial, pero basta con señalar que el código liberado públicamente sin ninguna licencia es inútil. Django y muchas aplicaciones compatibles con Django se distribuyen bajo la licencia BSD, sin embargo, usted es libre de elegir su propia licencia. Sólo tenga en cuenta que la elección de su licencia repercutirá sobre quién podrá utilizar su código.Next we’ll create
pyproject.toml,setup.cfg, andsetup.pyfiles which detail how to build and install the app. A full explanation of these files is beyond the scope of this tutorial, but the setuptools documentation has a good explanation. Create thedjango-polls/pyproject.toml,django-polls/setup.cfg, anddjango-polls/setup.pyfiles with the following contents:django-polls/pyproject.toml[build-system] requires = ['setuptools>=40.8.0'] build-backend = 'setuptools.build_meta'django-polls/setup.cfg[metadata] name = django-polls version = 0.1 description = A Django app to conduct web-based polls. long_description = file: README.rst url = https://www.example.com/ author = Your Name author_email = yourname@example.com license = BSD-3-Clause # Example license 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.10 Programming Language :: Python :: 3.11 Programming Language :: Python :: 3.12 Topic :: Internet :: WWW/HTTP Topic :: Internet :: WWW/HTTP :: Dynamic Content [options] include_package_data = true packages = find: python_requires = >=3.10 install_requires = Django >= X.Y # Replace "X.Y" as appropriatedjango-polls/setup.pyfrom setuptools import setup setup()Only Python modules and packages are included in the package by default. To include additional files, we’ll need to create a
MANIFEST.infile. Thesetuptoolsdocs referred to in the previous step discuss this file in more detail. To include the templates, theREADME.rstand ourLICENSEfile, create a filedjango-polls/MANIFEST.inwith the following contents:django-polls/MANIFEST.ininclude LICENSE include README.rst recursive-include django_polls/static * recursive-include django_polls/templates *It’s optional, but recommended, to include detailed documentation with your app. Create an empty directory
django-polls/docsfor future documentation. Add an additional line todjango-polls/MANIFEST.in:recursive-include docs *Tenga en cuenta que el directorio
docsno se incluirá en su paquete a menos que usted agregue algunos archivos a este. Muchas aplicaciones Django proporcionan también su documentación online a través de sitios como readthedocs.org.Try building your package by running
python setup.py sdistinsidedjango-polls. This creates a directory calleddistand builds your new package,django-polls-0.1.tar.gz.
For more information on packaging, see Python’s Tutorial on Packaging and Distributing Projects.
Usando su propio paqueteLink to this heading
Dado que movimos el directorio polls fuera del proyecto, ya no funciona. Vamos a solucionar esto mediante la instalación de nuestro nuevo paquete django-polls.
To install the package, use pip (you already installed it, right?):
python -m pip install --user django-polls/dist/django-polls-0.1.tar.gzUpdate
mysite/settings.pyto point to the new module name:INSTALLED_APPS = [ "django_polls.apps.PollsConfig", ..., ]Update
mysite/urls.pyto point to the new module name:urlpatterns = [ path("polls/", include("django_polls.urls")), ..., ]Run the development server to confirm the project continues to work.
Publicando su aplicaciónLink to this heading
Ahora que hemos empaquetado y probado django-polls, está lista para compartir con el mundo! Si esto no era más que un ejemplo, usted ahora podría:
Enviar por correo electrónico el paquete a un amigo.
Cargar el paquete en su sitio web.
Post the package on a public repository, such as the Python Package Index (PyPI). packaging.python.org has a good tutorial for doing this.
Installing Python packages with a virtual environmentLink to this heading
Earlier, we installed django-polls as a user library. This has some
disadvantages:
Modificar las librerías de usuario puede afectar a otro programa Python en su sistema.
Usted no podrá ejecutar distintas versiones de este paquete (u otros con el mismo nombre).
Typically, these situations only arise once you’re maintaining several Django projects. When they do, the best solution is to use venv. This tool allows you to maintain multiple isolated Python environments, each with its own copy of the libraries and package namespace.