Django Official tutorial (10) "Advanced content: Writing reusable Applications"

Source: Internet
Author: User
Tags parent directory install django virtualenv in python
Advanced content: How to write reusable applications

This article starts at the end of part seventh (en) of the tutorial. We will translate the previously written survey application into a separate Python package that can be reused in new projects and shared with others.

If you have not completed tutorial 1-7, we encourage you to complete them again so that you can match your project with the following tutorial. The problem of reusability

Designing, building, testing, and maintaining WEB applications requires a lot of work. Many Python and Django projects will face this problem. It would be great if we could save a little bit of repetitive work.

Reusability is deep in Python's design philosophy. The Python Package index (PyPI) has a large number of packages that you can use in your own program. View the classification for Django, where the bread contains existing reusable applications that you can use in your own projects. Django itself is just a Python package. This means that you can make the most of your existing Python packages or Django applications to help you complete your WEB project. You just need to write some special parts.

Let's say your new project needs a voting application similar to what we've written before. How to make this application reusable. Luckily, you are on the right path. In the third part of the tutorial (en), we learned how to detach a voting application from a master project by using include in a URL profile at the project level. In this tutorial, we will take further steps to make the application easy to use in new projects and to be posted to others for installation and use.

package. Application.

The Python Package (package) provides an organizational way to group Python code into dependencies, a way that improves reusability. The package contains one or more Python code files (also known as "modules").

Packages can be imported through the import foo.bar or from foo import bar . For packages organized by a directory (such as polls), there must be a special file _init_.pyin the directory, even if the file is empty.

Django apps are just a Python package, but only for Django projects. Applications typically follow common Django conventions, such as models (model),tests (test),URLs (URLs) , and Views (view) modules.

We then use the term packaging to describe the process of "making a Python package that can be used by someone else." This may be a bit confusing. The meaning of this sentence in the original text is that the package will be used as verbs and nouns at the same time, which may cause difficulty in reading, but it will not be translated into Chinese because we have the word packing ^_^. your project and your reusable application

After finishing the previous tutorial, our project should be 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 polls/
                images/
                    background.gif
                style.css
                templates/
                polls/ index.html
                results.html
        tests.py
        urls.py
        views.py
            templates/admin/base_ Site.html

You created the mysite/templatesin section seventh (en) of the tutorial and created the polls/templatesin Part III (EN) of the tutorial. Now you may have a clearer idea of why we chose to separate the project from the template directory for the application: All the voting applications are in use. This makes the application fully inclusive and easier to use for new projects.

The polls directory can now be replicated to a new Django project and can be reused immediately. But there are a few places to be prepared for the release. We need packaged applications to make it easier for others to install. install some prerequisite tools

The Python packaged solution is a bit confusing at the moment because there are a variety of different tools. In this tutorial, we will use Setuptools to build our packages. This is the recommended packaging tool (after merging with the distribute branch). However, use the PIP to install and uninstall it. You should now install these two packages. If you need help, you can refer to how to use the PIP to install Django. You can install Setuptoolsin the same way. Pack Your Apps

Python packaging refers to making your application in a specific format so that it can be easily installed and used. Django itself is packaged according to this rule. For a small application, such as our voting application, this process is not too difficult.

1. First, create a parent directory for the polls directory outside of your Django project, named Django-polls.

Choose the name you apply

When choosing a name for your package, remember to check the contents of the PyPI to avoid conflicts with existing packages. Using django- as a module name prefix is useful, and will help people looking for Django applications to identify which packages are for Django.

Applying a label (that is, the last part of the module path separated by dots) must be unique in the Installed_apps . Avoid using the same tags as the Django contrib package, such as auth,admin, or message.

2. Move polls directory to django-polls directory

3. Create the file Django-polls/readme.rstand write to the following content.

# Django-polls/readme.rst

=====
polls
=====

polls is a simple Django app. conduct web-based. 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 as 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 en abled).

5. Visit http://127.0.0.1:8000/polls/to participate in the poll.

