In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
Nginx + uWSGI + Python + Django deployment example analysis, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Nginx:
Nginx is a high-performance Web and reverse proxy server with many very superior features:
As a Web server: it uses fewer resources, supports more concurrent connections and embodies higher efficiency than Apache,Nginx, which makes Nginx especially popular among web hosting providers. Can support up to 50000 concurrent connections response, thank Nginx for choosing epoll and kqueue for us as the development model.
As a load balancing server: Nginx can not only directly support Rails and PHP internally, but also support external services as a HTTP proxy server. Nginx is written in C, both in terms of system resource overhead and CPU use efficiency is much better than Perlbal.
As a mail proxy server: Nginx is also an excellent mail proxy server (one of the earliest purposes of developing this product is also as a mail proxy server), Last.fm describes the successful and wonderful experience.
Nginx installation is very simple, the configuration file is very simple (and can also support perl syntax), servers with very little Bugs: Nginx is very easy to start, and can run almost 7 hours 24 without reboot, even if it runs for several months. You can also upgrade the software version with uninterrupted service.
UWSGI:
APP (applications) are applications written by developers, such as django,bottle. The logical part of recording how requests from the client are handled.
WSGI, is a protocol that Python uses for Web development.
UWSGI, is a program that acts as a Web server or middleware.
If the architecture is Nginx+uWSGI+APP,uWSGI, it is a middleware.
If the architecture is uWSGI+APP,uWSGI, it's a server.
Uwsgi is a proprietary protocol implemented by uWSGI programs.
The order in which Web protocols appear:
CGI-> FCGI-> WSGI-> uwsgi
CGI, the earliest protocol
FCGI, faster than CGI.
WSGI,Python proprietary protocol
Uwsgi, which is faster than FCGI and WSGI, is the native protocol of uWSGI project. Its main feature is to use binary to store data. Previous protocols used strings, so it is better than string protocol in storage space and parsing speed.
Django:
Django (Wikipedia) Django is an open source Web application framework written by Python. The software design pattern of MVC is adopted, that is, model M, view V and controller C. It was originally developed to manage some of the Lawrence Publishing Group's news-based websites. And released under the BSD license in July 2005. The framework is named after the Belgian gypsy jazz guitarist Django Reinhardt.
The main goal of Django is to make it easy to develop complex, database-driven websites. Django focuses on reusability and "pluggability" of components, agile development and DRY rules (Don't Repeat Yourself). Python is widely used in Django, even including configuration files and data models.
The core of the Django framework includes an object-oriented mapper that acts as an intermediary between the data model (defined in the form of Python classes) and relational databases; an URL dispatcher based on regular expressions; a view system for processing requests; and a templating system.
The core framework also includes:
A lightweight, stand-alone Web server for development and testing.
A form serialization and validation system for conversion between HTML forms and data suitable for database storage.
A caching framework, and there are several caching methods to choose from.
L middleware support, allowing interference in all stages of request processing.
The built-in distribution system allows components in the application to communicate with each other using predefined signals.
A serialization system capable of generating or reading Django model instances represented by XML or JSON.
A system for extending the capabilities of the template engine.
Main features of Django
Django "self-provided military supplies" (Batteries-Included)
Django is based on the concept of "bring your own quartermaster", so you don't have to use separate libraries to implement common functions such as authentication, URL routing, templating systems, object-relational mappers (ORM), and database model migrations. If you are using or have ever used Flask, you must have noticed that it needs to call other libraries, such as Flask-Login, to perform user authentication. This is not the case with Django.
Free API
With Django, it is easy to generate Python API from your model. With a simple command, no extra coding is needed to start generating API.
Unique management page
Even before the site is fully built, you can get the information from external contributors. This is the power of Django. The framework enables you to quickly and easily generate management sites from application models.
Code design
In contrast to most Web frameworks, Django makes it easier to add new functionality to the product by using something called app. As a result, developers can feel that Django encourages you to write modular code.
Django's perfect support for ORM
Django's object-relational mapping (ORM) provides perfect support for the database. Therefore, it does not have the trouble of dealing with structured query language (SQL) when it is used to query the data needed by the database. Unlike many Python frameworks that work directly on the database through SQL, Django developers have a unique choice to manipulate the corresponding Python's Model objects. Django can be used out of the box for databases such as PostgreSQL,MySQL,SQLite and Oracle.
Powerful built-in template system
Based on the inheritance system, Django's templates allow developers to build entire dynamic Web sites with very small amounts of front-end code. This benefits from the option of replacing some elements of the template with other context-specific elements. Imagine that you know that every page on your site will have a header and a footer. Now, you first need to write code in the basic template of the site. You can then dynamically change the components between the two contents from other parts of the application.
A simple and readable URL
Is it difficult to read the URL developed in PHP os ASP correctly? With Django, you can create an easy-to-read URL, which is good for both people and search engines. You can also use other frameworks to create readable URL, but none of them are as easy to construct URL as Django
Django is an open source library written by Python, advanced, MVC style. Django, also known as the "ultimate framework for perfectionists", was originally designed for news sites because it allows developers to write database-driven Web applications without having to code from scratch.
In addition to completing common Web development tasks faster, Django keeps the design clean and practical. Django is the best choice for new Python Web developers because official documentation and tutorials are the best of several (of its kind) software development frameworks.
The technology market is flooded with a range of network frameworks, but Django is at the peak of the most popular server-side Web framework. The motto behind designing Django is simple: avoid repetition. Django is written in Python, so it reduces too much middle-tier code and highlights efficiency gains. Django can support cloud platforms, making it a more popular choice for Web development.
Deploy Nginx + uWSGI + Python + Django
Nginx version: 1.5.9
Django version: 1.4.9
Uwsgi version: 2.0.4
Python version: 2.6.6
Install, Django,nginx,uwsgi,MySQL, compile and install, easy to maintain
[root@kurol ~] # mkdir-p / data/logs [root@kurol ~] # yum-y install gcc cc gcc-c++ [root@kurol ~] # tar-zxvf pcre-8.34.tar.gz [root@kurol ~] # cd pcre-8.34 [root@kurol pcre-8.34] #. / configure [root@kurol pcre-8.34] # make & & make install [root@kurol pcre-8.34] # cd. [root@kurol ~] # wget http://nginx .org/download/nginx-1.5.9.tar.gz [root@kurol ~] # tar-zxvf nginx-1.5.9.tar.gz [root@kurol ~] # cd nginx-1.5.9 [root@kurol nginx-1.5.9] #. / configure-- prefix=/usr/local/nginx-- with-http_stub_status_module-- without-http_gzip_ module [root @ kurol nginx-1.5.9] # make & & make install [root@ Kurol nginx-1.5.9] # cd. [root@kurol ~] # yum-y install MySQL-python mysql mysql-devel mysql-server [root@kurol ~] # yum-y install libxml2 python-devel [root@kurol ~] # wget http://projects.unbit.it/downloads/uwsgi-2.0.4.tar.gz[root@kurol ~] # tar-zxvf uwsgi-2.0.4.tar.gz [root@kurol ~] # cd uwsgi-2.0.4 [root@kurol Uwsgi-2.0.4] # make [root@kurol uwsgi-2.0.4] # cp uwsgi / usr/bin [root@kurol uwsgi-2.0.4] # cd. [root@kurol ~] # wget https://www.djangoproject.com/m/releases/1.4/Django-1.4.9.tar.gz-- no-check-certificate [root@kurol] # tar-zvxf Django-1.4.9.tar.gz [root@kurol ~] # cd Django- 1.4.9 [root@kurol Django-1.4.9] # python setup.py install
Configure Nginx.
[/ usr/local/nginx/conf/nginx.conf] server {listen 80; server_name www.mykurol.com; location / {uwsgi_pass 127.0.0.1 listen 9001; include uwsgi_params; uwsgi_param UWSGI_CHDIR / data/www/board; uwsgi_param UWSGI_SCRIPT django_wsgi; access_log off } location * ^. +\. (mpg | avi | mp3 | swf | zip | tgz | gz | rar | bz2 | doc | xls | exe | ppt | txt | tar | mid | midi | wav | rtf | mpeg) ${root / data/www/board/static; access_log off;}}
Configure uwsgi.
[/ usr/local/nginx/conf/uwsgi.ini] [uwsgi] socket = 0.0.0.0:9001master = truepidfile = / usr/local/nginx/uwsgi.pidprocesses = 8chdir = / data/www/boardpythonpath = / data/wwwprofiler = truememory-report = trueenable-threads = truelogdate = truelimit-as = 6048daemonize = / data/logs/django.log
Start the project board
[root@kurol logs] # cd / data/www/ [root@kurol www] # django-admin.py startproject board [root@kurol www] # cd board/ [root@kurol board] # vim Djangoggwsgi.pyrogen python# coding python# coding: utf-8import osimport sysreload (sys) sys.setdefaultencoding ('utf8') os.environ.setdefault ("DJANGO_SETTINGS_MODULE") "board.settings") from django.core.handlers.wsgi import WSGIHandlerapplication = WSGIHandler () [root@kurol www] # lsboard [root@kurol www] # tree.`-- board |-- board | |-- _ _ init__.py | |-- settings.py | |-- urls.py | `--wsgi.py`-- manage.py2 directories, 5 files
Start uwsgi and nginx services., where uwsgi uses a custom location profile
[root@kurol] # / usr/bin/uwsgi-- ini / usr/local/nginx/conf/uwsgi.ini / usr/bin/uwsgi: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory [root@kurol ~] # ln-s / usr/local/lib/libpcre.so.1 / lib64 [root@kurol ~] # / usr/bin/uwsgi-- ini / usr/local/nginx/conf/uwsgi.ini [root@kurol ~] # / usr/local/nginx/sbin/nginx [root@kurol ~] # netstat-ltunp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 00 0.0.0.0 ltunp Active Internet connections 9001 0.0.0.0 ltunp Active Internet connections * LISTEN 15243/uwsgi tcp 00 0.0.0.0 80 0.0.0.0 * LISTEN 15423/nginx tcp 0 0 0.0.0.0 22 0.0.0 0 * LISTEN 868/sshd tcp 0 0127.0.0.1 Vol 25 0.0.0.0VR * LISTEN 957/master
Facilitate service management and create nginx and uwsgi startup scripts.
Nginx:
[root@kurol board] # touch / etc/init.d/nginx [root@kurol board] # chmod 775 / etc/init.d/nginx [root@kurol board] # vim / ETC Unipool init.dAccord nginx PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DESC= binbinbinLash sh # set-e PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DESC= "nginx daemon" NAME=nginx DAEMON=/usr/local/nginx / sbin/nginx CONFIGFILE=/usr/local/nginx/conf/nginx.conf PIDFILE=/usr/local/nginx/logs/nginx.pid SCRIPTNAME=/etc/init.d/nginx # If the daemon file is not found Terminate the script. Test-x $DAEMON | | exit 0 d_start () {$DAEMON-c $CONFIGFILE | | echo-n "already running"} d_stop () {kill-QUIT `cat $PIDFILE` | | echo-n "no running"} d_reload () {kill-HUP `cat $PIDFILE` | echo-n "could not reload"} case "$1" in start) Echo-n "Starting $DESC: $NAME" d_start echo. " ; stop) echo-n "Stopping $DESC: $NAME" d_stop echo ".;; reload) echo-n" Reloading $DESC configuration... " D_reload echo "Reloaded."; restart) echo-n "Restarting $DESC: $NAME" d_stop # Sleep for two seconds before starting again, this should give the nginx daemon some time to perform a graceful stop sleep 2 d_start echo "." *) echo "Usage: $SCRIPTNAME {start | stop | restart | force-reload)" > & 2 exit 3;; esac exit 0
Uwsgi:
[root@kurol board] # touch / etc/init.d/uwsgi [root@kurol board] # chmod 775 / etc/init.d/uwsgi [root@kurol board] # vim / ETC PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DESC= init.dAccording to Uwsgigabe binram sh # set-e PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin DESC= "uwsgi daemon" NAME=uwsgi DAEMON=/usr/bin/uwsgi CONFIGFILE=/usr/local/nginx/conf/uwsgi.ini PIDFILE=/usr/local/nginx/uwsgi.pid SCRIPTNAME=/etc/init.d/uwsgi # If the daemon file is not found Terminate the script. Test-x $DAEMON | | exit 0 d_start () {$DAEMON-- ini $CONFIGFILE | | echo-n "already running"} d_stop () {kill-QUIT `cat $PIDFILE` | | echo-n "no running"} d_reload () {kill-HUP `cat $PIDFILE` | | echo-n "could not reload"} case "$1" in start) Echo-n "Starting $DESC: $NAME" d_start echo. " ; stop) echo-n "Stopping $DESC: $NAME" d_stop echo ".;; reload) echo-n" Reloading $DESC configuration... " D_reload echo "Reloaded."; restart) echo-n "Restarting $DESC: $NAME" d_stop # Sleep for two seconds before starting again, this should give the nginx daemon some time to perform a graceful stop sleep 2 d_start echo "." *) echo "Usage: $SCRIPTNAME {start | stop | restart | force-reload)" > & 2 exit 3;; esac exit 0
Create a data model:
[root@kurol board] # cd / data/www/board/webserver/ [root@kurol webserver] # vim models.pyfrom django.db import modelsclass webserver (models.Model): username = models.CharField ('username', max_length=30) password = models.CharField ('password', max_length=30) email = models.EmailField ('email', blank=True) desc = models.TextField ('description', max_length=500 Blank=True) class Meta: db_table = u'board_webserver'def _ _ unicode__ (self): return self.username [root@kurol webserver] # vim / data/www/board/board/settings.pyDATABASES = {'default': {' ENGINE': 'django.db.backends.mysql', # Add' postgresql_psycopg2', 'mysql',' sqlite3' or 'oracle'. 'NAME': 'OBServer', # Or path to database file if using sqlite3. 'USER': 'root', # Not used with sqlite3. 'PASSWORD':'*, # Not used with sqlite3. 'HOST':', # Set to empty string for localhost. Not used with sqlite3. 'PORT':', # Set to empty string for default. Not used with sqlite3. }} INSTALLED_APPS = ('django.contrib.auth',' django.contrib.contenttypes', 'django.contrib.sessions',' django.contrib.sites', 'django.contrib.messages',' django.contrib.staticfiles', 'webserver', # Uncomment the next line to enable the admin: #' django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs' ) [root@kurol board] # export LC_ALL=en_US.UTF-8 [root@kurol board] # python manage.py sqlall webserver # check the sql statement BEGIN CREATE TABLE `board_ webserver` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `username` varchar (30) NOT NULL, `password` varchar (30) NOT NULL, `email` varchar (75) NOT NULL, `room` longtext NOT NULL); COMMIT
The SQL statement is fine. Continue to execute.
# use migrate instead of syscdb in Django 1.9 and future versions
Syncdb will create all app under the INSTALL_APPS configured under setting.py, create their corresponding data tables to the specified database, but only create tables that do not exist, such as above
'django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.sites',' django.contrib.messages', 'django.contrib.staticfiles',' webserver'
A corresponding table is created.
[root@kurol board] # python manage.py syncdb Creating tables... Creating table board_webserverInstalling custom SQL... Installing indexes... Installed 0 object (s) from 0 fixture (s)
Error reporting problem
[root@kurol board] # python manage.py syncdb
TypeError: decode () argument 1 must be string, not None
Resolve:
Just write export LC_ALL=en_US.UTF-8 to profile or .bashrc.
[root@kurol board] # export LC_ALL=en_US.UTF-8
Generate applications, modify urls specified pages, and add views views
[root@kurol webserver] # cd / data/www/board/ [root@kurol board] # python manage.py startapp webserver [root@kurol board] # vim board/urls.pyfrom django.conf.urls import patterns, include, urlurlpatterns = patterns (', (r'^ $', 'board.views.index'), (r' ^ board/', include ('webserver.urls') ) [root@kurol board] # cd webserver/ [root@kurol webserver] # touch urls.py [root@kurol webserver] # vim urls.pyfrom django.conf.urls.defaults import * urlpatterns = patterns (', (r'^ $', 'webserver.views.index'), (r' ^ random_number/$', 'webserver.views.random_number') ) [root@kurol webserver] # cd. [root@kurol board] # cd board [root@kurol board] # vim views.py# Create your views here.from django.http import HttpResponsedef index (request): html = "" Main Main Page "return HttpResponse (html)
The browser opens and shows that Main Page has been successfully deployed.
This is the answer to the case analysis question about Nginx + uWSGI + Python + Django deployment. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.