Fully understand the Python Web development framework Django
- 2020-04-02 13:45:16
- OfStack
I spent two weeks developing a Django based project task management Web application in between jobs. The real-time dynamics of the project plan can be easily viewed by project members. From the foreground to the background, it's a lot of work: HTML, CSS, JavaScript, Apache, Python, mod_wsgi, Django. I have not used CSS and JavaScript for a long time, and I feel a little rusty. Setting up the backend Django development environment also took a lot of time and effort. Write it down so you don't get sidetracked later. I also recommend the Django framework, if you want to write your own web applications very quickly, you can consider using Django, and Django will give you a powerful background management interface.
Django is an open source Web application framework written in Python. The main goal of adopting the MVC software design pattern is to make it easy to develop complex, database-driven websites. Django focuses on component reuse and "pluggability," agile development, and the DRY rule (Don't Repeat Yoursef). Python is widely used in Django, even including configuration files and data models. It can run on either mod_python or mod_wsgi enabled Apache2, or any WSGI (Web Server Gataway Interface) compliant Web Server.
1. Rapid development of Django
Step 1 (Model) : design your own data Model.
Step 2 (View) : create the page template. Django's own Html template language makes it easy to combine data and templates to create dynamic pages.
Step 3 (Control) : define the URL to provide the service and Control.
Primer: (link: http://wiht.link/django_primer)
2. Set up the Django development environment
Django can run on any WSGI compliant Web server. This article mainly introduces the environment of Apache2+mod_wsgi+Django. The required software is as follows:
Apache2: Web server
Python2.x: the Python language is supported
Mod_wsgi: Apache WSGI module, with the support of this module, you can use Python as a CGI script to write network applications (there was a previous mod_python, in the Apache official website found that mod_python is outdated, gradually to be replaced by mod_wsgi, it is said that mod_wsig performance is better)
Django: a powerful Python Web development framework, the main character of this article.
2.1 installation of Apache
Next: (link: http://httpd.apache.org/download.cgi) (select version 2.2.22, mod_wsig does not currently support 2.4.2)
Unzip: $tar XVFZ httpd-nn.tar.gz
$CD HTTPD - NN
Compile configuration: $./configure with-included-apr prefix= prefix #with-included-apr option to use the apr library in the apache package
Compile: $make
Installation: $make install
Match: $vim PREFIX/conf/httpd.conf
Test: $PREFIX/bin/apache ectl-k start
Barometer:
Official home: (link: http://httpd.apache.org/)
Installation documentation: (link: http://httpd.apache.org/docs/2.2/install.html)
2.2 installation of Python
Next: (link: http://www.python.org/getit/releases/2.7.3/) (could choose 2. X version 3.0 temporarily does not support)
Unzip: $tar XVF python- x.tar
$CD python - Y
Compile configuration: $./configure enable-shared prefix= prefix # enable-shared option specifies the dynamic library to generate python
Compile: $make
Installation: $make install
Test: $python
Barometer:
Official home page: (link: http://www.python.org/)
2.3 installation of mod_wsgi module
Next: (link: http://code.google.com/p/modwsgi/) (select version 3.3)
Unzip: $tar XVFZ mod_wsgi.x.y.tar.gz
$CD mod_wsgi. X.Y
Compiler configuration: $. /. / configure � with - apxs = / usr/local/apache2 / bin/apxs � with - python = / usr/local/bin/python # specified apache2 module compiler and python parser
Compile: $make
Installation: $make install
Test: $python
2.3.1 Configure Apache (modify/usr/local/apche2 confi/HTTPD. Conf.)
# loading wsgi The module
LoadModule wsgi_module modules/mod_wsgi.so
....
# HTTP Request processing script
WSGIScriptAlias /test /home/xxx/www/test.wsgi
<Directory "/home/xxx/www">
Order allow, deny
Allow from all
</Directory>
2.3.2. Write test. Wsgi (wsgi standards: (link: http://www.python.org/dev/peps/pep-3333/))
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 input: (link: http://www.mysite.com/test). See "Hello World!" Congratulations on successfully installing the WSGI module.
Barometer:
The official homepage: (link: http://code.google.com/p/modwsgi/)
Installation documentation: (link: http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide)
The configuration document: (link: http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide)
WSGI document: (link: http://www.python.org/dev/peps/pep-3333/)
2.4 installation of Django
Next: (link: https://www.djangoproject.com/download/) (select version 1.4)
Unzip: $tar XVFZ django-1.4.tar.gz
$CD Django 1.4
Install: $python setup.py install
Test:
$python
>>> import django
>>> print(django.get_version())
Barometer:
The official homepage: (link: https://www.djangoproject.com/)
Installation documentation: (link: https://docs.djangoproject.com/en/1.4/intro/install/)
Quick start: (link: https://docs.djangoproject.com/en/1.4/intro/tutorial01/)
3. Django support in Chinese
Django USES utf-8 encoding, so internationalization support is not a problem. Because of the first time to play Django, the Chinese display is messy, annoying to the death (mysql has been using the default string is latin1 encoding, vim default saved file encoding as ASCII). Finally, if the Chinese display garbled code, or Django error (... Unicode... Blabla...). , please check:
Setup for Django. Settings. Py, LANGUAGE_CODE= "zh_CN"? FILE_CHARSET = 'utf-8'? DEFAULT_CHARSET = 'utf-8'?
Check if all file encodings for your project are stored in utf-8? Make sure to add: #-*- to the first line of the.py file
Coding: utf-8 - * -?
HTML template file head section, add
<
Meta HTTP - equiv = "content-type" Content = "text/HTML. Charset = utf-8 "/
>
Check whether the database string encoding of your project is utf-8. The command is as follows:
To view:
show create database dbname;
show create table tablename;
show full columns from tablename;
Create:
create database dbname CHARACTER SET utf8;
create table tblname CHARACTER SET utf8;
Modification:
alter database dbname CHARACTER SET = utf8;
alter table tablename CONVERT TO CHARACTER SET utf8;
4. Deployment of Django applications
Django applications can be run in two ways. One is to use the manager.py runserver IP :port under the project to start a lightweight web server implemented in Python during the development phase. The other is to deploy your own application to a production environment through mod_wsgi and provide services to external users. The following is a brief overview of Django deployment (configuration on the virtual host, refer to the documentation).
Suppose you create a list of Django project files as follows:
my-site
|- my-site
|- myapp
|-static
|- ...
|- static
|- css
|- js
| ...
|- apache
|- ...
4.1. Create the wsgi script of Django project (my-site/apache/django.wsgi), as follows:
import os, sys
sys.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), as follows:
# Request access www.xxx.com/ When, turn to django.wsgi
WSGIScriptAlias / /.../www/my-site/apache/django.wsgi
<Directory /.../www/my-site/apache>
Order deny,allow
Allow from all
</Directory>
# Access path configuration for static files
Alias /static/ /.../www/my-site/static/
<Directory /.../www/my-site/static>
Order deny,allow
Allow from all
</Directory>
4.3. The configuration setting. Py
EBUG = False
Custom 404.html, 500.html template (page not found, server internal error)
4.4. Static files
STATIC_ROOT = ' / ... /www/my-site/static/'
STATIC_URL = ' /static/'
$./manager.py collectstatic
Note: during the development stage, the static file of the corresponding app is generally placed in the static directory under the app directory. At the time of a formal production deployment, use./manager.py collectstatic to collect all static files to the location specified by STATIC_ROOT, including those in the administrative background.
4.5. Restart apahce
Enter the corresponding URL in the browser and see your own web application interface. Congratulations!
5. To summarize
This article mainly introduces the construction of Django development environment, deployment of Django application and the solution of Chinese garble. How to use Django to quickly create your own web applications is not mentioned. Django is relatively well-documented, and with The release of an official Book, The Django Book, it's easy to create your own Web applications as long as your development environment is set up.
To learn more about Django, see:
Django1.4 document: (link: https://docs.djangoproject.com/en/1.4/)
Django Book in English: (link: http://www.djangobook.com/en/2.0/)
Django Book in Chinese: (link: http://djangobook.py3k.cn/2.0/)