reusable-apps.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. =============================================
  2. Advanced tutorial: How to write reusable apps
  3. =============================================
  4. This advanced tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>`
  5. left off. We'll be turning our Web-poll into a standalone Python package
  6. you can reuse in new projects and share with other people.
  7. If you haven't recently completed Tutorials 1–6, 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. Your project and 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. static/
  57. style.css
  58. images/
  59. background.gif
  60. templates/
  61. polls/
  62. detail.html
  63. index.html
  64. results.html
  65. urls.py
  66. views.py
  67. templates/
  68. admin/
  69. base_site.html
  70. You created ``mysite/templates`` in :doc:`Tutorial 2 </intro/tutorial02>`,
  71. and ``polls/templates`` in :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps
  72. it is clearer why we chose to have separate template directories for the
  73. project and application: everything that is part of the polls application is in
  74. ``polls``. It makes the application self-contained and easier to drop into a
  75. new project.
  76. The ``polls`` directory could now be copied into a new Django project and
  77. immediately reused. It's not quite ready to be published though. For that, we
  78. need to package the app to make it easy for others to install.
  79. .. _installing-reusable-apps-prerequisites:
  80. Installing some prerequisites
  81. =============================
  82. The current state of Python packaging is a bit muddled with various tools. For
  83. this tutorial, we're going to use distribute_ to build our package. It's a
  84. community-maintained fork of the older ``setuptools`` project. We'll also be
  85. using `pip`_ to uninstall it after we're finished. You should install these
  86. two packages now. If you need help, you can refer to :ref:`how to install
  87. Django with pip<installing-official-release>`. You can install ``distribute``
  88. the same way.
  89. .. _distribute: http://pypi.python.org/pypi/distribute
  90. .. _pip: http://pypi.python.org/pypi/pip
  91. Packaging your app
  92. ==================
  93. Python *packaging* refers to preparing your app in a specific format that can
  94. be easily installed and used. Django itself is packaged very much like
  95. this. For a small app like polls, this process isn't too difficult.
  96. 1. First, create a parent directory for ``polls``, outside of your Django
  97. project. Call this directory ``django-polls``.
  98. .. admonition:: Choosing a name for your app
  99. When choosing a name for your package, check resources like PyPI to avoid
  100. naming conflicts with existing packages. It's often useful to prepend
  101. ``django-`` to your module name when creating a package to distribute.
  102. This helps others looking for Django apps identify your app as Django
  103. specific.
  104. 2. Move the ``polls`` directory into the ``django-polls`` directory.
  105. 3. Create a file ``django-polls/README.txt`` with the following contents::
  106. =====
  107. Polls
  108. =====
  109. Polls is a simple Django app to conduct Web-based polls. For each
  110. question, visitors can choose between a fixed number of answers.
  111. Detailed documentation is in the "docs" directory.
  112. Quick start
  113. -----------
  114. 1. Add "polls" to your INSTALLED_APPS setting like this::
  115. INSTALLED_APPS = (
  116. ...
  117. 'polls',
  118. )
  119. 2. Include the polls URLconf in your project urls.py like this::
  120. url(r'^polls/', include('polls.urls')),
  121. 3. Run `python manage.py syncdb` to create the polls models.
  122. 4. Start the development server and visit http://127.0.0.1:8000/admin/
  123. to create a poll (you'll need the Admin app enabled).
  124. 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
  125. 4. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
  126. scope of this tutorial, but suffice it to say that code released publicly
  127. without a license is *useless*. Django and many Django-compatible apps are
  128. distributed under the BSD license; however, you're free to pick your own
  129. license. Just be aware that your licensing choice will affect who is able
  130. to use your code.
  131. 5. Next we'll create a ``setup.py`` file which provides details about how to
  132. build and install the app. A full explanation of this file is beyond the
  133. scope of this tutorial, but the `distribute docs
  134. <http://packages.python.org/distribute/setuptools.html>`_ have a good explanation.
  135. Create a file ``django-polls/setup.py`` with the following contents::
  136. import os
  137. from setuptools import setup
  138. README = open(os.path.join(os.path.dirname(__file__), 'README.txt')).read()
  139. # allow setup.py to be run from any path
  140. os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
  141. setup(
  142. name = 'django-polls',
  143. version = '0.1',
  144. packages = ['polls'],
  145. include_package_data = True,
  146. license = 'BSD License', # example license
  147. description = 'A simple Django app to conduct Web-based polls.',
  148. long_description = README,
  149. url = 'http://www.example.com/',
  150. author = 'Your Name',
  151. author_email = 'yourname@example.com',
  152. classifiers = [
  153. 'Environment :: Web Environment',
  154. 'Framework :: Django',
  155. 'Intended Audience :: Developers',
  156. 'License :: OSI Approved :: BSD License', # example license
  157. 'Operating System :: OS Independent',
  158. 'Programming Language :: Python',
  159. 'Programming Language :: Python :: 2.6',
  160. 'Programming Language :: Python :: 2.7',
  161. 'Topic :: Internet :: WWW/HTTP',
  162. 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
  163. ],
  164. )
  165. .. admonition:: I thought you said we were going to use ``distribute``?
  166. Distribute is a drop-in replacement for ``setuptools``. Even though we
  167. appear to import from ``setuptools``, since we have ``distribute``
  168. installed, it will override the import.
  169. 6. Only Python modules and packages are included in the package by default. To
  170. include additional files, we'll need to create a ``MANIFEST.in`` file. The
  171. distribute docs referred to in the previous step discuss this file in more
  172. details. To include the templates and our LICENSE file, create a file
  173. ``django-polls/MANIFEST.in`` with the following contents::
  174. include LICENSE
  175. recursive-include polls/templates *
  176. 7. It's optional, but recommended, to include detailed documentation with your
  177. app. Create an empty directory ``django-polls/docs`` for future
  178. documentation. Add an additional line to ``django-polls/MANIFEST.in``::
  179. recursive-include docs *
  180. Note that the ``docs`` directory won't be included in your package unless
  181. you add some files to it. Many Django apps also provide their documentation
  182. online through sites like `readthedocs.org <http://readthedocs.org>`_.
  183. 8. Try building your package with ``python setup.py sdist`` (run from inside
  184. ``django-polls``). This creates a directory called ``dist`` and builds your
  185. new package, ``django-polls-0.1.tar.gz``.
  186. For more information on packaging, see `The Hitchhiker's Guide to Packaging
  187. <http://guide.python-distribute.org/quickstart.html>`_.
  188. Using your own package
  189. ======================
  190. Since we moved the ``polls`` directory out of the project, it's no longer
  191. working. We'll now fix this by installing our new ``django-polls`` package.
  192. .. admonition:: Installing as a user library
  193. The following steps install ``django-polls`` as a user library. Per-user
  194. installs have a lot of advantages over installing the package system-wide,
  195. such as being usable on systems where you don't have administrator access
  196. as well as preventing the package from affecting system services and other
  197. users of the machine. Python 2.6 added support for user libraries, so if
  198. you are using an older version this won't work, but Django 1.5 requires
  199. Python 2.6 or newer anyway.
  200. Note that per-user installations can still affect the behavior of system
  201. tools that run as that user, so ``virtualenv`` is a more robust solution
  202. (see below).
  203. 1. Inside ``django-polls/dist``, untar the new package
  204. ``django-polls-0.1.tar.gz`` (e.g. ``tar xzvf django-polls-0.1.tar.gz``). If
  205. you're using Windows, you can download the command-line tool bsdtar_ to do
  206. this, or you can use a GUI-based tool such as 7-zip_.
  207. 2. Change into the directory created in step 1 (e.g. ``cd django-polls-0.1``).
  208. 3. If you're using GNU/Linux, Mac OS X or some other flavor of Unix, enter the
  209. command ``python setup.py install --user`` at the shell prompt. If you're
  210. using Windows, start up a command shell and run the command
  211. ``setup.py install --user``.
  212. With luck, your Django project should now work correctly again. Run the
  213. server again to confirm this.
  214. 4. To uninstall the package, use pip (you already :ref:`installed it
  215. <installing-reusable-apps-prerequisites>`, right?)::
  216. pip uninstall django-polls
  217. .. _bsdtar: http://gnuwin32.sourceforge.net/packages/bsdtar.htm
  218. .. _7-zip: http://www.7-zip.org/
  219. .. _pip: http://pypi.python.org/pypi/pip
  220. Publishing your app
  221. ===================
  222. Now that we've packaged and tested ``django-polls``, it's ready to share with
  223. the world! If this wasn't just an example, you could now:
  224. * Email the package to a friend.
  225. * Upload the package on your Web site.
  226. * Post the package on a public repository, such as `The Python Package Index
  227. (PyPI) <http://guide.python-distribute.org/contributing.html#pypi-info>`_.
  228. For more information on PyPI, see the `Quickstart
  229. <http://guide.python-distribute.org/quickstart.html#register-your-package-with-the-python-package-index-pypi>`_
  230. section of The Hitchhiker's Guide to Packaging. One detail this guide mentions
  231. is choosing the license under which your code is distributed.
  232. Installing Python packages with virtualenv
  233. ==========================================
  234. Earlier, we installed the polls app as a user library. This has some
  235. disadvantages:
  236. * Modifying the user libraries can affect other Python software on your system.
  237. * You won't be able to run multiple versions of this package (or others with
  238. the same name).
  239. Typically, these situations only arise once you're maintaining several Django
  240. projects. When they do, the best solution is to use `virtualenv
  241. <http://www.virtualenv.org/>`_. This tool allows you to maintain multiple
  242. isolated Python environments, each with its own copy of the libraries and
  243. package namespace.