4. Create django-polls/license files. Choosing a license is beyond the scope of this guide, but it can be said that publicly published code without a license is useless. Django and many Django-compliant applications are released under BSD license; however, you are free to choose your own license. Just be aware that your permission choices will affect who can use your code.

5. Next we will create a setup.py file that provides details on how to create and install the application. The complete explanation of this file is beyond the scope of this article, but the Setuptools docs document has a great explanation for it. Create a django-polls/setup.py file that contains the following:

# django-polls/setup.py import os from setuptools import find_packages, Setup with open (Os.path.join os.path.dirname (__f ile__), ' Readme.rst ') as Readme:readme = Readme.read () # enables setup.py to run anywhere Os.chdir (os.path.normpath

(Os.path.abspath (__file__), Os.pardir)) Setup (name= ' django-polls ', version= ' 0.1 ', packages=find_packages (), Include_package_data=true, Licens E= ' BSD License ', # example License description= ' A simple Django App. conduct web-based. ', polls N=readme, url= ' https://www.example.com/', author= ' Your Name ', author_email= ' yourname@example.com ', classif iers=[' Environment:: Web Environment ', ' Framework:: Django ', ' Framework:: Django:: x.y ', # R  Eplace "x.y" as appropriate ' intended audience:: Developers ', ' License:: OSI Approved:: BSD License ', # example License ' operating System:: OS independent ', ' Programming Language:: Python ', # Replace These appropriately if your are stuck on Python 2. ' Programming Language:: Python:: 3 ', ' Programming Language:: Python:: 3.4 ', ' Programming Language:: P 
Ython:: 3.5 ', ' Topic:: Internet:: Www/http ', ' Topic:: Internet:: www/http:: Dynamic Content ',], )

6. The generated packaging file contains only Python modules and packages by default. If you want to include additional files, we need to create a manifest.in file. More details are presented in the Setuptools documentation mentioned in the previous step. To include templates , our readme.rst , and LICENSE files, create django-polls/manifest.in files that contain the following:

# django-polls/manifest.in

include LICENSE
include Readme.rst
recursive-include polls/static *
Recursive-include Polls/templates *

7. This is an optional step, but we recommend that you complete this step. Package The application's detailed documentation together. Create an empty directory Django-polls/docsfor future documents and add a row to the django-polls/manifest.in :

Recursive-include Docs *

Note that if there is no file in the Docs directory, it will not be packaged. Many Django applications also provide online documentation through hosted Web sites, such as readthedocs.org.

8. Try packaging (run in the django/polls directory) with the python setup.py sdist command. This creates a directory named Dist and creates a packaged file django-polls-0.1.tar.gzin it.

For more information on packaging, see the Python Tutorial: Tutorial on packaging and distributing Projects. use your bag.

Since we've removed the polls directory from the project, it's no longer working. We now solve this problem by installing a new django/polls package.

Install as User library

The following steps will install Django/polls as a user library. Compared to a global installation, a single user installation has many benefits, such as the ability to use it in systems that do not have administrator privileges, and to prevent packages from being installed that affect system services or other users on the machine.

Note that a single user installation can still affect other user's system tools, so virtualenv is a more powerful solution (see article).

1. To install this package, you need to use the PIP (you have installed it, right?). )

Pip Install--user django-polls/dist/django-polls-0.1.tar.gz

2. If you're lucky, your Django project should be working properly now. Run the server again to confirm.

3. To uninstall this package, use PIP.

Pip Uninstall Django-polls
Publish your application

Now we have packaged and tested the django-pollsand are ready to share it with everyone. If this is not an example, you can now: send this packet to a friend by e-mail. Upload the package to your own website. Publish your package on a public library, such as the Python Package index (PyPI). There is a great tutorial on the packaging.python.org. Installing the Python pack with virtualenv

Before, we installed the voting application as a user library. Here are some disadvantages:
-Modifying the user library may affect other Python software in your system.
-You will not be able to use multiple versions of the package (or other packages of the same name) at the same time.

Typically, these situations only occur when you are managing multiple Django projects at the same time. When this happens, the best way is to use virtualenv. This tool allows you to maintain multiple separate Python environments, each of which replicates a dedicated library and package namespace (package namespace).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.