"Fossies" - the Fresh Open Source Software Archive

Member "Django-1.11.25/docs/intro/reusable-apps.txt" (1 Oct 2019, 12988 Bytes) of package /linux/www/Django-1.11.25.tar.gz:


As a special service "Fossies" has tried to format the requested text file into HTML format (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

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