reusable-apps.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. =============================================
  2. Advanced tutorial: How to write reusable apps
  3. =============================================
  4. This advanced tutorial begins where :doc:`Tutorial 5 </intro/tutorial05>` left
  5. off. We'll be turning our Web-poll into a standalone Python package you can
  6. reuse in new projects and share with other people.
  7. If you haven't recently completed Tutorials 1–5, we encourage you to review
  8. these so that your example project matches the one described below.
  9. Reusability matters
  10. ===================
  11. It's a lot of work to design, build, test and maintain a web application. Many
  12. Python and Django projects share common problems. Wouldn't it be great if we
  13. could save some of this repeated work?
  14. Reusability is the way of life in Python. `The Python Package Index (PyPI)
  15. <http://guide.python-distribute.org/contributing.html#pypi-info>`_ has a vast
  16. range of packages you can use in your own Python programs. Check out `Django
  17. Packages <http://www.djangopackages.com>`_ for existing reusable apps you could
  18. incorporate in your project. Django itself is also just a Python package. This
  19. means that you can take existing Python packages or Django apps and compose
  20. them into your own web project. You only need to write the parts that make
  21. your project unique.
  22. Let's say you were starting a new project that needed a polls app like the one
  23. we've been working on. How do you make this app reusable? Luckily, you're well
  24. on the way already. In :doc:`Tutorial 3 </intro/tutorial03>`, we saw how we
  25. could decouple polls from the project-level URLconf using an ``include``.
  26. In this tutorial, we'll take further steps to make the app easy to use in new
  27. projects and ready to publish for others to install and use.
  28. .. admonition:: Package? App?
  29. A Python `package <http://docs.python.org/tutorial/modules.html#packages>`_
  30. provides a way of grouping related Python code for easy reuse. A package
  31. contains one or more files of Python code (also known as "modules").
  32. A package can be imported with ``import foo.bar`` or ``from foo import
  33. bar``. For a directory (like ``polls``) to form a package, it must contain
  34. a special file ``__init__.py``, even if this file is empty.
  35. A Django *app* is just a Python package that is specifically intended for
  36. use in a Django project. An app may also use common Django conventions,
  37. such as having a ``models.py`` file.
  38. Later on we use the term *packaging* to describe the process of making a
  39. Python package easy for others to install. It can be a little confusing, we
  40. know.
  41. Completing your reusable app
  42. ============================
  43. After the previous tutorials, our project should look like this::
  44. mysite/
  45. manage.py
  46. mysite/
  47. __init__.py
  48. settings.py
  49. urls.py
  50. wsgi.py
  51. polls/
  52. __init__.py
  53. admin.py
  54. models.py
  55. tests.py
  56. urls.py
  57. views.py
  58. You also have a directory somewhere called ``mytemplates`` which you created in
  59. :doc:`Tutorial 2 </intro/tutorial02>`. You specified its location in the
  60. TEMPLATE_DIRS setting. This directory should look like this::
  61. mytemplates/
  62. admin/
  63. base_site.html
  64. polls/
  65. detail.html
  66. index.html
  67. results.html
  68. The polls app is already a Python package, thanks to the ``polls/__init__.py``
  69. file. That's a great start, but we can't just pick up this package and drop it
  70. into a new project. The polls templates are currently stored in the
  71. project-wide ``mytemplates`` directory. To make the app self-contained, it
  72. should also contain the necessary templates.
  73. Inside the ``polls`` app, create a new ``templates`` directory. Now move the
  74. ``polls`` template directory from ``mytemplates`` into the new
  75. ``templates``. Your project should now look like this::
  76. mysite/
  77. manage.py
  78. mysite/
  79. __init__.py
  80. settings.py
  81. urls.py
  82. wsgi.py
  83. polls/
  84. admin.py
  85. __init__.py
  86. models.py
  87. templates/
  88. polls/
  89. detail.html
  90. index.html
  91. results.html
  92. tests.py
  93. urls.py
  94. views.py
  95. Your project-wide templates directory should now look like this::
  96. mytemplates/
  97. admin/
  98. base_site.html
  99. Looking good! Now would be a good time to confirm that your polls application
  100. still works correctly. How does Django know how to find the new location of
  101. the polls templates even though we didn't modify :setting:`TEMPLATE_DIRS`?
  102. Django has a :setting:`TEMPLATE_LOADERS` setting which contains a list
  103. of callables that know how to import templates from various sources. One of
  104. the defaults is :class:`django.template.loaders.app_directories.Loader` which
  105. looks for a "templates" subdirectory in each of the :setting:`INSTALLED_APPS`.
  106. The ``polls`` directory could now be copied into a new Django project and
  107. immediately reused. It's not quite ready to be published though. For that, we
  108. need to package the app to make it easy for others to install.
  109. .. admonition:: Why nested?
  110. Why create a ``polls`` directory under ``templates`` when we're
  111. already inside the polls app? This directory is needed to avoid conflicts in
  112. Django's ``app_directories`` template loader. For example, if two
  113. apps had a template called ``base.html``, without the extra directory it
  114. wouldn't be possible to distinguish between the two. It's a good convention
  115. to use the name of your app for this directory.
  116. .. _installing-reusable-apps-prerequisites:
  117. Installing some prerequisites
  118. =============================
  119. The current state of Python packaging is a bit muddled with various tools. For
  120. this tutorial, we're going to use distribute_ to build our package. It's a
  121. community-maintained fork of the older ``setuptools`` project. We'll also be
  122. using `pip`_ to uninstall it after we're finished. You should install these
  123. two packages now. If you need help, you can refer to :ref:`how to install
  124. Django with pip<installing-official-release>`. You can install ``distribute``
  125. the same way.
  126. .. _distribute: http://pypi.python.org/pypi/distribute
  127. .. _pip: http://pypi.python.org/pypi/pip
  128. Packaging your app
  129. ==================
  130. Python *packaging* refers to preparing your app in a specific format that can
  131. be easily installed and used. Django itself is packaged very much like
  132. this. For a small app like polls, this process isn't too difficult.
  133. 1. First, create a parent directory for ``polls``, outside of your Django
  134. project. Call this directory ``django-polls``.
  135. .. admonition:: Choosing a name for your app
  136. When choosing a name for your package, check resources like PyPI to avoid
  137. naming conflicts with existing packages. It's often useful to prepend
  138. ``django-`` to your module name when creating a package to distribute.
  139. This helps others looking for Django apps identify your app as Django
  140. specific.
  141. 2. Move the ``polls`` directory into the ``django-polls`` directory.
  142. 3. Create a file ``django-polls/README.txt`` with the following contents::
  143. =====
  144. Polls
  145. =====
  146. Polls is a simple Django app to conduct Web-based polls. For each
  147. question, visitors can choose between a fixed number of answers.
  148. Detailed documentation is in the "docs" directory.
  149. Quick start
  150. -----------
  151. 1. Add "polls" to your INSTALLED_APPS setting like this::
  152. INSTALLED_APPS = (
  153. ...
  154. 'polls',
  155. )
  156. 2. Include the polls URLconf in your project urls.py like this::
  157. url(r'^polls/', include('polls.urls')),
  158. 3. Run `python manage.py syncdb` to create the polls models.
  159. 4. Start the development server and visit http://127.0.0.1:8000/admin/
  160. to create a poll (you'll need the Admin app enabled).
  161. 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
  162. 4. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
  163. scope of this tutorial, but suffice it to say that code released publicly
  164. without a license is *useless*. Django and many Django-compatible apps are
  165. distributed under the BSD license; however, you're free to pick your own
  166. license. Just be aware that your licensing choice will affect who is able
  167. to use your code.
  168. 5. Next we'll create a ``setup.py`` file which provides details about how to
  169. build and install the app. A full explanation of this file is beyond the
  170. scope of this tutorial, but the `distribute docs
  171. <http://packages.python.org/distribute/setuptools.html>`_ have a good explanation.
  172. Create a file ``django-polls/setup.py`` with the following contents::
  173. import os
  174. from setuptools import setup
  175. README = open(os.path.join(os.path.dirname(__file__), 'README.txt')).read()
  176. # allow setup.py to be run from any path
  177. os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
  178. setup(
  179. name = 'django-polls',
  180. version = '0.1',
  181. packages = ['polls'],
  182. include_package_data = True,
  183. license = 'BSD License', # example license
  184. description = 'A simple Django app to conduct Web-based polls.',
  185. long_description = README,
  186. url = 'http://www.example.com/',
  187. author = 'Your Name',
  188. author_email = 'yourname@example.com',
  189. classifiers = [
  190. 'Environment :: Web Environment',
  191. 'Framework :: Django',
  192. 'Intended Audience :: Developers',
  193. 'License :: OSI Approved :: BSD License', # example license
  194. 'Operating System :: OS Independent',
  195. 'Programming Language :: Python',
  196. 'Programming Language :: Python :: 2.6',
  197. 'Programming Language :: Python :: 2.7',
  198. 'Topic :: Internet :: WWW/HTTP',
  199. 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
  200. ],
  201. )
  202. .. admonition:: I thought you said we were going to use ``distribute``?
  203. Distribute is a drop-in replacement for ``setuptools``. Even though we
  204. appear to import from ``setuptools``, since we have ``distribute``
  205. installed, it will override the import.
  206. 6. Only Python modules and packages are included in the package by default. To
  207. include additional files, we'll need to create a ``MANIFEST.in`` file. The
  208. distribute docs referred to in the previous step discuss this file in more
  209. details. To include the templates and our LICENSE file, create a file
  210. ``django-polls/MANIFEST.in`` with the following contents::
  211. include LICENSE
  212. recursive-include polls/templates *
  213. 7. It's optional, but recommended, to include detailed documentation with your
  214. app. Create an empty directory ``django-polls/docs`` for future
  215. documentation. Add an additional line to ``django-polls/MANIFEST.in``::
  216. recursive-include docs *
  217. Note that the ``docs`` directory won't be included in your package unless
  218. you add some files to it. Many Django apps also provide their documentation
  219. online through sites like `readthedocs.org <http://readthedocs.org>`_.
  220. 8. Try building your package with ``python setup.py sdist`` (run from inside
  221. ``django-polls``). This creates a directory called ``dist`` and builds your
  222. new package, ``django-polls-0.1.tar.gz``.
  223. For more information on packaging, see `The Hitchhiker's Guide to Packaging
  224. <http://guide.python-distribute.org/quickstart.html>`_.
  225. Using your own package
  226. ======================
  227. Since we moved the ``polls`` directory out of the project, it's no longer
  228. working. We'll now fix this by installing our new ``django-polls`` package.
  229. .. admonition:: Installing as a user library
  230. The following steps install ``django-polls`` as a user library. Per-user
  231. installs have a lot of advantages over installing the package system-wide,
  232. such as being usable on systems where you don't have administrator access
  233. as well as preventing the package from affecting system services and other
  234. users of the machine. Python 2.6 added support for user libraries, so if
  235. you are using an older version this won't work, but Django 1.5 requires
  236. Python 2.6 or newer anyway.
  237. Note that per-user installations can still affect the behavior of system
  238. tools that run as that user, so ``virtualenv`` is a more robust solution
  239. (see below).
  240. 1. Inside ``django-polls/dist``, untar the new package
  241. ``django-polls-0.1.tar.gz`` (e.g. ``tar xzvf django-polls-0.1.tar.gz``). If
  242. you're using Windows, you can download the command-line tool bsdtar_ to do
  243. this, or you can use a GUI-based tool such as 7-zip_.
  244. 2. Change into the directory created in step 1 (e.g. ``cd django-polls-0.1``).
  245. 3. If you're using GNU/Linux, Mac OS X or some other flavor of Unix, enter the
  246. command ``python setup.py install --user`` at the shell prompt. If you're
  247. using Windows, start up a command shell and run the command
  248. ``setup.py install --user``.
  249. With luck, your Django project should now work correctly again. Run the
  250. server again to confirm this.
  251. 4. To uninstall the package, use pip (you already :ref:`installed it
  252. <installing-reusable-apps-prerequisites>`, right?)::
  253. pip uninstall django-polls
  254. .. _bsdtar: http://gnuwin32.sourceforge.net/packages/bsdtar.htm
  255. .. _7-zip: http://www.7-zip.org/
  256. .. _pip: http://pypi.python.org/pypi/pip
  257. Publishing your app
  258. ===================
  259. Now that we've packaged and tested ``django-polls``, it's ready to share with
  260. the world! If this wasn't just an example, you could now:
  261. * Email the package to a friend.
  262. * Upload the package on your Web site.
  263. * Post the package on a public repository, such as `The Python Package Index
  264. (PyPI) <http://guide.python-distribute.org/contributing.html#pypi-info>`_.
  265. For more information on PyPI, see the `Quickstart
  266. <http://guide.python-distribute.org/quickstart.html#register-your-package-with-the-python-package-index-pypi>`_
  267. section of The Hitchhiker's Guide to Packaging. One detail this guide mentions
  268. is choosing the license under which your code is distributed.
  269. Installing Python packages with virtualenv
  270. ==========================================
  271. Earlier, we installed the polls app as a user library. This has some
  272. disadvantages:
  273. * Modifying the user libraries can affect other Python software on your system.
  274. * You won't be able to run multiple versions of this package (or others with
  275. the same name).
  276. Typically, these situations only arise once you're maintaining several Django
  277. projects. When they do, the best solution is to use `virtualenv
  278. <http://www.virtualenv.org/>`_. This tool allows you to maintain multiple
  279. isolated Python environments, each with its own copy of the libraries and
  280. package namespace.