一、Web原理
1、客户端 <=> WEB服务器(nginx/apache)<=> 转发动态请求 <=> Python <=> 数据库
具体:
客户端 <=> WEB服务器(nginx/apache)<=> wsgi服务 <=> Python <=> 数据库
2、WSGI
WSGI是全称是“Web Server Gateway Interface”
二、web应用
1、在虚拟机中创建文件夹
mkdir flask
cd flask/
ls
vim webapp.py
vim wsgi_server.py
按i进入编辑模式
2、webapp.py
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return '<b>Hello World</b>'
3、wsgi_server.py
# 这是一个官方提供的仅用于测试的wsgi程序
from wsgiref.simple_server import make_server
# 导入自己的框架
from webapp import application
# 创建一个服务
# 参数:host port 执行的任务
server = make_server('10.224.168.219', 5000, application)
# 启动服务
server.serve_forever()
4、启动
python3 wsgi_server.py
可能会打不开,需要将防火墙关掉
service iptables stop
5、测试 浏览器中输入:http://10.224.168.219:5000
三、uWSGI
1、uWSGI 是专门的wsgi程序
2、安装:pip install uwsgi
3、启动:uwsgi --http 10.224.168.219:5000 --wsgi-file webapp.py
4、配置文件:
(1)参数1:http、socket —— 指定主机和端口
(2)参数2:wsgi-file —— 应用所在的模块
(3)参数3:chdir —— 启动程序后的当前目录
(4)参数4:callable —— 指定应用程序的实例
四、Nginx+uWSGI+Flask的使用
1、Nginx(添加虚拟主机)
server {
listen 80;
server_name www.flask.com;
location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:5000;
}
}
启动Nginx或重新加载配置文件
重启nginx:service nginx restart
重新加载配置:service nginx reload
2、uWSGI
[uwsgi]
# 指定socket的主机端口
socket = 127.0.0.1:5000
# 指定的模块
wsgi-file = webapp.py
# 应用实例
callable = app
启动服务:uwsgi uwsgi.ini
3、书写flask项目
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello Flask'
if __name__ == '__main__':
app.run()
4、添加本地的域名解析
修改文件:C:\Windows\System32\drivers\etc\hosts
末尾添加内容:10.224.168.219 www.flask.com
5、测试服务
在浏览器中输入:http://www.flask.com