Chapter 14 – How to write reusable apps
最后更新于:2022-04-01 04:48:04
Chapter Still in Draft!!
This chapter is still a work in progress. You are welcome to browse and offer suggestions, but it is likely full of errors, jumbled and not recommended for use yet. You have been warned…
[TODO This is from the Django docs. Need to update to follow code examples in the book.]
This advanced tutorial begins where Tutorial 6 left off. Well be turning our Web-poll into a standalone Python package you can reuse in new projects and share with other people.
If you havent recently completed Tutorials 16, we encourage you to review these so that your example project matches the one described below.
[TOC]
## Reusability matters
Its a lot of work to design, build, test and maintain a web application. Many Python and Django projects share common problems. Wouldnt it be great if we could save some of this repeated work?
Reusability is the way of life in Python. [The Python Package Index (PyPI)](https://pypi.python.org/pypi) has a vast range of packages you can use in your own Python programs. Check out [Django Packages](https://www.djangopackages.com/) for existing reusable apps you could incorporate in your project. Django itself is also just a 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.
Lets say you were starting a new project that needed a polls app like the one weve been working on. How do you make this app reusable? Luckily, youre well on the way already. In Tutorial 3 , we saw how we could decouple polls from the project-level URLconf using an `include`. In this tutorial, well take further steps to make the app easy to use in new projects and ready to publish for others to install and use.
Package? App?
A Python [package](https://docs.python.org/tutorial/modules.html#packages) provides a way of grouping related Python code for easy reuse. A package contains one or more files of Python code (also known as modules).
A package can be imported with `import foo.bar` or `from foo import bar`. For a directory (like `polls`) to form a package, it must contain a special file `__init__.py`, even if this file is empty.
A Django *application* is just a Python package that is specifically intended for use in a Django project. An application may use common Django conventions, such as having `models`, `tests`, `urls`, and `views`submodules.
Later on we use the term *packaging* to describe the process of making a Python package easy for others to install. It can be a little confusing, we know.
## Your project and your reusable app
After the previous tutorials, our project should look like this:
~~~
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
polls/
__init__.py
admin.py
migrations/
__init__.py
0001_initial.py
models.py
static/
polls/
images/
background.gif
style.css
templates/
polls/
detail.html
index.html
results.html
tests.py
urls.py
views.py
templates/
admin/
base_site.html
~~~
You created `mysite/templates` in Tutorial 2 , 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.
The `polls` directory could now be copied into a new Django project and immediately reused. Its not quite ready to be published though. For that, we need to package the app to make it easy for others to install.
## Installing some prerequisites
The current state of Python packaging is a bit muddled with various tools. For this tutorial, were going to use [setuptools](https://pypi.python.org/pypi/setuptools) to build our package. Its the recommended packaging tool (merged with the `distribute`fork). Well also be using [pip](https://pypi.python.org/pypi/pip) to install and uninstall it. You should install these two packages now. You can install `setuptools` the same way.
## Packaging your app
Python *packaging* refers to preparing your app in a specific format that can be easily installed and used. Django itself is packaged very much like this. For a small app like polls, this process isnt too difficult.
1. First, create a parent directory for `polls`, outside of your Django project. Call this directory `django-polls`.
Choosing a name for your app
When choosing a name for your package, check resources like PyPI to avoid naming conflicts with existing packages. Its often useful to prepend `django-` to your module name when creating a package to distribute. This helps others looking for Django apps identify your app as Django specific.
Application labels (that is, the final part of the dotted path to application packages) *must* be unique in`INSTALLED_APPS`. Avoid using the same label as any of the Django contrib packages , for example `auth`, `admin`, or `messages`.
2. Move the `polls` directory into the `django-polls` directory.
3. Create a file `django-polls/README.rst` with the following contents:
~~~
# django-polls/README.rst
=====
Polls
=====
Polls is a simple 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 = [
...
'polls',
]
2. Include the polls URLconf in your project urls.py like this::
url(r'^polls/', include('polls.urls')),
3. Run `python manage.py migrate` to create the polls models.
4. Start the development server and visit http://127.0.0.1:8000/admin/
to create a poll (you'll need the Admin app enabled).
5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
~~~
4. Create a `django-polls/LICENSE` file. Choosing a license is beyond the scope of this tutorial, but suffice it to say that code released publicly without a license is *useless*. Django and many Django-compatible apps are distributed under the BSD license; however, youre free to pick your own license. Just be aware that your licensing choice will affect who is able to use your code.
5. Next well create a `setup.py` file which provides details about how to build and install the app. A full explanation of this file is beyond the scope of this tutorial, but the [setuptools docs](http://pythonhosted.org/setuptools/setuptools.html) have a good explanation. Create a file `django-polls/setup.py` with the following contents:
~~~
# django-polls/setup.py
import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-polls',
version='0.1',
packages=['polls'],
include_package_data=True,
license='BSD License', # example license
description='A simple Django app to conduct Web-based polls.',
long_description=README,
url='http://www.example.com/',
author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', # example license
'Operating System :: OS Independent',
'Programming Language :: Python',
# Replace these appropriately if you are stuck on Python 2.
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
~~~
6. Only Python modules and packages are included in the package by default. To include additional files, well need to create a `MANIFEST.in` file. The setuptools docs referred to in the previous step discuss this file in more details. To include the templates, the `README.rst` and our `LICENSE` file, create a file `django-polls/MANIFEST.in` with the following contents:
~~~
# django-polls/MANIFEST.in
include LICENSE
include README.rst
recursive-include polls/static *
recursive-include polls/templates *
~~~
7. Its optional, but recommended, to include detailed documentation with your app. Create an empty directory `django-polls/docs` for future documentation. Add an additional line to `django-polls/MANIFEST.in`:
~~~
recursive-include docs *
~~~
Note that the `docs` directory wont be included in your package unless you add some files to it. Many Django apps also provide their documentation online through sites like [readthedocs.org](https://readthedocs.org/).
8. Try building your package with `python setup.py sdist` (run from inside `django-polls`). This creates a directory called `dist` and builds your new package, `django-polls-0.1.tar.gz`.
For more information on packaging, see Pythons [Tutorial on Packaging and Distributing Projects](https://packaging.python.org/en/latest/distributing.html).
## Using your own package
Since we moved the `polls` directory out of the project, its no longer working. Well now fix this by installing our new `django-polls` package.
Installing as a user library
The following steps install `django-polls` as a user library. Per-user installs have a lot of advantages over installing the package system-wide, such as being usable on systems where you dont have administrator access as well as preventing the package from affecting system services and other users of the machine.
Note that per-user installations can still affect the behavior of system tools that run as that user, so`virtualenv` is a more robust solution (see below).
1. To install the package, use pip (you already installed it, right?):
~~~
pip install --user django-polls/dist/django-polls-0.1.tar.gz
~~~
2. With luck, your Django project should now work correctly again. Run the server again to confirm this.
3. To uninstall the package, use pip:
~~~
pip uninstall django-polls
~~~
## Publishing your app
Now that weve packaged and tested `django-polls`, its ready to share with the world! If this wasnt just an example, you could now:
* Email the package to a friend.
* Upload the package on your Web site.
* Post the package on a public repository, such as [the Python Package Index (PyPI)](https://pypi.python.org/pypi). [packaging.python.org](https://packaging.python.org/)has [a good tutorial](https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi) for doing this.
## Installing Python packages with virtualenv
Earlier, we installed the polls app as a user library. This has some disadvantages:
* Modifying the user libraries can affect other Python software on your system.
* You wont be able to run multiple versions of this package (or others with the same name).
Typically, these situations only arise once youre maintaining several Django projects. When they do, the best solution is to use [virtualenv](http://www.virtualenv.org/). This tool allows you to maintain multiple isolated Python environments, each with its own copy of the libraries and package namespace.
## Whats Next
Next we will be digging deeper into a subject common to many modern websites generating non-HTML data.