<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DevOps技术分享 &#187; Programming</title>
	<atom:link href="http://www.showerlee.com/archives/category/programming/feed" rel="self" type="application/rss+xml" />
	<link>http://www.showerlee.com</link>
	<description>与你共同学习运维开发</description>
	<lastBuildDate>Mon, 19 Oct 2020 05:51:41 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.6</generator>
		<item>
		<title>CentOS7.4部署Python3+Django+uWSGI+Nginx</title>
		<link>http://www.showerlee.com/archives/2590</link>
		<comments>http://www.showerlee.com/archives/2590#comments</comments>
		<pubDate>Fri, 20 Apr 2018 10:18:53 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[NGINX]]></category>
		<category><![CDATA[uwsgi]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2590</guid>
		<description><![CDATA[安装环境 Remote: CentOS 7.4 x64 (django.example.com) Python [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"> </span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Remote: CentOS 7.4 x64 (<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com)
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Python: Python3.6.5
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Django: Django 2.0.4
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	nWSGI:&nbsp;&nbsp;<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>-2.0.15
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Nginx:&nbsp; nginx-&nbsp;1.10.2-1.el6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"> </span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><strong>一. 系统环境配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1.关闭iptables和selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# su - root
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# service iptables stop
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># setenforce 0</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/sysconfig/selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	修改
</p>
<pre class="prettyprint lang-bsh">SELINUX=disabled</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;color:#337FE5;">2.添加本地host DNS</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/hosts</span>
</p>
<pre class="prettyprint lang-bsh">127.0.0.1    <a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;"><strong>二. Python配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1.安装python3.6.5源及依赖包</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># yum install epel-release -y</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum groupinstall "Development tools" -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel zx-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel libffi-devel -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.编译安装python3.6.5以及pip package manager</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# wget <a href="https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz" rel="nofollow">https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz</a> --no-check-certificate
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# tar xf Python-3.6.5.tar.xz
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd Python-3.6.5
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./configure --prefix=/usr/local --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# make &amp;&amp; make altinstall
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">3.安装virtualenv</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip3.6 install --upgrade pip
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip3.6 install virtualenv
</p>
<div>
</div>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><strong>三. Nginx配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1. 安装nginx package</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install nginx -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.配置nginx with nWSGI</span>
</p>
<p>
	#&nbsp;vi /etc/nginx/conf.d/<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.conf
</p>
<pre class="prettyprint">server {
&nbsp; &nbsp; listen<span> </span> 80;
&nbsp; &nbsp; server_name&nbsp; <a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com;&nbsp;&nbsp;

&nbsp; &nbsp; charset utf-8;

&nbsp; &nbsp; access_log&nbsp; /var/log/nginx/<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>_access.log;
&nbsp; &nbsp; error_log&nbsp; &nbsp;/var/log/nginx/<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>_error.log;
&nbsp; &nbsp;&nbsp;
&nbsp; &nbsp; location = /favicon.ico { access_log off; log_not_found off; }

&nbsp; &nbsp; location /static/ {
&nbsp; &nbsp; &nbsp; &nbsp; root /usr/share/nginx/html/<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com;
&nbsp; &nbsp; }

&nbsp; &nbsp; client_max_body_size 20M;
&nbsp; &nbsp;&nbsp;
&nbsp; &nbsp; location / {
&nbsp; &nbsp; &nbsp; &nbsp; include&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_params;
&nbsp; &nbsp; &nbsp; &nbsp; <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_pass&nbsp; &nbsp; &nbsp; unix:/etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>-<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.sock;
&nbsp; &nbsp; &nbsp; &nbsp; <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_read_timeout 30s;
&nbsp; &nbsp; &nbsp; &nbsp; <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_send_timeout 30s;
&nbsp; &nbsp; }

}
</pre>
<p>
	
</p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><strong>四. Django+uWSGI配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1. uWSGI配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir -p /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>-<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.ini
</p>
<pre class="prettyprint">[uwsgi]
project = django.example.com
base = /data/www

chdir = %(base)/%(project)
home = %(base)/%(project)/.py3env
module = myproject.wsgi:application

pidfile = /tmp/uwsgi-master-django.pid

master = true
processes = 2
enable-threads = true

# use unix socket because it is more secure and faster than TCP socket
socket = /etc/uwsgi/uwsgi-django.sock
chmod-socket = 660
uid = nginx
gid = nginx

vacuum = true
die-on-term = true

logto = /var/log/nginx/uwsgi-django.log</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2. 配置Django base folder</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd /usr/share/nginx/html
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir django.example.com
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">django.example.com</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# virtualenv -p /usr/local/bin/python3 .py3env
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">3. 开启virtualenv python3环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">#&nbsp;source .py3env/bin/activate</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#337FE5;font-size:13px;">4. 在此环境安装Django相关模块</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# pip install django uwsgi&nbsp;PyMySQL
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">5. 创建uWSGI启动脚本</span>
</p>
<p>
	# mkdir -p /etc/uwsgi/bin
</p>
<p>
	# vi /etc/systemd/system/uwsgi-django.service
</p>
<pre class="prettyprint lang-bsh">[Unit]
&nbsp; &nbsp; Description=uWSGI instance to serve myproject

[Service]
&nbsp; &nbsp; BASE=/data/www/django.example.com
&nbsp; &nbsp; ENV=$BASE/.py3env
&nbsp; &nbsp; ExecStartPre=-/usr/bin/bash -c 'chown -R nginx:nginx /etc/uwsgi'
&nbsp; &nbsp; ExecStart=/usr/bin/bash -c 'source <span>/usr/share/nginx/html/</span><span>django.example.com/</span>.py3env/bin/activate; uwsgi --ini /etc/uwsgi/uwsgi-django.ini'

[Install]
&nbsp; &nbsp; WantedBy=multi-user.target</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"></span>
</p>
<p>
	
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;"><strong>五. Django项目配置</strong></span>
</p>
<p>
	<span style="color:#337FE5;">1. 保证virtualenv python3环境开启</span>
</p>
<p>
	<span style="color:#337FE5;"><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># cd&nbsp;</span><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/usr/share/nginx/html/django.example.com/</span><br />
</span>
</p>
<p>
	# source&nbsp;.py3env/bin/activate
</p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.创建一个Django项目</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;django-admin startproject myproject .
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">3.添加static目录</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi&nbsp;myproject/settings.py
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	末行添加:
</p>
<pre class="prettyprint lang-bsh">STATIC_ROOT = os.path.join(BASE_DIR, "static/")</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">4.创建本地SQLlite文件</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#E53333;">Tip:这里使用SQLlite代替其他数据库作为我们项目的DB</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./manage.py makemigrations<br />
# ./manage.py migrate
</p>
<pre class="prettyprint lang-bsh">Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">5.创建项目管理员账户</span>
</p>
<p>
	#&nbsp;./manage.py createsuperuser
</p>
<pre class="prettyprint lang-bsh">Username (leave blank to use 'root'): root
Email address: <a href="mailto:admin@admin.com">admin@admin.com</a>
Password:
Password (again):
Superuser created successfully.</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">6.生成项目静态文件目录</span>
</p>
<p>
	#&nbsp;./manage.py collectstatic
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">7.修改wsgi入口文件</span>
</p>
<p>
	#&nbsp;vi myproject/wsgi.py
</p>
<pre class="prettyprint lang-bsh">import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
sys.path.append('<span>/usr/share/nginx/html/</span><span>django.example.com</span>')

from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">8.添加</span><span style="color:#337FE5;">ALLOWED_HOSTS</span>
</p>
<p>
	#&nbsp;vi myproject/settings.py
</p>
<p>
	Update:
</p>
<pre class="prettyprint lang-bsh">ALLOWED_HOSTS = ['django.example.com']</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">9. 修改权限</span><span style="color:#337FE5;">(可执行并保持与nginx启动user一致)</span>
</p>
<p>
	# chmod -R 755&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chown -R nginx:nginx&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chmod -R 755 /usr/share/nginx/html/django.example.com
</p>
<p>
	# chown -R nginx:nginx /usr/share/nginx/html/django.example.com
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">10.启动nginx+uwsgi</span>
</p>
<p>
	# systemctl restart nginx
</p>
<p>
	# systemctl restart uwsgi-django
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	展示效果<span style="color:#E53333;">(保证Windows本地host文件能够解析django.example.com)</span>
</p>
<p>
	<a href="http://www.showerlee.com/archives/2590/django-nginx"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/django-nginx.png" alt="" width="800" height="329" class="alignnone size-full wp-image-2624" title="" align="" /></a>
</p>
<p>
	<a href="http://www.showerlee.com/archives/2590/django-nginx-dash"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/django-nginx-dash.png" alt="" width="800" height="253" class="alignnone size-full wp-image-2625" title="" align="" /></a><a href="http://www.showerlee.com/archives/2590/django-nginx-dash1"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/django-nginx-dash1.png" alt="" width="800" height="291" class="alignnone size-full wp-image-2626" title="" align="" /></a>
</p>
<p>
	
</p>
<p>
	Finished...</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2590">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS7.4部署Python3+Django+uWSGI+Nginx" href="http://www.showerlee.com/archives/2590">http://www.showerlee.com/archives/2590</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2590/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CentOS7.4部署Django+Python3+Apache+Mod_wsgi</title>
		<link>http://www.showerlee.com/archives/2511</link>
		<comments>http://www.showerlee.com/archives/2511#comments</comments>
		<pubDate>Mon, 16 Apr 2018 03:11:05 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[APACHE]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[mod_wsgi]]></category>
		<category><![CDATA[python3]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2511</guid>
		<description><![CDATA[安装环境 Remote: CentOS 7.4 x64 (django.example.com) Python [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Remote: CentOS 7.4 x64 (<a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com)
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Python: Python3.6.5
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Apache: Apache 2.4.6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Mod_wsgi: 4.6.4
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Django: Django 2.0.4
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><strong>一. 系统环境配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1.关闭iptables和selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# su - root
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# systemctl stop firewalld
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># setenforce 0</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/sysconfig/selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	修改
</p>
<pre class="prettyprint lang-bsh">SELINUX=disabled</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;color:#337FE5;">2.添加本地host DNS</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/hosts</span>
</p>
<pre class="prettyprint lang-bsh">127.0.0.1    <a href="http://www.showerlee.com/archives/tag/django-2" title="查看django中的全部文章" class="tag_link">django</a>.example.com</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;"><strong>二. Python配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1.安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.6.5源及依赖包</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># yum install epel-release -y</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum groupinstall "Development tools" -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">yum install zlib-devel bzip2-devel openssl-devel ncurses-devel zx-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel libffi-devel -y</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.编译安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.6.5以及pip package manager</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# wget <a href="https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz" rel="nofollow">https://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz</a> --no-check-certificate
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# tar xf Python-3.6.5.tar.xz
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd Python-3.6.5
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./configure --prefix=/usr/local --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# make &amp;&amp; make altinstall
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">3.安装virtualenv</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip3.6 install --upgrade pip
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip3.6 install virtualenv
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;"><strong>三. Django环境配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1. 配置Django virtualenv</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir -p /var/www/html/django
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/var/www/html/django</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# virtualenv -p /usr/local/bin/<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.6 .py3env
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2. 开启virtualenv <a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">#&nbsp;source .py3env/bin/activate</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#337FE5;font-size:13px;">3. 在此环境安装Django相关模块</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# pip install django pymysql
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><strong>四. Apache配置</strong></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">1. 安装apache package</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install httpd httpd-devel -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.安装<a href="http://www.showerlee.com/archives/tag/mod_wsgi" title="查看mod_wsgi中的全部文章" class="tag_link">mod_wsgi</a> for <a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#E53333;">Tip:这里其实是一个远古巨坑, 网上90%以上资料的会粗心的直接使用yum install <a href="http://www.showerlee.com/archives/tag/mod_wsgi" title="查看mod_wsgi中的全部文章" class="tag_link">mod_wsgi</a>去安装apache mod_wsgi模块, 这样做其实最终mod模块会调用本地默认的python2的所有库文件, 无论你后面如何配置django入口文件, apache都不会使用我们配置的virutalenv下隔离的<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>, 导致apache无法调用<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>而报错. 这里小伙伴要注意哦.</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># pip install mod_wsgi&nbsp;</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">3.导出apache所需的mod_wsgi模块</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">#&nbsp;mod_wsgi-express install-module</span>
</p>
<pre class="prettyprint lang-bsh">LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"
WSGIPythonHome "/var/www/html/.py3env"</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">4.配置apache配置文件</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;"><span style="color:#000000;"># vi</span><span style="color:#000000;">&nbsp;/etc/httpd/conf/httpd.conf</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	末行添加:
</p>
<pre class="prettyprint lang-bsh">LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"</pre>
<p>
	
</p>
<p>
	#&nbsp;vi /etc/httpd/conf.d/django.conf
</p>
<p>
	
</p>
<pre class="prettyprint lang-bsh">WSGIPythonHome "/var/www/html/django/.py3env"

Listen 8080
&lt;VirtualHost *:8080&gt;

ServerName django.example.com

Alias /static /var/www/html/django/static
&lt;Directory /var/www/html/django/static&gt;
 Require all granted
&lt;/Directory&gt;

&lt;Directory /var/www/html/django/myproject&gt;
  &lt;Files wsgi.py&gt;
    Require all granted
  &lt;/Files&gt;
&lt;/Directory&gt;

WSGIDaemonProcess myproject python-path=/var/www/html/django/.py3env/lib/<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.6/site-packages
WSGIScriptAlias / /var/www/html/django/myproject/wsgi.py

&lt;/VirtualHost&gt;</pre>
<p>
	
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">5.重启apache并设置开机自启动</span>
</p>
<p>
	# systemctl restart httpd
</p>
<p>
	# systemctl enable httpd
</p>
<p>
	
</p>
<p>
	
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;"><strong>五. Django项目配置</strong></span>
</p>
<p>
	<span style="color:#337FE5;">1. 保证virtualenv <a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>环境开启</span>
</p>
<p>
	# source <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/var/www/html/django/</span>.py3env/bin/activate
</p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">2.创建一个Django项目</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd /var/www/html/django/
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;django-admin startproject myproject .
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">3.添加static目录</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi&nbsp;myproject/settings.py
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	末行添加:
</p>
<pre class="prettyprint lang-bsh">STATIC_ROOT = os.path.join(BASE_DIR, "static/")</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;">4.创建本地SQLlite文件</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span><span style="color:#E53333;">Tip:这里使用SQLlite代替其他数据库作为我们项目的DB</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./manage.py makemigrations<br />
# ./manage.py migrate
</p>
<pre class="prettyprint lang-bsh">Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">5.创建项目管理员账户</span>
</p>
<p>
	#&nbsp;./manage.py createsuperuser
</p>
<pre class="prettyprint lang-bsh">Username (leave blank to use 'root'): root
Email address: <a href="mailto:admin@admin.com">admin@admin.com</a>
Password:
Password (again):
Superuser created successfully.</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">6.生成项目静态文件目录</span>
</p>
<p>
	#&nbsp;./manage.py collectstatic
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">7.修改wsgi入口文件</span>
</p>
<p>
	#&nbsp;vi myproject/wsgi.py
</p>
<pre class="prettyprint lang-bsh">import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
sys.path.append('/var/www/html/django')

from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">8.添加</span><span style="color:#337FE5;">ALLOWED_HOSTS</span>
</p>
<p>
	#&nbsp;vi myproject/settings.py
</p>
<p>
	Update:
</p>
<pre class="prettyprint lang-bsh">ALLOWED_HOSTS = ['django.example.com']</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">9.修改项目属主和权限</span>
</p>
<p>
	# chmod -R 755 /var/www/html
</p>
<p>
	# chown -R apache:apache /var/www/html
</p>
<p>
	
</p>
<p>
	查看最终目录下的生成的项目文件
</p>
<p>
	# ls -l
</p>
<pre class="prettyprint lang-bsh">-rwxr-xr-x 1 apache apache 38912 Apr 16 15:04 db.sqlite3
-rwxr-xr-x 1 apache apache   541 Apr 16 14:50 manage.py
drwxr-xr-x 3 apache apache  4096 Apr 16 15:21 myproject
drwxr-xr-x 3 apache apache  4096 Apr 16 15:05 static</pre>
<p>
	
</p>
<p>
	最终浏览器访问django项目
</p>
<p>
	<span style="color:#E53333;">Tip:保证windows本地添加django服务器的HOST域名</span>
</p>
<p>
	
</p>
<p>
	django测试页面
</p>
<p>
	<a href="http://www.showerlee.com/?attachment_id=2560"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/django.png" alt="" width="800" height="582" class="alignnone size-full wp-image-2560" title="" align="" /></a>
</p>
<p>
	
</p>
<p>
	项目主页, 输入之前创建的管理员账号密码
</p>
<p>
	<a href="http://www.showerlee.com/?attachment_id=2561"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/home.png" alt="" width="800" height="349" class="alignnone size-full wp-image-2561" title="" align="" /></a>
</p>
<p>
	
</p>
<p>
	项目后台
</p>
<p>
	<a href="http://www.showerlee.com/?attachment_id=2559"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2018/04/dashboard.png" alt="" width="600" height="245" class="alignnone size-full wp-image-2559" title="" align="" /></a>
</p>
<p>
	
</p>
<p>
	Finished...</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2511">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS7.4部署Django+Python3+Apache+Mod_wsgi" href="http://www.showerlee.com/archives/2511">http://www.showerlee.com/archives/2511</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2511/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>[Python] Multiprocessing多线程任务</title>
		<link>http://www.showerlee.com/archives/2157</link>
		<comments>http://www.showerlee.com/archives/2157#comments</comments>
		<pubDate>Mon, 11 Dec 2017 07:32:18 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[python3]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2157</guid>
		<description><![CDATA[在编写Python时, 如果我们需要同一时间内执行多个任务, 我们可以利用python内建模块multipro [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	在编写Python时, 如果我们需要同一时间内执行多个任务, 我们可以利用python内建模块multiprocessing来让其并行执行某个方法.
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">1. 随机执行方法</span>
</p>
<p>
	# vi ~/multipro1.py
</p>
<pre class="prettyprint lang-py">import multiprocessing

def spawn(num):
    print('Sprawned! {}.'.format(num))


if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=spawn, args=(i,))

        p.start()</pre>
<p><span style="color:#337FE5;">2. 按顺序执行方法</span> </p>
<p>
	<span># vi ~/multipro2.py</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint lang-py">import multiprocessing


def spawn(num):
    print('Sprawned! {}.'.format(num))


if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=spawn, args=(i,))

        p.start()

        # Waiting to finish One by one
        p.join()</pre>
<p>
	<span style="color:#E53333;">Tip: 这里</span><span style="color:#E53333;"><strong>if __name__ == "__main__":</strong></span><span style="color:#E53333;">的作用:</span>
</p>
<p>
	<span style="color:#E53333;">1. 当直接执行该脚本时, 内建变量__name__的值被赋予"__main__", 所以按照if逻辑, python解释器可以继续执行接下来的代码.</span>
</p>
<p>
	<span style="color:#E53333;">2. 当其他脚本去调用(import)该脚本时, __name__的值被赋予当前脚本名"multipro1", 而不是"__main__", 所以按照if逻辑, 保证if下面的代码不会被其他脚本调用.</span>
</p>
<p>
	
</p>
<p>
	<span>所以在我们日常编写脚本的时候, 可以推荐按照如下结构, 在自己使用正常的同时, 保证在其他python脚本在调用test.py中的test1(), test2(), test3()的同时, 不会去执行if条件下的方法.</span>
</p>
<p>
	<span><span style="color:#000000;"># vi test.py</span></span>
</p>
<pre class="prettyprint lang-py">def test1():
    ....

def test2():
    ....

def test3():
    ....

if __name__ == "__main__":
    ....
</pre>
<p>
	<span style="color:#337FE5;">3. 多线程处理返回值.</span>
</p>
<p>
	# vi multipro3.py
</p>
<pre class="prettyprint lang-py">from multiprocessing import pool

def job(num):
	return num * 2

if __name__ == '__main__':
	p = Pool(processes=20)
	data = p.map(job, range(5))
	data2 = p.map(job, [5, 2])
	p.close()</pre>
<p>
	<span style="color:#337FE5;">4.多线程爬取<span style="color:#337FE5;">随机</span>网站URL</span>
</p>
<p>
	<span style="color:#337FE5;"><span style="color:#000000;"># vi ~/multipro4.py</span></span>
</p>
<p>
	<span style="color:#337FE5;"><span style="color:#000000;"></p>
<pre class="prettyprint lang-py">from multiprocessing import Pool
import bs4 as bs
import random
import requests
import string

# Return Four digits domain URL
def random_starting_url():
    starting = ''.join(random.SystemRandom().choice(
        string.ascii_lowercase) for _ in range(4))
    url = ''.join(['http://', starting, '.com'])
    return url


# Correct URL if it is relative
def handle_local_links(url, link):
    if link.startswith('/'):
        return ''.join([url, link])
    else:
        return link


# Get URL from "a" tag of 'body' tag
def get_links(url):
    try:
        # Request the URL
        resp = requests.get(url)
        # return the HTML
        soup = bs.BeautifulSoup(resp.text, 'lxml')
        # Get 'body' tag of the HTML
        body = soup.body
        # Get URL from "a" tag of 'body' tag
        links = [link.get('href') for link in body.find_all('a')]
        # Correct URL if it is relative
        links = [handle_local_links(url, link) for link in links]
        # Encoding the URL to ascii
        links = [str(link.encode('ascii')) for link in links]

        return links

    except TypeError as e:
        print(e)
        print('Got a TypeError, probably got a None that we tried to iterate over')
        return([])
    except IndexError as e:
        print(e)
        print('No valid link found, return a empty list')
        return([])
    except AttributeError as e:
        print(e)
        print('Likely got None for links, so we are throwing this')
        return([])
    except Exception as e:
        print(str(e))
        return([])


def main():
    # CPU process
    process = 5
    # The site intends to scrap
    site = 3
    p = Pool(processes=process)
    # Get random URL list
    parse_us = [random_starting_url() for _ in range(site)]
    # Multiprocessing the URL and parse the result
    data = p.map(get_links, parse_us)
    # Get each URL in a list
    data = [url for url_list in data for url in url_list]
    p.close()
    # Write to txt file
    with open('urls.txt', 'w') as f:
        f.write(str(data))


if __name__ == '__main__':
    main()
</pre>
<p>
</span></span>
</p>
<p>
	
</p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2157">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] Multiprocessing多线程任务" href="http://www.showerlee.com/archives/2157">http://www.showerlee.com/archives/2157</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2157/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] 利用Beautiful Soup+Pandas+Pyqt5+Selenum进行python爬虫</title>
		<link>http://www.showerlee.com/archives/2109</link>
		<comments>http://www.showerlee.com/archives/2109#comments</comments>
		<pubDate>Thu, 07 Dec 2017 03:34:16 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[其他]]></category>
		<category><![CDATA[python3]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2109</guid>
		<description><![CDATA[Beautiful Soup, pandas, pyqt5是一组非常方便的进行网络爬虫的python模块. B [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	Beautiful Soup, pandas, pyqt5是一组非常方便的进行网络爬虫的python模块.
</p>
<p>
	<span>Beautiful Soup主要从解析好的HTML源码中抓取我们所需要的关键内容</span>
</p>
<p>
	<span>Pandas与<span>Beautiful Soup类似, 不过它侧重去抓取源码中的表格信息</span></span>
</p>
<p>
	<span><span>pyqt5这里的作用是模拟浏览器去解析源码中的Javasript, 并最终抓取JS实际的返回值.</span></span>
</p>
<p>
	
</p>
<p>
	这里我在我的Flask env下创建了一个测试页面, 用这些模块进行一些简单的页面爬虫测试.
</p>
<p><a href="http://flask.showerlee.com/scrapingtest/" rel="nofollow">http://flask.showerlee.com/scrapingtest/</a></p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS:&nbsp; &nbsp; &nbsp; &nbsp;Windows 7 x64&nbsp; &nbsp;<br />
Python:&nbsp; &nbsp;Python3.6.2<br />
Git Bash: Git-2.15.1.2-64-bit
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;">一. 环境配置:</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;">1. 安装并运行Git bash</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;"><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">2. 安装并测试python版本</span><br />
</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;"></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;"><span style="color:#000000;">#</span><span style="color:#000000;">&nbsp;python -V</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;"><span style="color:#000000;"> </span></span>
</p>
<pre class="prettyprint lang-py">Python 3.6.2</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	3. 安装相关爬虫模块
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# python -m pip install beautifulsoup4&nbsp;lxml&nbsp;pandas&nbsp;html5lib&nbsp;<span>pyqt5&nbsp;selenum</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">二.&nbsp;</span><span style="color:#337FE5;font-size:16px;">Beautiful Soup演示</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi ~/scrap1.py
</p>
<p>
	<span style="color:#E53333;">Tip: 这里首先去调用io和sys模块是为了改变默认的标准输出为utf-8, 这么做是为了保证无论我们抓取的源页面是什么格式, 都不会在用BS解析时报</span><span style="color:#E53333;">UnicodeEncodeError.</span>
</p>
<pre class="prettyprint lang-py">import io
import sys
import bs4 as bs
import urllib.request

# 改变标准输出的默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

# 获取该页面编码并解码成utf-8
sauce = urllib.request.urlopen(
&nbsp; &nbsp; 'http://flask.showerlee.com/scrapingtest/').read().decode('utf-8')

# 利用BS抓取页面源代码,并利用lxml规范格式
soup = bs.BeautifulSoup(sauce, 'lxml')

# 获取页面源代码
print(soup)

# 获取titile标签源代码
print(soup.title)

# 获取titile标签name
print(soup.title.name)

# 获取titile标签字符
print(soup.title.string)
print(soup.title.text)

# 获取第一个p标签源代码
print(soup.p)

# 获取p标签源代码
print(soup.find_all('p'))

# 获取p标签所有内容
for paragraph in soup.find_all('p'):
&nbsp; &nbsp; print(paragraph.text)

# 获取页面所有内容
print(soup.get_text())

# 获取a标签所有内容
for url in soup.find_all('a'):
&nbsp; &nbsp; print(url.text)

# 获取a标签所有href链接
for url in soup.find_all('a'):
&nbsp; &nbsp; print(url.get('href'))

# 获取nav标签源代码
nav = soup.nav
print(nav)

# 获取nav标签URL
for url in nav.find_all('a'):
&nbsp; &nbsp; print(url.get('href'))

# 获取body标签内容
body = soup.body
for paragraph in body.find_all('p'):
&nbsp; &nbsp; print(paragraph.text)

# 获取div标签下body下的内容
for div in soup.find_all('div', class_='body'):
&nbsp; &nbsp; print(div.text)

# 获取table标签源代码
table = soup.table
# table = soup.find('table')
print(table)

# 获取table每行内容
table_rows = table.find_all('tr')

for tr in table_rows:
&nbsp; &nbsp; td = tr.find_all('td')
&nbsp; &nbsp; row = [i.text for i in td]
&nbsp; &nbsp; print(row)
<div>
	
</div>
</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap1.py</span>
</p>
<pre class="prettyprint lang-py">......</pre>
<p>
	<span style="color:#337FE5;font-size:16px;">三. Pandas</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># vi ~/scrap2.py</span>
</p>
<pre class="prettyprint lang-py">import pandas as pd

dfs = pd.read_html(
    'http://flask.showerlee.com/scrapingtest/', header=0)

for df in dfs:
    print(df)</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap2.py</span>
</p>
<pre class="prettyprint lang-py">  Program Name  Internet Points    Kittens?
0       Python        932914021  Definitely
1       Pascal              532    Unlikely
2         Lisp             1522   Uncertain
3           D#               12    Possibly
4        Cobol                3         No.
5      Fortran            52124        Yes.
6      Haskell               24        lol.</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">四. pyqt5</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	<span style="color:#000000;">这里我们首先不解析JS, 直接利用Beautiful Soup去抓取p标签下class=jstest的内容</span>
</p>
<p>
	# vi ~/scrap3.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">import io
import sys
import bs4 as bs
import urllib.request

# 改变标准输出的默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

# 获取该页面编码并解码成utf-8
sauce = urllib.request.urlopen(
    'http://flask.showerlee.com/scrapingtest/').read().decode('utf-8')

# 利用BS抓取页面源代码,并利用lxml规范格式
soup = bs.BeautifulSoup(sauce, 'lxml')

js_test = soup.find('p', class_='jstest')

print(js_test.text)</pre>
<p>
	
</p>
<p># python scrap3.py</p>
<pre class="prettyprint lang-py">No js loaded</pre>
<p><span style="color:#E53333;">可以看到实际抓取的为未被JS处理的标签内容</span> </p>
<p>
	
</p>
<p>
	
</p>
<p>
	这里利用pyqt5<span>去抓取p标签下class=jstest的内容</span>
</p>
<p>
	# vi ~/scrap4.py
</p>
<pre class="prettyprint lang-py">import bs4 as bs
import sys
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl


class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        # print('Load finished')

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()


def main():
    page = Page('http://flask.showerlee.com/scrapingtest/')
    soup = bs.BeautifulSoup(page.html, 'html.parser')
    js_test = soup.find('p', class_='jstest')
    print(js_test.text)


if __name__ == '__main__':
    main()
</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap4.py</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"> </span>
</p>
<pre class="prettyprint lang-py">js loaded successfully</pre>
<p>
	<span style="color:#E53333;">JS解析成功.</span>
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">四. selenum</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	首先我们需要从官网下载chrome driver, 并放到脚本同路径的driver目录里.
</p>
<p>
	
</p>
<p>
	这里需要查找匹配你当前chrome浏览器版本的driver版本. 这边我的chrome版本为62.0, 所以选择driver版本为2.35.
</p>
<p>
	
</p>
<p>
	# vi selenum.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
import time, sys, io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

def scrape():

	chromedriver = r".\driver\chromedriver.exe"
	URL = "http://flask.showerlee.com/scrapingtest/"

	try:
		driver = webdriver.Chrome(chromedriver)
		driver.set_window_position(-10000, 0)
		driver.get(URL)
		time.sleep(10)
		result = driver.execute_script("return document.body.innerHTML").encode('utf-8')
	except TimeoutException as e:
		print(e)

	soup = BeautifulSoup(result, "lxml")

	print(soup)

	driver.close()

scrape()</pre>
<p><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python selenum.py</span> </p>
<p>
	
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">...</pre>
<p>
	
</p>
<p>
	
</p>
<p>
	更多文档:
</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/</a></p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/</a></p>
<p><a href="http://pyqt.sourceforge.net/Docs/PyQt5/" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt5/</a></p>
<p><a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p>
<p><a href="https://chromedriver.storage.googleapis.com/index.html" rel="nofollow">https://chromedriver.storage.googleapis.com/index.html</a></p>
<p>
	
</p>
<p></p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2109">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] 利用Beautiful Soup+Pandas+Pyqt5+Selenum进行python爬虫" href="http://www.showerlee.com/archives/2109">http://www.showerlee.com/archives/2109</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2109/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CentOS6.9部署Python3+Flask+uWSGI+Nginx</title>
		<link>http://www.showerlee.com/archives/2024</link>
		<comments>http://www.showerlee.com/archives/2024#comments</comments>
		<pubDate>Wed, 18 Oct 2017 04:20:20 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Flask]]></category>
		<category><![CDATA[NGINX]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[python3]]></category>
		<category><![CDATA[uwsgi]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2024</guid>
		<description><![CDATA[最近在业余时间去学习python web开发, 并用Flask做了一个BLOG小程序放到我的个人仓库和Gith [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;"><a href="http://www.showerlee.com/archives/2024/flask01"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2017/10/flask01.png" alt="flask01" width="432" height="204" class="alignnone size-full wp-image-2091" /></a><br />
</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	最近在业余时间去学习python web开发, 并用<a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a>做了一个BLOG小程序放到我的个人仓库和Github仓库, 这里把自己的文档分享给大家, 仅供参考
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="https://github.com/showerlee/Flaskdev" target="_blank">https://github.com/showerlee/Flaskdev</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="https://git.showerlee.com/showerlee/Flaskdev" target="_blank">https://git.showerlee.com/showerlee/Flaskdev</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS(virtualbox): CentOS 6.9 x64 (flask.example.com)
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS(localhost):&nbsp; Windows 7 x64&nbsp; &nbsp;
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Python: Python3.4/Python2.6.6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a>: Flask 0.12.x
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	nWSGI:&nbsp;&nbsp;<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>-2.0.15
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Nginx:&nbsp; nginx-&nbsp;1.10.2-1.el6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;">一. 系统环境配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1.关闭iptables和selinux
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># su - root</span><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# service iptables stop
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># setenforce 0</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/sysconfig/selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	修改
</p>
<pre class="prettyprint lang-bsh">SELINUX=disabled</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;">2.添加本地host DNS</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/hosts</span>
</p>
<pre class="prettyprint lang-bsh">127.0.0.1    flask.example.com</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">二. Python配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1.安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.4源及依赖包
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># yum install epel-release -y</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum groupinstall "Development tools" -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel zx-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2.编译安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.4以及pip package manager
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# wget <a href="https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz" rel="nofollow">https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz</a> --no-check-certificate
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# tar xf Python-3.4.3.tar.xz
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd Python-3.4.3
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./configure --prefix=/usr/local --with-ensurepip=install
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# make &amp;&amp; make install
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	3.安装<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">virtualenv</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip install --upgrade pip
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip install virtualenv
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;">三. Nginx配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1. 安装nginx package
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install nginx -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2.配置nginx with nWSGI
</p>
<p>
	<span>#&nbsp;vi /etc/nginx/conf.d/flask.conf</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint">server {
    listen	 80;
    server_name  flask.example.com;  

    charset utf-8;

    access_log  /var/log/nginx/flask_access.log  main;
    error_log   /var/log/nginx/flask_error.log;


    location / { 
        try_files $uri @yourapplication; 
        client_max_body_size 32M;
    }
    location @yourapplication {
        include <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_params;
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_pass unix:/tmp/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>.sock;       
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_read_timeout 30s;
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_send_timeout 30s;
    }
}</pre>
<p>
	
</p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;">四. Flask+uWSGI配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1. uWSGI配置
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir -p /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>/uwsgi.ini
</p>
<pre class="prettyprint">[uwsgi]
base = /usr/share/nginx/html/flask
 
python-path = %(base)
app = hello
module = %(app)
callable = app
 
pidfile = /tmp/uwsgi-master.pid
touch-reload = /etc/uwsgi/bin/reload
 
master = true
processes = 5
enable-threads = true
 
limit-as = 512
 
# use unix socket because it is more secure and faster than TCP socket
socket = /tmp/uwsgi.sock
chmod-socket = 660
uid = nginx
gid = nginx
 
vacuum = true
die-on-term = true
emperor = true
 
logto = /var/log/nginx/uwsgi.log</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2. 配置Flask base folder
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd /usr/share/nginx/html
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir flask
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd flask
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# virtualenv -p /usr/local/bin/<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a> .py3env
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	3. 开启virtualenv python3环境
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">#&nbsp;source .py3env/bin/activate</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">4. 在此环境安装Flask相关模块</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# pip install flask uwsgi&nbsp;PyMySQL flask-wtf passlib
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">5. 写入Flask测试文件</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi hello.py
</p>
<pre class="prettyprint lang-py">from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()</pre>
<p>
	
</p>
<p>
	6. 创建uWSGI启动脚本
</p>
<p>
	# mkdir -p /etc/uwsgi/bin
</p>
<p>
	# vi&nbsp;<span>/etc/uwsgi/bin/uwsgi.sh</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint lang-bsh">#!/bin/bash
 
# Get function from functions library
. /etc/init.d/functions
 
BASE=/usr/share/nginx/html/flask
UWSGI=$BASE/.py3env/bin
INI=/etc/uwsgi
 
start() {
  echo -n "Starting server ..." 
  touch $INI/bin/reload
  $UWSGI/uwsgi --ini $INI/uwsgi.ini &gt;/dev/null 2&gt;&amp;1 &amp;
  success $"Started"
  echo
}
 
reload() {  
  $UWSGI/uwsgi --reload /tmp/uwsgi-master.pid
  success $ "Reloaded"
  echo
}
 
stop() {
  echo -n "Stopping server ..."
  $UWSGI/uwsgi --stop /tmp/uwsgi-master.pid
  success $ "Stopped"
  echo
}
 
### main logic ###
case "$1" in
  start) 
    start
    ;;
  stop)
    stop
    ;;
  reload)
    reload
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|reload}"
    exit 1
 
esac
exit 0</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"></span>
</p>
<p>
	
</p>
<p>
	7. 修改权限<span style="color:#E53333;">(可执行并保持与nginx启动user一致)</span>
</p>
<p>
	# chmod -R 755 <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chown -R nginx:nginx <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chmod -R 755 /usr/share/nginx/html/flask
</p>
<p>
	# chown -R nginx:nginx /usr/share/nginx/html/flask
</p>
<p>
	
</p>
<p>
	8.启动nginx+uwsgi
</p>
<p>
	# service nginx start
</p>
<p>
	#&nbsp;/etc/uwsgi/bin/uwsgi.sh start
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	展示效果<span style="color:#E53333;">(保证Windows本地host文件能够解析flask.example.com)</span>
</p>
<p>
	<a href="http://www.showerlee.com/archives/2024/flask"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2017/10/flask.png" alt="flask" width="483" height="164" class="alignnone size-full wp-image-2088" /></a>
</p>
<p>
	
</p>
<p>
	Finished...
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:18px;">Trouble shooting:</span>
</p>
<p>
	1.查看uwsgi log, 发现循环输出如下warning.
</p>
<p>
	# tail -f&nbsp;/var/log/nginx/uwsgi.log
</p>
<p>
	
</p>
<pre class="prettyprint lang-bsh">chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
...</pre>
<p><span style="color:#337FE5;">Solution:</span> </p>
<p>
	
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># cd /usr/share/nginx/html</span>
</p>
<p>
	#&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">source .py3env/bin/activate</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python hellp.py</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"> </span>
</p>
<pre class="prettyprint lang-bsh"> * Running on <a href="http://127.0.0.1:5000/" rel="nofollow">http://127.0.0.1:5000/</a> (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 126-450-249</pre>
<p>
	
</p>
<p>
	若无报错提示并显示如上输出, ctrl+C 强制退出. 并重启服务, 该warning即停止.
</p>
<p>
	<span style="color:#E53333;">Tip:&nbsp; 该方法亦可测试你的主方法文件是否有语法格式错误.</span>
</p>
<p>
	#&nbsp;<span>/etc/uwsgi/bin/uwsgi.sh start</span>
</p>
<p>
	该错误会偶尔在开发过程中添加新方法后出现, 暂不清楚原因, 有经验的朋友可以留言.
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"><br />
</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">My Flask APP for the reference:</span>
</p>
<p><a href="https://git.showerlee.com/showerlee/Flaskdev" rel="nofollow">https://git.showerlee.com/showerlee/Flaskdev</a></p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2024">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS6.9部署Python3+Flask+uWSGI+Nginx" href="http://www.showerlee.com/archives/2024">http://www.showerlee.com/archives/2024</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2024/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CentOS6升级python到2.7版本</title>
		<link>http://www.showerlee.com/archives/1706</link>
		<comments>http://www.showerlee.com/archives/1706#comments</comments>
		<pubDate>Thu, 29 Oct 2015 07:34:55 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1706</guid>
		<description><![CDATA[1.安装依赖包 #&#160;yum install zlib-devel bzip2-devel opens [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	<span style="line-height:1.5;">1.安装依赖包</span>
</p>
<p>
	#&nbsp;yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel wget xz -y
</p>
<p>
	
</p>
<p>
	2.编译安装python2.7
</p>
<p>
	# cd ~&nbsp;
</p>
<p>
	#&nbsp;wget --no-check-certificate <a href="https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz" rel="nofollow">https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz</a>
</p>
<p>
	#&nbsp;tar xvfJ Python-2.7.9.tar.xz&nbsp;
</p>
<p>
	#&nbsp;cd Python-2.7.9
</p>
<p>
	# ./configure --prefix=/usr/local&nbsp;LDFLAGS="-Wl,-rpath /usr/local/lib"
</p>
<p>
	#&nbsp;make &amp;&amp; make altinstall
</p>
<p>
	#&nbsp;ln -s /usr/local/bin/python2.7 /usr/local/bin/python
</p>
<p>
	退出SSH并重新登录
</p>
<p>
	# python -V
</p>
<pre class="prettyprint lang-bsh">Python 2.7.9</pre>
<p>
	# which python
</p>
<pre class="prettyprint lang-bsh">/usr/local/bin/python</pre>
<p>
	3.安装python setuptools
</p>
<p>
	#&nbsp;python ez_setup.py
</p>
<p>
	# which easy_install
</p>
<pre class="prettyprint lang-bsh">/usr/local/bin/easy_install</pre>
<p>
	#&nbsp;/usr/local/bin/easy_install-2.7 pip
</p>
<p>
	# ll /usr/local/bin
</p>
<pre class="prettyprint lang-bsh">total 6136
-rwxr-xr-x 1 root root     101 Oct 29 02:34 2to3
-rwxr-xr-x 1 root root     323 Oct 29 02:42 easy_install
-rwxr-xr-x 1 root root     331 Oct 29 02:42 easy_install-2.7
-rwxr-xr-x 1 root root      99 Oct 29 02:34 idle
-rwxr-xr-x 1 root root     287 Oct 29 02:48 pip
-rwxr-xr-x 1 root root     289 Oct 29 02:48 pip2
-rwxr-xr-x 1 root root     293 Oct 29 02:48 pip2.7
-rwxr-xr-x 1 root root      84 Oct 29 02:34 pydoc
lrwxrwxrwx 1 root root      24 Oct 29 02:36 python -&gt; /usr/local/bin/python2.7
-rwxr-xr-x 1 root root 6224569 Oct 29 02:34 python2.7
-rwxr-xr-x 1 root root    1687 Oct 29 02:34 python2.7-config
-rwxr-xr-x 1 root root   18547 Oct 29 02:34 smtpd.py</pre>
<p>
	升级完毕</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1706">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS6升级python到2.7版本" href="http://www.showerlee.com/archives/1706">http://www.showerlee.com/archives/1706</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1706/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[Python] 利用HTML页面查看字符串差异</title>
		<link>http://www.showerlee.com/archives/1580</link>
		<comments>http://www.showerlee.com/archives/1580#comments</comments>
		<pubDate>Mon, 28 Sep 2015 08:21:19 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1580</guid>
		<description><![CDATA[1. 比对两个字符串差异. # vi diff.py #!/usr/bin/env python import [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	1. 比对两个字符串差异.
</p>
<p>
	# vi diff.py
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import difflib

text1 = '''text1:
This mudule provides classes and fuctions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
'''
text1_lines = text1.splitlines()

text2 = '''text2:
This mudule provides classes and fuctions for Comparing sequences.
including HTML and  context and unified diffs.
difflib document v7.5
''' 
text2_lines = text2.splitlines()

#d = difflib.Differ()
#diff = d.compare(text1_lines, text2_lines)

#print '\n'.join(list(diff))

d = difflib.HtmlDiff()
print d.make_file(text1_lines, text2_lines)</pre>
<p>
	运行脚本并重定向为一个html静态页面
</p>
<p>
	# chmod 755 diff.py
</p>
<p>
	#&nbsp;./diff.py &nbsp;&gt; diff.html
</p>
<p>
	浏览器打开该页面
</p>
<p>
	如图:
</p>
<p>
	<a href="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150928-1.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150928-1-1024x186.png" alt="QQ20150928-1" width="1024" height="186" class="alignnone size-large wp-image-1581" /></a>
</p>
<p>
	2. 比对两个配置文件的差异.
</p>
<p>
	# vi diff02.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import difflib
import sys

try:
	textfile1 = sys.argv[1]
	textfile2 = sys.argv[2]
except Exception, e:
	print "Error: " + str(e)
	print "Usage: %s filename1 filename2" %sys.argv[0]
	sys.exit()

def readfile(filename):
	try:
		with open(filename, 'rb') as fileHandle:
			text = fileHandle.read().splitlines()
		return text
	except IOError as error:
		print ('Read file Error:' + str(error))
		sys.exit()

if not textfile1 or not textfile2:
	print "Usage: %s filename1 filename2" %sys.argv[0]
	sys.exit()

text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()

print d.make_file(text1_lines, text2_lines)</pre>
<p>#&nbsp;./diff02.py nginx.conf.v1 nginx.conf.v2 &gt;diff02.html</p>
<p>
	
</p>
<p>
	
</p>
<p>
	
</p>
<p><a href="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150929-1.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150929-1-1024x579.png" alt="QQ20150929-1" width="1024" height="579" class="alignnone size-large wp-image-1583" /></a></p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1580">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] 利用HTML页面查看字符串差异" href="http://www.showerlee.com/archives/1580">http://www.showerlee.com/archives/1580</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1580/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] SMTP(SSL)发送邮件</title>
		<link>http://www.showerlee.com/archives/1464</link>
		<comments>http://www.showerlee.com/archives/1464#comments</comments>
		<pubDate>Thu, 27 Aug 2015 06:33:45 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1464</guid>
		<description><![CDATA[这里需要注意的是大家使用QQ邮箱(SMTL over SSL)时, 需要首先在其网页客户端后台打开SMTP/P [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	这里需要注意的是大家使用<span>QQ邮箱(<span>SMTL over SSL</span>)时</span>, 需要首先在其网页客户端后台打开SMTP/POP服务, 并且设置QQ邮箱独立密码作为SMTP登陆密码, 这样在使用MUA时就不会报Authentication failed的错误.
</p>
<p>
	QQ邮箱&nbsp;<span style="line-height:1.5;">POP3端口: 995&nbsp;</span><span style="line-height:1.5;">SMTP端口: 587</span>
</p>
<p>
	密码使用QQ邮箱独立密码
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass

# Build a new attach instance
msg = MIMEMultipart()

# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with pic attachment'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.qq.com"  
SMTP_port = "587"
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "qq.com"  

# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '&lt;0&gt;')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s&lt;%s@%s&gt;" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)

    # Send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')

    try:  
        server = smtplib.SMTP(SMTP_server, SMTP_port)
        server.starttls()
        server.set_debuglevel(1)   
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False


if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure" </pre>
<p>
	
</p>
<div>
	
</div>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1464">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] SMTP(SSL)发送邮件" href="http://www.showerlee.com/archives/1464">http://www.showerlee.com/archives/1464</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1464/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] SMTP发送邮件</title>
		<link>http://www.showerlee.com/archives/1454</link>
		<comments>http://www.showerlee.com/archives/1454#comments</comments>
		<pubDate>Thu, 27 Aug 2015 05:01:51 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1454</guid>
		<description><![CDATA[这里PYTHON脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱. QQ邮箱利用的是加密STMP, 需要加 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	这里<a href="http://www.showerlee.com/archives/tag/python" title="查看PYTHON中的全部文章" class="tag_link">PYTHON</a>脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱.
</p>
<p>
	QQ邮箱利用的是加密STMP, 需要加密版本的童鞋请关注随后的更新.
</p>
<p>
	TIPS: 我的本地环境是MAC系统, Windows环境需要修改相应的字符编码.
</p>
<p>
	
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass

# Build a new attach instance
msg = MIMEMultipart()

# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with attachments'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.126.com"  
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "126.com"  

# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '&lt;0&gt;')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s&lt;%s@%s&gt;" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)

    # send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')

    try:  
        server = smtplib.SMTP()
        server.set_debuglevel(1) 
        server.connect(SMTP_server)  
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False


if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure" </pre>
<p>
	
</p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1454">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] SMTP发送邮件" href="http://www.showerlee.com/archives/1454">http://www.showerlee.com/archives/1454</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1454/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] re(正则表达式)模块详解</title>
		<link>http://www.showerlee.com/archives/1441</link>
		<comments>http://www.showerlee.com/archives/1441#comments</comments>
		<pubDate>Fri, 24 Apr 2015 07:00:54 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1441</guid>
		<description><![CDATA[一、Python中转义字符 &#160; 正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符，这里跟P [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">一、Python中转义字符</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; 正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符，这里跟Python的语法冲突，因此，Python用" \\\\ "表示正则表达式中的" \ "，因为正则表达式中如果要匹配" \ "，需要用\来转义，变成" \\ "，而Python语法中又需要对字符串中每一个\进行转义，所以就变成了" \\\\ "。</span><br />
<span style="font-family:Verdana;"> 上面的写法是不是觉得很麻烦，为了使正则表达式具有更好的可读性，Python特别设计了原始字符串(raw string)，需要提醒你的是，在写文件路径的时候就不要使用raw string了，这里存在陷阱。raw string就是用'r'作为字符串的前缀，如 r"\n"：表示两个字符"\"和"n"，而不是换行符了。Python中写正则表达式时推荐使用这种形式。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">二、正则表达式元字符说明：</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">. &nbsp; &nbsp;匹配除换行符以外的任意字符</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">^ &nbsp; &nbsp;匹配字符串的开始</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">$ &nbsp; &nbsp;匹配字符串的结束</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">[] &nbsp; 用来匹配一个指定的字符类别</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">？ &nbsp; <span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span>前一个字符字符0次到1次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">* &nbsp; &nbsp;<span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span>前一个字符0次到无穷次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">+&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span><span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">前一个字符1次到无穷次</span></span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">{} &nbsp; 对于前一个字符重复m次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">{m，n} 对前一个字符重复为m到n次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\d &nbsp; 匹配数字，相当于[0-9]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\D &nbsp; 匹配任何非数字字符，相当于[^0-9]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\s &nbsp; 匹配任意的空白符，相当于[ fv]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\S &nbsp; 匹配任何非空白字符，相当于[^ fv]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\w &nbsp; 匹配任何字母数字字符，相当于[a-zA-Z0-9_]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\W &nbsp; 匹配任何非字母数字字符，相当于[^a-zA-Z0-9_]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\b &nbsp; 匹配单词的开始或结束</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">三、导入正则表达式模块</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">3.1、导入正则表达式模块</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; import &nbsp;re</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">3.2、查看正则表达式模块方法</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; dir(re)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']</span><br />
<span style="font-family:Verdana;"> &gt;&gt;&gt;</span></p>
<p><span style="font-family:Verdana;"> 四、常用的正则表达式处理函数</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.1、re.search</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; &nbsp;re.search 函数会在字符串内查找模式匹配，只到找到第一个匹配然后返回，如果字符串没有匹配，则返回None。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 提示：当我们不会用模块方法的时候用help</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.search)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">search(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第二个参数：表示要匹配的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第三个参数：标致位，用于控制正则表达式的匹配方式</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 实例：下面的例子kuangl&nbsp;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; name="Hello,My name is kuangl,nice to meet you..."</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.search(r'k(uan)gl',name)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; if k:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... &nbsp; &nbsp; print k.group(0),k.group(1)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... else:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... &nbsp; &nbsp; print "Sorry,not search!"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">...</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">kuangl uan</span><br />
<span style="line-height:1.5;"><br />
</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">4.2、re.match</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp; re.match 尝试从字符串的开始匹配一个模式，也等于说是匹配第一个单词</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.match)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">match(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第二个参数：表示要匹配的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第三个参数：标致位，用于控制正则表达式的匹配方式</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 实例：下面的例子匹配Hello单词</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; name="Hello,My name is kuangl,nice to meet you..."</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.match(r"(\H....)",name)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; if k:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... &nbsp; &nbsp; &nbsp;print k.group(0),'\n',k.group(1)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... else:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... &nbsp; &nbsp; print "Sorry,not match!"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">...</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">Hello</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">Hello</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp; &nbsp;re.match与re.search的区别：re.match只匹配字符串的开始，如果字符串开始不符合正则表达式，则匹配失败，函数返回None；而re.search匹配整个字</span><span style="font-family:Verdana;line-height:1.5;">串，直到找到一个匹配。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.3、re.findall</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; re.findall 在目标字符串查找符合规则的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.findall)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">findall(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：目标字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;但三个参数：后面还可以跟一个规则选择项</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;返回的结果是一个列表，建中存放的是符合规则的字符串，如果没有符合规则的字符串呗找到，就会返回一个空值。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：查找邮件账号</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; mail='&lt;user01@mail.com&gt; &lt;user02@mail.com&gt; <a href="mailto:user04@mail.com">user04@mail.com</a>' #第3个故意没有尖括号</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.findall(r'(\w+@m....[a-z]{3})',mail)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['user01@mail.com', 'user02@mail.com', 'user04@mail.com']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.4、re.sub</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.sub 用于替换字符串的匹配项</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.sub)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">sub(pattern, repl, string, count=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：替换后的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第三个参数：字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第四个参数：替换个数。默认为0，表示每个匹配项都替换</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：将空白处替换成-</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.sub(r'\s','-',test)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">'Hi,-nice-to-meet-you-where-are-you-from?'</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.sub(r'\s','-',test,5) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#替换至第5个</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">'Hi,-nice-to-meet-you-where are you from?'</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.5、re.split</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.split 用于来分割字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.split)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">split(pattern, string, maxsplit=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第二个参数：字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第三个参数：最大分割字符串，默认为0，表示每个匹配项都分割</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;实例：分割所有的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; re.split(r"\s+",test)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">['Hi,', 'nice', 'to', 'meet', 'you', 'where', 'are', 'you', 'from?']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; re.split(r"\s+",test,3) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#分割前三个</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">['Hi,', 'nice', 'to', 'meet you where are you from?']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.6、re.compile</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.compile 可以把正则表达式编译成一个正则对象</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.compile)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">compile(pattern, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：标志位&nbsp;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.compile(r'\w*o\w*') #匹配带o的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; dir(k)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; print k.findall(test) &nbsp; &nbsp; #显示所有包涵o的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['to', 'you', 'you', 'from']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; print k.sub(lambda m: '[' + m.group(0) + ']',test) &nbsp;# 将字符串中含有o的单词用[]括起来</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">Hi, nice [to] meet [you] where are [you] [from]?</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">五、用urllib2、re、os 模块下载文件的脚本</span>
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import urllib2
import re
import os
URL='http://image.baidu.com/channel/wallpaper'
read=urllib2.urlopen(URL).read()
pat =  re.compile(r'src="http://.+?.js"&gt;')
urls=re.findall(pat,read)
for i in urls:
    url= i.replace('src="','').replace('"&gt;','')
try:
    iread=urllib2.urlopen(url).read()
    name=os.path.basename(url)
    with open(name,'wb') as jsname:
    jsname.write(iread)
except:
    print url,"url error"</pre>
<p>
	
</p>
<div style="padding:0px;margin:0px;color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
</div>
<p>
	
</p>
<div style="padding:0px;margin:0px;color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
</div>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1441">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] re(正则表达式)模块详解" href="http://www.showerlee.com/archives/1441">http://www.showerlee.com/archives/1441</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1441/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
