Mac上使用uWSGI

  • 通过pip install uwsgi 和brew install uwsgi的区别

pip install uwsgi 安装在python的目录下,在命令窗口下输入uwsgi会提示找不到该命令(MAC 环境下是这样,在服务器上都是直接通过pip 来安装)。

brew install uwsgi 会将uwsgi安装在/usr/local/Cellar/目录下,在全局可以直接使用uwsgi执行各种命令。

  • uwsgi命令
uwsgi --http-socket :8081 --plugin python --wsgi-file main.py --stats 127.0.0.1:8888 --daemonize /var/log/uwsgi.log

--http-socket :8081 指定端口号

--wsgi-file main.py 指定启动文件

--plugin python 指定使用python插件解析(遇到 unrecognized option ‘--uwsgi-file‘如 --module , --wsgi-file , --callable 等都可以使用该命令指定解析器,在Mac上使用brew 安装的uwsgi执行命令会提示有一些配置参数找不到)

deMacBook-Pro:site-packages anonyper$ uwsgi --http-socket :8081 --wsgi-file main.py
uwsgi: unrecognized option `--wsgi-file'
getopt_long() error
deMacBook-Pro:site-packages anonyper$

--stats 127.0.0.1:8888 在127.0.0.1:8888可以用过uwsgitop查看服务器性能状态

--daemonize /var/log/uwsgi.log 记录日志到该文件内(加了该命令后普通的杀掉进程之后服务还会重启,需要强制kill -9 才能杀掉,因为daemonize增加守护进程,使web服务更加稳定)

--disable-loggin, 不记录请求信息的日志。只记录错误以及uWSGI内部消息到日志中。

  • 在执行的py中需要有application方法或者使用web.py时转换一个application对象

如下

#!/usr/bin/python
def application(env, start_response):
    start_response('200 OK', [('Content_Type', 'text/html')])
    return "Congraduation!!! uWSGI Testing OK!!!"

或者

# -*- coding: utf-8 -*-
"""
@file: main.py

@time: 18-6-12
"""

import web
urls = (
    '/test/hello', 'hello',
)

app = web.application(urls, globals())


class hello:
    def GET(self):
        web.header("Access-Control-Allow-Origin", "*")
        post_data = dict(web.input())
        name = post_data.get('name', 'zhangsan')
        return 'Hello, ' + 'zhangsan' + '!' + name


if __name__ == "__main__":
    app.run()

以上都是main_test.py的内容,执行命令如下:

uwsgi --http-socket :8081 --plugin python --wsgi-file main_test.py
  • uwsgitop查看服务器性能(虽然没看明白有啥用)

安装uwsgitop可以使用pip install uwsgitop或者brew install uwsgitop

uwsgitop 127.0.0.1:8888

使用该命令需要在使用uwsgi命令时增加--stats 127.0.0.1:8888的命令

  • 通过配置文件,启动uwsgi服务

定义一个xxx.ini的文件,使用key=value的方式来写配置参数。然后在命令行中输入uwsgi xxx.ini(uwsgi --ini xxx.ini)如:

[uwsgi]
http-socket = :8081
plugin = python
wsgi-file = ./main_test.py
processes = 4 #workers个数,也是进程数
threads = 4 # 线程数
max-request = 20480

等价于在命令行输入

uwsgi --http-socket :8081 —plugin python --wsgi-file main.py --processes 4 --threads 4 --max-request 20480
  • 其他配置
--master(-M), 启动主进程,方便管理所有进程, 可以配合--pidfie 使用。方便停止(uwsgi --stop /tmp/uwsgi.pid)/重启uwsgi ( uwsgi --reload /tmp/uwsgi.pid)
--listen (-l), 内核监听(listen)网络队列的长度,受文件操作系统最大的网络连接数(net.core.somaxconn) 的限制, 长度越大意味着在高并发的环境下,丢失请求越少。
--memory-report, 开启内存占用报告(uwsgitop中可以看到) 
  • 参考消息

http://www.cnblogs.com/zhouej/archive/2012/03/25/2379646.html

https://uwsgi-docs.readthedocs.io/en/latest/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。