nginx+uwsgi+python捕获http消息并处理(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuweigangzwg/article/details/78095051

nginx+uwsgi+python捕获http消息并处理(一)

写本文的目的及应用场景,当http发送消息给nginx,我们要捕获并处理这个消息时可以采用的方法有例如,给nginx加一个module,写nginx的lua程序,或者用uwsgi去对接nginx;python是具体具体接收消息并处理的程序。这里简单介绍nginx+uwsgi+python捕获http消息并处理。


1:安装uwsgi

在linux系统系统中执行

sudo add-apt-repository ppa:stevecrozz/ppa /
sudo apt-get update
sudo apt-get install uwsgi

完成安装。


2:nginx的配置

在nginx的http的模块配置中配置如下

	location /gvc_uwsgi { #处理uwsgi
  		include uwsgi_params;  
  		uwsgi_pass 127.0.0.1:9090;
	}
其中9090就是我用到的端口。gvc_uwsgi就是我们的 http模块中location地址。


3:编写处理的python命名为uwsgi_test.py

def application(environ, start_response):
   # the environment variable CONTENT_LENGTH may be empty or missing
   try:
      request_body_size = int(environ.get('CONTENT_LENGTH', 0))
   except (ValueError):
      request_body_size = 0
   print(request_body_size)

   # When the method is POST the query string will be sent
   # in the HTTP request body which is passed by the WSGI server
   # in the file like wsgi.input environment variable.
   request_body = environ['wsgi.input'].read(request_body_size)   #获取request_body
   print(request_body)
....
....
具体的处理
....
....
   status = "200 OK"
   response_headers = [('Content-type', 'text/plain')]
   start_response(status, response_headers)
application(environ, start_response):就是我们的程序入口,request_body是接收到的http消息,response_body是返回的内容。


4:启动

首先启动nginx这里不说明,启动uwsgi命令如下:

sudo uwsgi -s 127.0.0.1:9090 --plugin python --wsgi-file uwsgi_test.py

uwsgi_test.py就是我们写的python脚本。


5:给nginx发送模拟消息

这里用火狐浏览器的httprequester模拟发送http消息

例如:20170830:152700:1000:-1:2001:3001发送这个消息。

发送地址:http://10.144.96.157:8080/gvc_uwsgi,注意这里的ip是nginx的ip,这个8080是nginx的http的模块配置,不是那个uwsgi的9090端口,gvc_uwsgi就是我们http模块中location地址。


6:运行结果






可以看到打印的http消息,具体处理根据不同业务做处理。


如有错误请指正:

交流请加QQ群:62054820
QQ:379969650.



猜你喜欢

转载自blog.csdn.net/zhuweigangzwg/article/details/78095051