Full interpretation of the Python Web development Framework Django

Source: Internet
Author: User

A comprehensive understanding of the Python Web development Framework Djangodjango is an open-source Web application framework, written by Python. Using MVC's software design model, the main goal is to make it easy to develop complex, database-driven Web sites. Django focuses on component reusability and "pluggable", agile development and dry rules (Don ' t Repeat Yoursef).

It took two weeks to develop a Django-based project task management Web application using work-gap time. The real-time dynamics of the project plan can be easily viewed by Project members (^_^ and reinvent the wheel again). From the front desk to the backstage, a good toss, use: HTML, CSS, JavaScript, Apache, Python, Mod_wsgi, Django. For a long time without CSS and JavaScript, feel a little rusty, checked countless manuals. The setup of the background Django development environment also took a lot of time and effort. Record it to avoid detours later. Also recommend the Django framework, if you want to write your own web app very quickly, consider using Django, and Django will provide you with a powerful background management interface.

Django is an open-source Web application framework, written by Python. Using MVC's software design model, the main goal is to make it easy to develop complex, database-driven Web sites. Django focuses on component reusability and "pluggable", agile development and dry rules (Don ' t Repeat Yoursef). Python is commonly used in Django, and even includes configuration files and data models. It can run on a mod_python or MOD_WSGI-enabled Apache2, or any Web server that is compatible with WSGI (Web server Gataway Interface).

1. Django's rapid development

First step (model): Design your own data model.
Step Two (View): Create a page template. Django's own HTML template language makes it easy to combine data and templates to create dynamic pages.
Step Three (Control): Define URLs, provide services, and control.
Getting Started Tutorial: https://docs.djangoproject.com/en/1.4/intro/tutorial01/

2. Setting up the Django development environment

Django can run on any Web server that adheres to WSGI. This paper mainly introduces the environment construction of Apache2+mod_wsgi+django. The required software is as follows:

Apache2:web Server
Python2.x:python Language Support
Mod_wsgi:apache Wsgi module, with the support of this module, you can use Python as a CGI script to write Web applications (before there is a mod_python, found on the Apache network Mod_python is outdated, gradually be mod_ Wsgi substitution, said Mod_wsig performance better)
Django: A powerful Python web development framework, the protagonist of this article.
Installation of 2.1 Apache

Download: http://httpd.apache.org/download.cgi (select version 2.2.22,mod_wsig temporarily does not support 2.4.2)

Decompression: $tar XVFZ httpd-nn.tar.gz

$CD Httpd-nn

Compile configuration: $./configure–with-included-apr–prefix=prefix #with-included-apr option specifies the APR library used in the Apache package

Compiling: $make

Installation: $make Install

Configuration: $vim prefix/conf/httpd.conf

Test: $PREFIX/bin/apachectl-k start

Reference

Official homepage: http://httpd.apache.org/
Installation Documentation: http://httpd.apache.org/docs/2.2/install.html
Installation of 2.2 Python

Download: http://www.python.org/getit/releases/2.7.3/(select 2. X version can be, 3.0 temporarily not supported)

Decompression: $tar xvf Python-x.tar

$CD python-y

Compile configuration: $./configure–enable-shared–prefix=prefix #–enable-shared option specifies a dynamic library to generate Python

Compiling: $make

Installation: $make Install

Test: $python

Reference

Official homepage: http://www.python.org/
Installation of the 2.3 Mod_wsgi module

Download: http://code.google.com/p/modwsgi/(choose 3.3 version)

Decompression: $tar XVFZ Mod_wsgi. X.y.tar.gz

$CD Mod_wsgi. x.y

Compile configuration: $././configure–with-apxs=/usr/local/apache2/bin/apxs–with-python=/usr/local/bin/python # Specify the module compiler and Python parser for Apache2

Compiling: $make

Installation: $make Install

Test: $python

2.3.1 Configuring Apache (Modify/usr/local/apche2/confi/httpd.conf)

?
123456789 # 加载wsgi模块LoadModule wsgi_module modules/mod_wsgi.so....# HTTP请求处理脚本WSGIScriptAlias /test /home/xxx/www/test.wsgi<Directory"/home/xxx/www">Order allow, denyAllow from all</Directory>

