python搭建Web需要的环境配置
环境:centos7.6 +Python2.7+Apache2.4
- 安装python虚拟环境
12pip install virtualenv #py2安装pip3 install virtualenv #py3安装 - 创建虚拟环境(需要安装virtualenv(可以让每一个python项目单独使用一个环境,而不会影响python系统环境,也不会影响其他项目的环境)),系统中的python模块在虚拟环境中不能直接使用
123mkdir django_projectcd django_projectvirtualenv venv #创建虚拟环境,虚拟环境名字‘venv’ - 在虚拟环境里安装django()
123456789101112source venv/bin/activate #进入virtualenv的虚拟开发环境,会显示(vene),代表已经进入了这个环境,然后就可以安装Djangopip install django# 删除虚拟环境# rm -r venv# 需要在虚拟环境中另外安装虚拟环境的python模块# pip install numpy #安装numpy# pip install scipy# pip install matplotlib# 查看虚拟环境中已经安装的包:pip list# deactivate 退出虚拟环境 - 创建django项目
1234django-admin.py startproject mysitecd mysite#测试项目,测试正常后,ctrl+c结束python manage.py runserver - 安装apache
123yum install httpd httpd-devel -y#python组件 python-develyum install python-devel - 安装apache所需的mod_wsgi模块
12yum -y install mod_wsgi#或者pip install mod_wsgi - 查看apache2是否导入mod_wsgi模块
1grep -r 'mod_wsgi.so' /etc/httpd/ - 新建一个apache的虚拟主机
1234567891011121314vi /etc/httpd/conf.d/django.conf<Directory /var/www/html/django_project/mysite/mysite><Files wsgi.py>Require all granted</Files></Directory>WSGIPythonHome /var/www/html/django_project/venvWSGIPythonPath /var/www/html/django_project/venv/lib/python2.7/site-packagesListen 8080<VirtualHost *:8080>ServerName django.example.comWSGIScriptAlias / /var/www/html/django_project/mysite/mysite/wsgi.py</VirtualHost> - 重启apache
1systemctl restart httpd httpd -k restart - wsgi.py配置
这个问题差点被搞死,我以为会自动把相关配置弄好,结果我错了,需要加一个路径 /var/www/html/django_project1/mysite/(项目路径)
1import os import sys sys.path.append('/var/www/html/django_project1/mysite/') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "salt_web.settings") application = get_wsgi_application() - 配置settings.py ,设置允许访问的地址
1ALLOWED_HOSTS = ['175.24.114.227']
- 配置urls.py
1from django.conf.urls import url from . import views urlpatterns = [ url('hello/', views.hello), url('test/', views.hello), ]
- 配置views.py
1from django.shortcuts import render from django.http import HttpResponse import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import numpy as np import io import base64 def hello(request): np.random.seed(1000) y = np.random.standard_normal(20) plt.plot(y.cumsum()) plt.grid(True) plt.xlim(-1, 20) plt.ylim(np.min(y.cumsum()) - 1, np.max(y.cumsum()) + 1) plt.show() buf = io.BytesIO() plt.savefig(buf, format='png') base64_png = base64.b64encode(buf.getvalue()) # response = HttpResponse(buf.getvalue(),content_type='image/png') context = {} context['hello'] = 'Python Test' context['image'] = base64_png return render(request, 'hello.html', context)
- 添加模板文件
1cd project mkdir templates vim test.html #修改settings.py,修改 TEMPLATES 中的 DIRS 为 [os.path.join(BASE_DIR, 'templates')],如下所示: ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 修改位置 BASE_DIR与 manage.py 目录同级 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ... #views.py from django.shortcuts import render def runoob(request): context = {} context['hello'] = 'Hello World!' #要传递到模板的参数 hello return render(request, 'runoob.html', context) #指定模板名称,传递参数 #test.html <h1>{{ hello }}</h1> #参数页面显示
- 图片显示空白,
1from django.shortcuts import render from django.http import HttpResponse import matplotlib as mpl mpl.use('Agg') #需要使用agg import matplotlib.pyplot as plt import numpy as np import io import base64 def hello(request): np.random.seed(1000) y = np.random.standard_normal(20) plt.plot(y.cumsum()) plt.grid(True) plt.xlim(-1, 20) plt.ylim(np.min(y.cumsum()) - 1, np.max(y.cumsum()) + 1) plt.show() buf = io.BytesIO() plt.savefig(buf, format='png') base64_png = base64.b64encode(buf.getvalue()) plt.close() buf.close() # response = HttpResponse(buf.getvalue(),content_type='image/png') context = {} context['hello'] = 'Python Test' context['image'] = base64_png return render(request, 'hello.html', context)
- 模板内加载静态资源 static
123456789101112131415161718192021222324252627# INSTLLED_APPS中的django.contrib.staticfiles必须删除或者注释掉,DEBUG模式必须开启STATIC_URL = '/static/'STATIC_ROOT = os.path.join(BASE_DIR, 'static/')INSTALLED_APPS = [# 'django.contrib.staticfiles',]DEBUG = True#在urls.py中,再配置url路由from django.conf.urls import urlfrom django.contrib import adminfrom django.conf import settings #引入settingsfrom django.conf.urls.static import static #引入staticfrom . import viewsurlpatterns = [url(r'^index/', views.index),url('hello/', views.hello),url('test/', views.test),url('zero/', views.zero),url('one/', views.one),url('two/', views.two),url('three/', views.three),#path('hello/', views.hello),url(r'^admin/', admin.site.urls),]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
- 语言编码
123# -*- coding: UTF-8 -*-# coding=utf-8# 文件名:test.py
注意事项:
- apache日志查看: /var/log/httpd/error_log
- mod_wsgi 模块 apache无法加载,可能是python版本不一致:
下载mod_wsgi安装包:
1curl https://files.pythonhosted.org/packages/47/69/5139588686eb40053f8355eba1fe18a8bee94dc3efc4e36720c73e07471a/ mod_wsgi-4.6.5.tar.gz -o mod_wsgi-4.6.5.tar.gz tar -zxvf mod_wsgi-4.6.5.tar.gz cd mod_wsgi-4.6.5 #使用指定的python版本安装mod_wsgi python2.7 setup.py install
安装成功后配置apache加载wsgi模块,使用mod_wsgi-express install-module查询mod_wsgi.so的路径,输出如下:
123[root@javen-zhao mod_wsgi-4.6.5]# mod_wsgi-express install-moduleLoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py27.so"WSGIPythonHome "/usr"
在Apache模块配置目录/etc/httpd/conf.modules.d/创建一个mod_wsgi.conf配置文件,加入上面的内容:
123vim mod_wsgi.confLoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py27.so"#WSGIPythonHome "/usr"
重新启动apache检查是否配置成功:
1httpd -k restart
查看apache的错误日志:
123456tail -f /var/log/httpd/error_log[Thu Dec 20 16:08:40.307003 2018] [lbmethod_heartbeat:notice] [pid 14097] AH02282: No slotmem from mod_heartmonitor[Thu Dec 20 16:08:40.309895 2018] [mpm_prefork:notice] [pid 14097] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/4.6.5 Python/2.7configured -- resuming normal operations[Thu Dec 20 16:08:40.309917 2018] [core:notice] [pid 14097] AH00094: Command line: 'httpd'