reusable-apps.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. <https://pypi.python.org/pypi>`_ has a vast range of packages you can use in
  16. your own Python programs. Check out `Django Packages
  17. <https://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 <https://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 *application* is just a Python package that is specifically
  36. intended for use in a Django project. An application may use common Django
  37. conventions, such as having ``models``, ``tests``, ``urls``, and ``views``
  38. submodules.
  39. Later on we use the term *packaging* to describe the process of making a
  40. Python package easy for others to install. It can be a little confusing, we
  41. know.
  42. Your project and your reusable app
  43. ==================================
  44. After the previous tutorials, our project should look like this::
  45. mysite/
  46. manage.py
  47. mysite/
  48. __init__.py
  49. settings.py
  50. urls.py
  51. wsgi.py
  52. polls/
  53. __init__.py
  54. admin.py
  55. migrations/
  56. __init__.py
  57. 0001_initial.py
  58. models.py
  59. static/
  60. polls/
  61. images/
  62. background.gif
  63. style.css
  64. templates/
  65. polls/
  66. detail.html
  67. index.html
  68. results.html
  69. tests.py
  70. urls.py
  71. views.py
  72. templates/
  73. admin/
  74. base_site.html
  75. You created ``mysite/templates`` in :doc:`Tutorial 2 </intro/tutorial02>`,
  76. and ``polls/templates`` in :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps
  77. it is clearer why we chose to have separate template directories for the
  78. project and application: everything that is part of the polls application is in
  79. ``polls``. It makes the application self-contained and easier to drop into a
  80. new project.
  81. The ``polls`` directory could now be copied into a new Django project and
  82. immediately reused. It's not quite ready to be published though. For that, we
  83. need to package the app to make it easy for others to install.
  84. .. _installing-reusable-apps-prerequisites:
  85. Installing some prerequisites
  86. =============================
  87. The current state of Python packaging is a bit muddled with various tools. For
  88. this tutorial, we're going to use setuptools_ to build our package. It's the
  89. recommended packaging tool (merged with the ``distribute`` fork). We'll also be
  90. using `pip`_ to install and uninstall it. You should install these
  91. two packages now. If you need help, you can refer to :ref:`how to install
  92. Django with pip<installing-official-release>`. You can install ``setuptools``
  93. the same way.
  94. .. _setuptools: https://pypi.python.org/pypi/setuptools
  95. .. _pip: https://pypi.python.org/pypi/pip
  96. Packaging your app
  97. ==================
  98. Python *packaging* refers to preparing your app in a specific format that can
  99. be easily installed and used. Django itself is packaged very much like
  100. this. For a small app like polls, this process isn't too difficult.
  101. 1. First, create a parent directory for ``polls``, outside of your Django
  102. project. Call this directory ``django-polls``.
  103. .. admonition:: Choosing a name for your app
  104. When choosing a name for your package, check resources like PyPI to avoid
  105. naming conflicts with existing packages. It's often useful to prepend
  106. ``django-`` to your module name when creating a package to distribute.
  107. This helps others looking for Django apps identify your app as Django
  108. specific.
  109. Application labels (that is, the final part of the dotted path to
  110. application packages) *must* be unique in :setting:`INSTALLED_APPS`.
  111. Avoid using the same label as any of the Django :doc:`contrib packages
  112. </ref/contrib/index>`, for example ``auth``, ``admin``, or
  113. ``messages``.
  114. 2. Move the ``polls`` directory into the ``django-polls`` directory.
  115. 3. Create a file ``django-polls/README.rst`` with the following contents:
  116. .. snippet::
  117. :filename: django-polls/README.rst
  118. =====
  119. Polls
  120. =====
  121. Polls is a simple Django app to conduct Web-based polls. For each
  122. question, visitors can choose between a fixed number of answers.
  123. Detailed documentation is in the "docs" directory.
  124. Quick start
  125. -----------
  126. 1. Add "polls" to your INSTALLED_APPS setting like this::
  127. INSTALLED_APPS = [
  128. ...
  129. 'polls',
  130. ]
  131. 2. Include the polls URLconf in your project urls.py like this::
  132. url(r'^polls/', include('polls.urls')),
  133. 3. Run `python manage.py migrate` to create the polls models.
  134. 4. Start the development server and visit http://127.0.0.1:8000/admin/
  135. to create a poll (you'll need the Admin app enabled).
  136. 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.
  137. 4. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the
  138. scope of this tutorial, but suffice it to say that code released publicly
  139. without a license is *useless*. Django and many Django-compatible apps are
  140. distributed under the BSD license; however, you're free to pick your own
  141. license. Just be aware that your licensing choice will affect who is able
  142. to use your code.
  143. 5. Next we'll create a ``setup.py`` file which provides details about how to
  144. build and install the app. A full explanation of this file is beyond the
  145. scope of this tutorial, but the `setuptools docs
  146. <https://pythonhosted.org/setuptools/setuptools.html>`_ have a good
  147. explanation. Create a file ``django-polls/setup.py`` with the following
  148. contents:
  149. .. snippet::
  150. :filename: django-polls/setup.py
  151. import os
  152. from setuptools import setup
  153. with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
  154. README = readme.read()
  155. # allow setup.py to be run from any path
  156. os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
  157. setup(
  158. name='django-polls',
  159. version='0.1',
  160. packages=['polls'],
  161. include_package_data=True,
  162. license='BSD License', # example license
  163. description='A simple Django app to conduct Web-based polls.',
  164. long_description=README,
  165. url='https://www.example.com/',
  166. author='Your Name',
  167. author_email='yourname@example.com',
  168. classifiers=[
  169. 'Environment :: Web Environment',
  170. 'Framework :: Django',
  171. 'Framework :: Django :: X.Y', # replace "X.Y" as appropriate
  172. 'Intended Audience :: Developers',
  173. 'License :: OSI Approved :: BSD License', # example license
  174. 'Operating System :: OS Independent',
  175. 'Programming Language :: Python',
  176. # Replace these appropriately if you are stuck on Python 2.
  177. 'Programming Language :: Python :: 3',
  178. 'Programming Language :: Python :: 3.4',
  179. 'Programming Language :: Python :: 3.5',
  180. 'Topic :: Internet :: WWW/HTTP',
  181. 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
  182. ],
  183. )
  184. 6. Only Python modules and packages are included in the package by default. To
  185. include additional files, we'll need to create a ``MANIFEST.in`` file. The
  186. setuptools docs referred to in the previous step discuss this file in more
  187. details. To include the templates, the ``README.rst`` and our ``LICENSE``
  188. file, create a file ``django-polls/MANIFEST.in`` with the following
  189. contents:
  190. .. snippet::
  191. :filename: django-polls/MANIFEST.in
  192. include LICENSE
  193. include README.rst
  194. recursive-include polls/static *
  195. recursive-include polls/templates *
  196. 7. It's optional, but recommended, to include detailed documentation with your
  197. app. Create an empty directory ``django-polls/docs`` for future
  198. documentation. Add an additional line to ``django-polls/MANIFEST.in``::
  199. recursive-include docs *
  200. Note that the ``docs`` directory won't be included in your package unless
  201. you add some files to it. Many Django apps also provide their documentation
  202. online through sites like `readthedocs.org <https://readthedocs.org>`_.
  203. 8. Try building your package with ``python setup.py sdist`` (run from inside
  204. ``django-polls``). This creates a directory called ``dist`` and builds your
  205. new package, ``django-polls-0.1.tar.gz``.
  206. For more information on packaging, see Python's `Tutorial on Packaging and
  207. Distributing Projects <https://packaging.python.org/en/latest/distributing.html>`_.
  208. Using your own package
  209. ======================
  210. Since we moved the ``polls`` directory out of the project, it's no longer
  211. working. We'll now fix this by installing our new ``django-polls`` package.
  212. .. admonition:: Installing as a user library
  213. The following steps install ``django-polls`` as a user library. Per-user
  214. installs have a lot of advantages over installing the package system-wide,
  215. such as being usable on systems where you don't have administrator access
  216. as well as preventing the package from affecting system services and other
  217. users of the machine.
  218. Note that per-user installations can still affect the behavior of system
  219. tools that run as that user, so ``virtualenv`` is a more robust solution
  220. (see below).
  221. 1. To install the package, use pip (you already :ref:`installed it
  222. <installing-reusable-apps-prerequisites>`, right?)::
  223. pip install --user django-polls/dist/django-polls-0.1.tar.gz
  224. 2. With luck, your Django project should now work correctly again. Run the
  225. server again to confirm this.
  226. 3. To uninstall the package, use pip::
  227. pip uninstall django-polls
  228. .. _pip: https://pypi.python.org/pypi/pip
  229. Publishing your app
  230. ===================
  231. Now that we've packaged and tested ``django-polls``, it's ready to share with
  232. the world! If this wasn't just an example, you could now:
  233. * Email the package to a friend.
  234. * Upload the package on your website.
  235. * Post the package on a public repository, such as `the Python Package Index
  236. (PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good
  237. tutorial <https://packaging.python.org/en/latest/distributing.html#uploading-your-project-to-pypi>`_
  238. for doing this.
  239. Installing Python packages with virtualenv
  240. ==========================================
  241. Earlier, we installed the polls app as a user library. This has some
  242. disadvantages:
  243. * Modifying the user libraries can affect other Python software on your system.
  244. * You won't be able to run multiple versions of this package (or others with
  245. the same name).
  246. Typically, these situations only arise once you're maintaining several Django
  247. projects. When they do, the best solution is to use `virtualenv
  248. <http://www.virtualenv.org/>`_. This tool allows you to maintain multiple
  249. isolated Python environments, each with its own copy of the libraries and
  250. package namespace.