gunicorn+flask搭建服务框架

1、常见gunicorn配置详解

1.1、什么是gunicorn

Gunicorn是一个WSGI HTTP服务器,python自带的有个web服务器,叫做wsgiref,
Gunicorn的优势在于,它使用了pre-fork worker模式,gunicorn在启动时,会在主进程中预先fork出指定数量的worker进程来处理请求,
gunicorn依靠操作系统来提供负载均衡,推进的worker数量是(2*$num_cores)+1
我们知道,python是单线程的语言,当进程阻塞时,后续请求将排队处理。所用pre-fork worker模式,极大提升了服务器请求负载。

1.2、gunicorn安装

apt-get install gunicorn

1.3、编写wsgi接口,test.py代码如下

def application(environ,start_response):
    start_response('200 OK',[('Content-Type','text/html')])
    return b'<h1>Hello,web!</h1>'

1.4.使用gunicorn监听请求,运行以下命令

gunicorn -w 2 -b 0.0.0.0:8000 test.application

运行结果:

-w:指定fork的worker进程数
-b:指定绑定的端口
test:模块名,python文件名
application:变量名,python文件中可调用的wsgi接口名称

1.5、访问web服务器   


和使用wsgiref,访问wsgi接口一致

1.6、gunicorn相关参数

1)-c CONFIG,--config=CONFIG
指定一个配置文件(py文件)
2)-b BIND,--bind=BIND
与指定socket进行板顶
3)-D,--daemon
后台进程方式运行gunicorn进程
4)-w WORKERS,--workers=WORKERS
工作进程的数量
5)-k WORKERCLASS,--worker-class=WORKERCLASS
工作进程类型,包括sync(默认),eventlet,gevent,tornado,gthread,gaiohttp
6)--backlog INT
最大挂起的连接数
7)--log-level LEVEL
日志输出等级

输出error log的颗粒度,有效的LEVEL有:

  • debug

  • info

  • warning

  • error

  • critical

8)--access-logfile FILE
访问日志输出文件
9)--error-logfile FILE
错误日志输出文件

2、gunicorn参数配置文件

2.1、gunicorn指定方式


-c CONFIG,--config=CONFIG 指定一个配置文件(py文件)
gunicorn可以写在配置文件中,下面举列说明配置文件的写法,conf.py

bind = "0.0.0.0:8000"
workers = 2

运行以下命令:

gunicorn -c conf.py test:application

运行结果和使用命令行参数,结果一样。

gunicorn配置文件是一个python文件,因此可以实现更复杂的逻辑,如下:

# conf.py
import logging
import logging.handlers
from logging.handlers import WatchedFileHandler
import os
import multiprocessing
bind = '127.0.0.1:8000'      #绑定ip和端口号
backlog = 512                #监听队列
chdir = '/home/test/server/bin'  #gunicorn要切换到的目的工作目录
timeout = 30      #超时
worker_class = 'gevent' #使用gevent模式,还可以使用sync 模式,默认的是sync模式

workers = multiprocessing.cpu_count() * 2 + 1    #进程数
threads = 2 #指定每个进程开启的线程数
loglevel = 'info' #日志级别,这个日志级别指的是错误日志的级别,而访问日志的级别无法设置
access_log_format = '%(t)s %(p)s %(h)s "%(r)s" %(s)s %(L)s %(b)s %(f)s" "%(a)s"'    #设置gunicorn访问日志格式,错误日志无法设置

"""
其每个选项的含义如下:
h          remote address
l          '-'
u          currently '-', may be user name in future releases
t          date of the request
r          status line (e.g. ``GET / HTTP/1.1``)
s          status
b          response length or '-'
f          referer
a          user agent
T          request time in seconds
D          request time in microseconds
L          request time in decimal seconds
p          process ID
"""
accesslog = "/home/test/server/log/gunicorn_access.log"      #访问日志文件
errorlog = "/home/test/server/log/gunicorn_error.log"        #错误日志文件

 

2.2、gunicorn配置方式

Gunicorn从三个不同地方获取配置:

  • 框架设置(通常只影响到Paster应用)

  • 配置文件(python文件):配置文件中的配置会覆盖框架的设置。

  • 命令行

框架设置只跟Paster(一个Web框架)有关,不讨论;命令行配置如上部分所示;现在我们看下怎么用配置文件配置gunicorn:

配置文件必须是一个python文件,只是将命令行中的参数写进py文件中而已,如果需要设置哪个参数,则在py文件中为该参数赋值即可。例如:

# example.py
bind = "127.0.0.1:8000"
workers = 2

运行gunicorn:

$ gunicorn -c example.py test:app

等同于:

$ gunicorn -w 2 -b 127.0.0.1:8000 test:app

 

3、python获取本地真实ip

import socket
myname=socket.getfqdn(socket.gethostname())
ip=socket.gethostbyname(myname)
print("computerName:{},ip:{}".format(myname,ip))

#输出computerName:jsydeMacBook-Pro.local,ip:10.31.72.59

4、gunicorn+flask从请求body获取参数

from flask_restful import reqparse;reqparse解析参数,详情可参考网址:http://www.pythondoc.com/Flask-RESTful/reqparse.html#id3;简单的例子如下

from flask_restful import reqparse

# request参数解析详解
# http://www.pythondoc.com/Flask-RESTful/reqparse.html#id3
reqparser = reqparse.RequestParser()
# 必须参数
reqparser.add_argument('name', type=str, required=True,help="Name cannot be blank!")

# 可选参数
reqparser.add_argument('id', type=int)

5、参考

https://blog.csdn.net/qq_43475458/article/details/108059922(gunicorn配置详解)

https://www.cnblogs.com/chenjingyi/p/5741742.html(python获取ip地址)

https://www.jianshu.com/p/fecf15ad0c9a (flask+gunicorn服务部署)

https://lvxiaoyu.com/static/posts/20170613.3.html  (FlaskBlueprint的区别)
http://www.pythondoc.com/Flask-RESTful/quickstart.html(add_resource
详解)

http://www.pythondoc.com/Flask-RESTful/reqparse.html#id3(reqparse参数解析详解)

猜你喜欢

转载自blog.csdn.net/u013069552/article/details/113516985