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.
If you haven’t recently completed Tutorials 1–8, we encourage you to review these so that your example project matches the one described below.
Ci vuole molto lavoro per progettare, costruire, testare e manutenere una applicazione web. Alcuni progetti in Python e Django condividono problemi comuni. Non sarebbe fantastico se potessimo risparmiare parte di questo lavoro ripetuto?
La riusabilità è uno stile di vita in Python. Il Python Package Index (PyPI) <https://pypi.org/> offre una vasta gamma di package che puoi usare nei tuoi programmi Python. Dai un’occhiata agli Django Packages per trovare app riutilizzabili da incorporare nei tuoi progetti. Django stesso è un normale package. Questo significa che puoi prendere package Django esistenti o app Django e comporli nel tuo progetto web. Devi solo scrivere le parti che rendono il tuo progetto unico.
Diciamo che tu stia iniziando un nuovo progetto che necessita di una applicazione di questionari come quella su cui abbiamo lavorato. Come rendi quest’app riutilizzabile? Fortunatamente, sei già un passo avanti. Nel Tutorial 1, abbiamo detto come disaccoppiare polls dalla configurazione delle URL a livello di progetto usando include
. In questo tutorial, faremo altri passi per rendere l’app facilmente utilizzabile in progetti nuovi e pronta da pubblicare affinchè altri possano installarla ed usarla.
Package? App?
Un package di Python fornisce una modo di raggruppare codice Python correlato per un riutilizzo piu semplice. Un package contiene uno o piu file scritti in Python ( conosciuti anche come «modules» ).
Un package puo essere importato con import foo.bar
oppure from foo import bar
. Per una cartella ( come polls
) per creare un package, deve contenere un file speciale __init__.py
, anche se questo file puo restare vuoto.
Un «applicazione» Django è un package Python che ha lo specifico scopo di essere usato in un progetto Django. Un” applicazione puo” useare convenzioni comuni di Django, come avere models
, tests
, urls
, e views
sottomoduli.
Più tardi usiamo il termine packaging per descrivere il processo di costruire un pacchetto python facile dagli altri per installare. Può essere un pochino confusonario, lo sappiamo
After the previous tutorials, our project should look like this:
djangotutorial/
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
You created djangotutorial/templates
in Tutorial 7, and polls/templates
in
Tutorial 3. Now perhaps it is clearer why we chose
to have separate template directories for the project and application:
everything that is part of the polls application is in polls
. It makes the
application self-contained and easier to drop into a new project.
La directory polls
può essere copiata in un nuovo progetto Django e immediatamente riutilizzata. Non è completamente pronta per essere pubblicata. Per questo, dobbiamo creare un pacchetto dall’app per semplificare l’installazione da parte di altri.
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.
Il packaging Python si riferisce al preparare la tua app in un formato specifico che può essere facilmente installato e riutilizzato. Django stesso è «impacchettato» così. Per piccole app come polls, è un processo non molto difficile.
First, create a parent directory for the package, outside of your Django
project. Call this directory django-polls
.
Scegli un nome per la tua app
When choosing a name for your package, check PyPI to avoid naming
conflicts with existing packages. We recommend using a django-
prefix for package names, to identify your package as specific to
Django, and a corresponding django_
prefix for your module name. For
example, the django-ratelimit
package contains the
django_ratelimit
module.
L” etichetta dell” applicazione (cioè, la parte finale del percorso puntato al package dell’applicazione) deve essere unica in INSTALLED_APPS
. Evita di usare le stesse etichette di uno degli Django contrib packages, per esempio auth
, admin
, o messages
.
Move the polls
directory into django-polls
directory, and rename it
to django_polls
.
Edit django_polls/apps.py
so that name
refers to the
new module name and add label
to give a short name for
the app:
django-polls/django_polls/apps.py
¶from django.apps import AppConfig
class PollsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "django_polls"
label = "polls"
Crea un file django-polls/README.rst
con il seguente contenuto:
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.
Crea un file ``django-polls/LICENSE`. Scegliere una licenza è oltre lo scopo di questo tutorial, ma è sufficiente dire che il codice rilasciato pubblicamente senza licenza è inutile. Django e molte app Django-compatibili sono distribuite sotto la licenza BSD; comunque, sei libero di scegliere la licenza che preferisci. Sii solo consapevole che la licenza che scegli influenzerà anche quelli che usano il tuo codice.
Next we’ll create the pyproject.toml
file which details how to build and
install the app. A full explanation of this file is beyond the scope of this
tutorial, but the Python Packaging User Guide has a good
explanation. Create the django-polls/pyproject.toml
file with the
following contents:
django-polls/pyproject.toml
¶[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "django-polls"
version = "0.1"
dependencies = [
"django>=X.Y", # Replace "X.Y" as appropriate
]
description = "A Django app to conduct web-based polls."
readme = "README.rst"
requires-python = ">= 3.10"
authors = [
{name = "Your Name", email = "yourname@example.com"},
]
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",
"Programming Language :: Python :: 3.13",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
]
[project.urls]
Homepage = "https://www.example.com/"
Many common files and Python modules and packages are included in the
package by default. To include additional files, we’ll need to create a
MANIFEST.in
file. To include the templates and static files, create a
file django-polls/MANIFEST.in
with the following contents:
django-polls/MANIFEST.in
¶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/docs
for future
documentation.
Nota che la directory docs
non verrà inclusa nel tuo package finchè non ci aggiungi dei file. Molte Django app offrono la loro documentazione online anche attraverso siti come readthedocs.org.
Many Python projects, including Django and Python itself, use Sphinx to build
their documentation. If you choose to use Sphinx you can link back to the
Django documentation by configuring Intersphinx
and including a value for Django in your project’s intersphinx_mapping
value:
intersphinx_mapping = {
# ...
"django": (
"https://docs.djangoproject.com/en/stable/",
None,
),
}
With that in place, you can then cross-link to specific entries, in the
same way as in the Django docs, such as
«:attr:`django.test.TransactionTestCase.databases`
».
Check that the build package is installed (python -m pip install
build
) and try building your package by running python -m build
inside
django-polls
. This creates a directory called dist
and builds your
new package into source and binary formats, django-polls-0.1.tar.gz
and
django_polls-0.1-py3-none-any.whl
.
Per ulteriori informazioni sul packaging, vedi il tutorial di Python Tutorial sul Packaging e la Distribuzione di Progetti.
Dato che abbiamo spostato la cartella polls
fuori dal nostro progetto, non funziona più. Possiamo sistemare questo problema, installando il nuovo nostro package django-polls
.
Installando una libreria utente
I seguenti step installano django-polls
come libreria utente. Le installazioni «per utente» hanno molti vantaggi rispetto a quelle di sistema, come per esempio il fatto di poter essere utilizzate su sistemi dove non si ha accesso di amministrazione così come il fatto che l’utilizzo del package non ha effetto sui servizi del sistema o sugli altri utenti della macchina.
Nota che le installazioni «per utente» possono ancora avere effetto sul comportamento di quei tool di sistema che sono lanciati da quell’utente, quindi utilizzare un virtual environment è una soluzione più robusta (vedi sotto).
To install the package, use pip (you already installed it, right?):
python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz
Update mysite/settings.py
to point to the new module name:
INSTALLED_APPS = [
"django_polls.apps.PollsConfig",
...,
]
Update mysite/urls.py
to point to the new module name:
urlpatterns = [
path("polls/", include("django_polls.urls")),
...,
]
Run the development server to confirm the project continues to work.
Ora che abbiamo creato e testato il package django-polls
, è pronto per essere condiviso con il mondo! Se questo non era solo un esempio, potresti fare ora:
Manda via mail il package ad un amico.
Uploada il pacchetto sul tuo sito web
Metti il package su un repository pubblico come il Python Package Index (PyPI). packaging.python.org <https://packaging.python.org>`_ offre un bel tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_ per farlo.
Earlier, we installed django-polls
as a user library. This has some
disadvantages:
Modificare le librerie delle utenze può danneggiare altri software Python installati nel tuo sistema.
Non sarai in grado di eseguire multiple versioni di questo pacchetto ( o altri con lo stesso nome ).
Tipicamente, queste situazioni accadono quando manutieni svariati progetti Django. In questo caso, la miglior soluzione è usare venv. Questo tool ti permette di mantenere più ambienti Python isolati, ognuno con la propria copia delle librerie ed un namespace proprio.
apr 02, 2025