网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

如何在python中使用Gunicorn服务器-创新互联

如何在python中使用Gunicorn服务器?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名雅安服务器托管、营销软件、网站建设、东乡族网站维护、网站推广。1. 简介

Gunicorn(Green Unicorn)是给Unix用的WSGI HTTP 服务器,它与不同的web框架是非常兼容的、易安装、轻、速度快。

如何在python中使用Gunicorn服务器

2. 示例代码1
def app(environ, start_response):
  data = b"Hello World\n"
  start_response("200 OK", [
    ("Content-Type", "test/plain"),
    ("Content-Length", str(len(data)))
  ])
  return iter([data])

启动

gunicorn -w 4 myapp:app

起来后显示

[2016-12-12 00:20:12 +0000] [11755] [INFO] Starting gunicorn 19.6.0
[2016-12-12 00:20:12 +0000] [11755] [INFO] Listening at: http://127.0.0.1:8000 (11755)
[2016-12-12 00:20:12 +0000] [11755] [INFO] Using worker: sync
[2016-12-12 00:20:12 +0000] [11760] [INFO] Booting worker with pid: 11760
[2016-12-12 00:20:12 +0000] [11761] [INFO] Booting worker with pid: 11761
[2016-12-12 00:20:12 +0000] [11762] [INFO] Booting worker with pid: 11762
[2016-12-12 00:20:12 +0000] [11763] [INFO] Booting worker with pid: 11763

此时,调用http://127.0.0.1:8000

$curl http://127.0.0.1:8000
Hello World

参数说明

-w 处理HTTP请求的worker进程数,以下两种启动方式等价

gunicorn -w 4 myapp:app
gunicorn --workers=4 myapp:app

参考:

 -w INT, --workers INT
            The number of worker processes for handling requests.

问题:为何调用 http://ip:8000不行呢, 这个是什么请求呢?

默认有-b参数,参考

 -b ADDRESS, --bind ADDRESS
            The socket to bind. [['127.0.0.1:8000']]

以下方式启动就可以用ip的方式启动了

sudo gunicorn -w 2 -b 0.0.0.0:4000 myapp:app
3. 示例代码2

之前简单的flask方法

from flask import Flask
app = Flask(__name__)

@app.route('/hello.world')
def check():
  return 'hello world!'


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

启动

$sudo gunicorn -b 0.0.0.0:300 -w 4 myapp3:app
[2016-12-18 19:19:51 +0000] [21005] [INFO] Starting gunicorn 19.6.0
[2016-12-18 19:19:51 +0000] [21005] [INFO] Listening at: http://0.0.0.0:300 (21005)
[2016-12-18 19:19:51 +0000] [21005] [INFO] Using worker: sync
[2016-12-18 19:19:51 +0000] [21010] [INFO] Booting worker with pid: 21010
[2016-12-18 19:19:51 +0000] [21011] [INFO] Booting worker with pid: 21011
[2016-12-18 19:19:51 +0000] [21014] [INFO] Booting worker with pid: 21014
[2016-12-18 19:19:51 +0000] [21017] [INFO] Booting worker with pid: 21017

测试

$curl localhost:300/hello.world
hello world!
4. 启动异常
[ERROR] Connection in use: ('127.0.0.1', 8000)

原因之一是之前启动的进程没有杀死。

注:ctrl+z 是挂起进程,但没有终止。ctrl+c是终止进程。

如果使用了ctrl+z再回到进程中可使用fg命令,这样可以用ctrl+c来关闭进程

看完上述内容,你们掌握如何在python中使用Gunicorn服务器的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网站名称:如何在python中使用Gunicorn服务器-创新互联
转载来于:http://bjjierui.cn/article/ddsphe.html

其他资讯