2.3.2 Writing Test.wsgi (WSGI standard: http://www.python.org/dev/peps/pep-3333/)

?
123456789 def application(environ, start_response): status = ‘200 OK‘ output = ‘Hello World!‘ response_headers = [(‘Content-type‘, ‘text/plain‘),   (‘Content-Length‘, str(len(output)))] start_response(status, response_headers) return [output]

2.3.3 Restart Apche2

In any Web browser, enter: Http://www.mysite.com/test. See "Hello world!", congratulations on your successful installation of the Wsgi module.

Reference

Official homepage: http://code.google.com/p/modwsgi/
Installation Documentation: Http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide
Configuration document: Http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide
WSGI Document: http://www.python.org/dev/peps/pep-3333/

2.4 Django Installation

Download: https://www.djangoproject.com/download/(choose 1.4 version)

Decompression: $tar XVFZ django-1.4.tar.gz

$CD Django-1.4

Installation: $python setup.py Install

Test

?
123 $python>>> importdjango>>> print(django.get_version())

Reference

Official homepage: https://www.djangoproject.com/
Installation Documentation: https://docs.djangoproject.com/en/1.4/intro/install/
Quick Start: https://docs.djangoproject.com/en/1.4/intro/tutorial01/

3. Django Chinese support

Django uses UTF-8 encoding, so it's not a problem for internationalization support. Because the first time to play Django, Chinese display chaos, tossing the dead (the MySQL default string that has been used is the latin1 encoding, Vim saves the file encoding as ASCII by default). Finally come to the conclusion that if the Chinese display garbled, or Django error (...), please check: BlaBla

Django's settings. Open your project's settings.py,language_code= "ZH_CN"? File_charset= ' utf-8′? Default_charset= ' utf-8′?
See if all of your project's file encodings are saved in UTF-8 encoding? Make sure that the first line of the. py file is added: #-*-coding:utf-8-*-?
HTML template file Head section, add <meta http-equiv= "Content-type" content= "text/html;charset=utf-8″/>
Check that the database string encoding for your project is UTF-8, and the command is as follows:
View:

?
123 show createdatabase dbname; show create table tablename; show full columns fromtablename;

Create:

?
12 createdatabase dbname CHARACTER SET utf8; create table tblname CHARACTER SETutf8;

Modify:

?
12 alterdatabase dbname CHARACTER SET = utf8; alter table tablename CONVERT TO CHARACTER SETutf8;

4. Deployment of Django Apps

The Django application runs in two ways, one in the development phase, using the manager.py runserver Ip:port under the Create project to launch a lightweight Web server implemented in Python, and the other is through Mod_ WSGI deploys your own applications to the production environment and provides services to the outside world. The following is a brief introduction to the Django deployment (the configuration on the virtual host, referencing the documentation yourself).

Suppose you create a list of Django project files as follows:

?
1234567891011 my-site|- my-site|- myapp |-static |- ...|- static |- css |- js | ...|- apache|- ...

4.1. Create a WSGI script for the Django Project (MY-SITE/APACHE/DJANGO.WSGI) with the following:

?
123456789101112131415 import os, syssys.path.append(‘/.../www/‘)sys.path.append(‘/.../www/my-site‘)os.environ[‘DJANGO_SETTINGS_MODULE‘] = ‘my-site.settings‘os.environ[‘PYTHON_EGG_CACHE‘] = ‘/.../www/.python-eggs‘ import django.core.handlers.wsgi_application = django.core.handlers.wsgi.WSGIHandler()def application(environ, start_response):  if environ[‘wsgi.url_scheme‘] == ‘https‘:    environ[‘HTTPS‘] = ‘on‘  return _application(environ, start_response)

4.2. Configure Apache (httpd.conf) with the following content:

?
123456789101112131415 # 请求访问www.xxx.com/的时候,转到django.wsgiWSGIScriptAlias / /.../www/my-site/apache/django.wsgi<Directory /.../www/my-site/apache>Order deny,allowAllow from all</Directory> # 静态文件的访问路径配置Alias /static/ /.../www/my-site/static/<Directory /.../www/my-site/static>Order deny,allowAllow from all</Directory>

4.3. Configure setting.py

Ebug=false
Custom 404.html,500.html Template (Web page not found, server internal error)

4.4. static files

?
123 STATIC_ROOT = ‘/…/www/my-site/static/‘STATIC_URL = ‘/static/‘$./manager.py collectstatic

Note: During the development phase, the static files of the corresponding app are usually placed under the static directory in the app directory. When deploying in a formal production environment, use the./manager.py collectstatic to collect all the static files into the Static_root specified location, including the admin backend.

4.5. Restart APAHCE

Browser input the appropriate URL address, see your own Web application interface, congratulations!

5. Summary

This paper mainly introduces the construction of Django development environment, the deployment of Django application and the solution of Chinese garbled characters. How to use Django to quickly create your own web app is not mentioned. Django is relatively well-documented, with the official launch of the Django book, which makes it easy to create your own Web applications as long as the development environment is built.

To learn more about Django, see:

Django1.4 Document: https://docs.djangoproject.com/en/1.4/
Django Book English version: http://www.djangobook.com/en/2.0/
Django book Chinese version: http://djangobook.py3k.cn/2.0/

Full interpretation of the Python Web development Framework Django

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.