Comprehensive analysis of project deployment techniques in Python's Django Framework 1th/2 page _python

Source: Internet
Author: User
Tags install django mercurial pip install django python script using git virtual environment virtualenv

The project starts out as a critical moment, and the choice can have a long-term impact on the project. There are a lot of tutorials on how to get started with the Django framework, but there's little discussion about how to use Django professionally, or how to use industry-recognized best practices to ensure that your project continues to grow in size. Planning ahead makes it easier for you (and all your co-workers) to move forward.

At the end of the article, you will have

    • A fully functional Django 1.6 project
    • All resources controlled by source code (using Git or mercurial)
    • Automatic regression and unit testing (using the UnitTest library)
    • An installation project that is independent of a specific environment (using VIRTUALENV)
    • Automated deployment and testing (using fabric)
    • Automatic database migration (using south)
    • A scale your site's development workflow

Except for the first part of the official tutorials in other parts of the tutorial. They should be like this. If you want to start a new, production-ready Django 1.6 project, please continue to look down.

Prerequisite

Assuming you already know the basics of Python, some of the Django experiences of the past will help, but that's not necessary. You need to git or mercurial to version control. That's it!
Ready to install

I assume you have Python installed. If you don't, go to python.org to find a version download installation that matches your system architecture. I use a 64-bit Ubuntu server on the Linode, and I'm happy to use the Linode service.

So, what's the first step? Install Django? Not exactly. Installing the installation package directly into your current site-packages has a common problem: if you have more than one Python project on your machine using Django and other libraries, you may encounter problems with the dependencies between applying and installing the Software Library. Therefore, we will use VIRTUALENV and its extended virtualenvwrapper to manage our Django installation. This is the practice advice of Python and Django users.

If you use Pip to install a third-party library (I don't understand why you don't), you can install Virtualenv and virtualenvwrapper with simple operations.

$ pip Install Virtualenvwrapper

After installation, add the attached content to your shell startup configuration file (. ZSHRC,. BASHRC,. Profile, etc.)

Copy Code code as follows:
Export workon_home= $HOME/.virtualenvsexport project_home= $HOME/directory-you-do-development-insource/usr/local/ bin/virtualenvwrapper.sh

Overload your startup profile (source. ZSHRC), and now you are ready.

Create a new environment

Creating a virtual environment is simple, just type

$ mkvirtualenv Django_project

"Django_project" is the name of your project.

You'll notice something that happens immediately:

Your shell is preceded by a "(Django_project)"

Distribute and PIP are automatically installed.

This is a useful part of Virtualenvwrapper: It automatically prepares you for the environment, allowing you to use the PIP installation Library immediately. Part of "(Django_project)" is to remind you that you are using virtualenv instead of Python on your system. To exit the virtual environment, simply enter the deactivate. When you go back to your project and start working, just use Workon django_project. Note that this is different from the vanilla virtualenv tool, where you can run these commands.

Install Django

"Wait a minute, ' Install Django '?" I've already installed Django! "That's great. But you're not going to use it. Instead, we will use a Django installation on the machine that is virtualenv managed and will not be messed up by other users (or yourself). To install Django in virtualenv, simply type:

$ pip Install Django

This latest version of Django will be installed in your VIRTUALENV environment, so you can confirm that:

$ which django-admin.py

This will point to your $home/.virtualenvs/directory. If not, confirm that you have "(Django_project)" in your input prompt. If not, activate virtualenv using Workon django_project.

Establish a project

Before we really start this project, let's talk about it first. I have consulted many Django/python projects in the past few years and discussed them with many developers. An overwhelming fact is that those with the most difficulty are often not using any version control. This may sound unbelievable (think about the popularity of GitHub), but developers are not going to touch version control at all. There are also those who think "this is a small project" and there is no need to use version control. This is wrong.

The tools listed here will not allow you to add additional expenses to the use of version control.

Before, I only mentioned git as (D) VCS. But since this project is written in Python, mercurial is also a good choice based on Python. Because both are more popular, you can find many online learning resources. Make sure you have git or mercurial installed. Both can get them through your distro ' s packaging system.

If you're going to use Git,github it's obviously a good option to save your code in a remote repository. With mercurial, Atlassian's bitbucket is a good choice (it also supports git, so you can use Git or mercurial).

(source) Control of your environment

Even though we haven't really done anything yet, we know we want everything under the control of the source code. We have two types of "things" that will be submitted: your code itself (including templates, etc.) and supporting files, like database fixtures, South Migrations (later) and requirements.txt files, listing all the packages your project relies on, allowing you to automatically build the environment (no need to use PIP again Install install all packages).

Let's start by creating our project folder. Set using the Startproject command provided by django-admin.py.

$ django-admin.py Startproject Django_project

We'll see the creation of a separate folder: Django_project. In the Django_project folder, we'll see another django_project folder that contains common elements: setting.py,urls.py and wsgi.py. There are manage.py files at the same level in the second Django_project folder.

Episode: Project vs. application

You might wonder why, in Django1.4, you have a command to create a new application and add a new Project command. The answer lies in the difference between Django "project" and Django "Application". In simple terms, a project is a complete set of Web sites or applications. An "Application" is a small, (hopefully) independent Django application that can be used in any Django project. If you're building a blog app called "Super Blog", then "Super blog" Is your Django project. If a "Super blog" supports a reader's vote, the "vote" is a Django application that is used by the Super blog. The idea is that your voting application can be applied to other Django projects that require a user's vote, rather than just being applied to a "Super blog" project. A project is a collection of applications built according to project-specific logic. An application can be applied to multiple projects.

Although you instinctively tend to include a lot of "super blog" specific code and information in your "voting" application, there are many benefits to avoid. Based on the principle of loose coupling, writing your application as an independent entity can keep the design intent and avoid the bugs in the project directly affecting your application. This also means that if you wish, you can send any of your applications to another developer and they do not need to access or change your main project.

Like many things in software development, it takes a little bit of effort, but the rewards are huge.

Create Warehouse

Now we have some "code" in our project (it's really just some stock scripts and empty profiles, and, with that in mind), now is the best time for us to start our Source control library. The following steps are implemented in Git and mercurial.
Git

$ git init

This command creates a git repository in the current directory. Add all of our files to git for submission.

$ git Add django_project

Now, we are actually submitting the code to our new library:

$ git commit-m ' Initial commit of Django_project '

Mercurial

$ HG Init

This command creates a mercurial warehouse in the current directory. Add all of our files to git for submission.

$ HG Add Django_project

Now, we are actually submitting the code to our new library:

$ HG commit-m ' Initial commit of Django_project '

If you're going to use something like GitHub or bitbucket, it's time to push the code up.

Using South for Database migration

One of the most frustrating features of Django is the change in the management model and the related changes in the database. With the help of South, you can create a complete application without having to write specific database code. South will create a migration file to detect your model changes and automatically generate them in the database. This allows you to move the database forward according to the latest changes, and to cancel a change or a series of changes. It makes your life so simple, it's amazing that the Django release doesn't contain it.

When to start using south

In the previous article, I suggested using South at the beginning of the project. It's good for a relatively simple project. However, if you have a large number of models in your prototype that have changed a lot, it's not time to use South. Correspondingly, just throw away and rebuild the database when needed. You can write scripts that make up databases that have some test data and edit them as needed. However, once your model is no longer changing, start using South as soon as possible. This is simple:

./manage.py Convert_to_south <app_name>

Installing and setting

Still in our virtual environment, install South like this:

$ pip Install South

We add south to the Installed_aps in the project's settings.py file. Add now, including the database settings in your project, and then run Python manage.py syncdb. You will need to elevate permissions using the Superuser username and password (you can enter and then return). More importantly, South has set up the tables it needs in the database.

You may realize that we are not adding applications to the project, but just running the syncdb. Doing this first allows South to be installed at the beginning. With South, all of the migration work in our application can be done, including the initial migration.

As we have just completed a lot of changes, it will now be a good time to submit. You have to adapt to frequent submissions, you know, the smaller the granularity of submissions, the higher the degree of freedom to roll back when an error occurs.

To commit, let's take a look at all the changes.

(git)

$ git Status
# on branch Master
# Changes don't staged for commit:
#  [use ' git add <file>. ' To Updat e what'll be committed)
#  (use "Git checkout-<file> ..." to discard changes in working directory) #
#    modified:  django_project/settings.py
# untracked files:
#  (use "git" add <file> ... "to Include in what'll be Committed)
# #    django_project/.settings.py.swp
#    django_project/__init__ . PYC
#    DJANGO_PROJECT/SETTINGS.PYC

(Mercurial)

$ HG Status
M django_project/django_project/settings.py
? django_project/django_project/.settings.py.swp
? django_project/django_project/__init__.pyc
? Django_project/django_project/settings.pyc

With Git and Mercurial, you may find files that you never want to submit, such as the Python-compiled. pyc file that appears above, as well as Vim's. SWP Exchange file. to ignore these files, create a. gitignore or. hgignore file in the root directory of the project and add a shell pattern in which to match the files you do not want to track. For example, most of my file content is:
?

Copy Code code as follows:
*.pyc.*swp

Before we submit, there is one more message to look at: The Python package we've installed. We want to be able to track the names and versions of the Python packages we use, so that we can easily recreate the production environment. The PIP has exactly one command to complete our request.

$ pip Freeze > Requirements.txt

I saved the PIP's output to a file named Requirements.txt and added the file to code control. In this way, we always have an updated list containing the packages that will be used.

Now add settings.py and Requirements.txt to the submission file and submit:

$ (GIT/HG) Add django_project/settings.py requirements.txt
$ (GIT/HG) commit-m ' Added South for database migrations '

New settings

As developers become more comfortable with Django and Python, they will find that settings.py is a simple Python script that can be "written". A common way to settings.py is to move from a rather bizarre project folder to a new folder called Conf or config. Be aware that you need to make minor changes to the manage.py to accommodate this movement.

Within setting.py, Installed_apps will quickly become a bunch of third-party packages, with its own Django applications and project-specific applications. I'm used to dividing the Installed_apps into three categories:

    1. Default_apps: Django Framework application as part of the default Django installation (like admin)
    2. Third_party_apps: Like South
    3. Local_apps: The application you created

This makes it easier to see which third-party applications you use, and which are the projects themselves. Just remember that the last line has the same code as the following:

Installed_apps = Default_apps + Third_party_apps + Local_apps

Otherwise, Django will have an error that does not define INSTALLED_APPS.

Create our Application

Use manage.py in a normal way to create an application (Python manage.py startapp MyApp) and add it to the Installed_app. Also, take the time to make manage.py executable (chmod +x manage.py) so that you can just type in the./manage.py <command> instead of always entering Python manage.py <command >. To be honest, few developers do that. I can't figure out why.

Before we add a model, the first thing we do is we tell South we want to migrate with it:

$ python manage.py schemamigration MyApp--initial

This creates a porting file to apply our model changes to the database (if we do) without having to completely destroy and rebuild it. When the situation deviates, it can also allow us to recover the changes. We use the porting file to migrate the changes to the database (even if it hasn't changed), the commands are as follows:

$ python manage.py migrate MyApp

South is smart enough to know where to find the transplant file, and remember the last transplant we made. You can specify a separate migration file, but this is generally not necessary.

When we finally make a change to the model, we use the following command to let South create a porting file:

$ python manage.py schemamigration MyApp--auto

This detects the model in MyApp and automatically adds, deletes, or modifies the tables in the database accordingly. You can then apply the changes to the database using the migration commands as above.

Development Area

One more thing you need to be aware of: separating the development area from the file area you've identified is obvious. Using git and mercurial to implement this is simple, and it also helps with deployment. Create a directory outside of the Django_project directory as your development area (I call it dev).

In your development directory, use Git or mercurial to clone the current project:

$ (GIT/HG) clone/path/to/my/project/

All two tools will create a full copy of the library. All changes, branches, and histories will be available in the new library. From now on, you should work in your development directory.

Because it's easy to use git and mercurial to branch, you create a branch when you switch to a large change in a new branch or site. Here are the implementation methods for two tools:
(git)

$ git checkout-b <branchname>

This not only creates a named new branch, but also checks out the code. Almost all development work should be on the branch so that the main branch can be recovered at any time.
(Mercurial)

$ HG Branch <branchname>

Note that branching is a controversial topic in the mercurial community and there are some options available here, but there is no "clearly correct" one. Here, I use the named branch, which is probably the safest and most beneficial branching style. Any commit after the branch command will take effect in the new branch.

Use Fabric for deployment

Then we have a Django application. How are we going to deploy it? Fabric. Talking about anything else is a waste of time for a project of a reasonable size. Fabric can be used for many different purposes, but it does work well in terms of deployment.

$ pip Install Fabric

Fabric requires a fabfile file called fabfile.py, which defines all the actions we can take. Now we're going to create it. Write the following to fabfile.py and place it in the project's root directory.

From Fabric.api import localdef prepare_deployment (branch_name): local
  (' Python manage.py test django_project ') Local
  (' git add-p && git commits ') # or local (' HG add && Hg commit ')

This will run the test and submit your changes, but the submission only occurs under the conditions of the test pass. Here, a simple "pull" action in a production environment can be a real deployment. We add something to the actual deployment. Add the following content to the fabfile.py:

Current 1/2 page 12 Next read the full text
Related Article

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.