【轉(zhuǎn)】Flask實(shí)現(xiàn)異步非阻塞請(qǐng)求功能

本文來源:http://blog.csdn.net/yannanxiu/article/details/52915929? 感謝作者!

前言

最近做物聯(lián)網(wǎng)項(xiàng)目的時(shí)候需要搭建一個(gè)異步非阻塞的HTTP服務(wù)器,經(jīng)過查找資料,發(fā)現(xiàn)可以使用gevent包。

關(guān)于gevent

Gevent 是一個(gè)Python并發(fā)網(wǎng)絡(luò)庫,它使用了基于 libevent 事件循環(huán)的 greenlet 來提供一個(gè)高級(jí)同步 API。下面是代碼示例:

fromgevent.wsgiimportWSGIServer

fromyourapplicationimportapp

http_server = WSGIServer(('',5000), app)

http_server.serve_forever()

代碼清單

下面放上Flask異步非阻塞的代碼清單,以后需要用到的時(shí)候直接移植即可。

# coding=utf-8

# Python Version: 3.5.1

# Flask

from flask import Flask, request, g

# gevent

from gevent import monkey

from gevent.pywsgi import WSGIServer

monkey.patch_all()

# gevent endimporttime

app = Flask(__name__)

app.config.update(DEBUG=True)

@app.route('/asyn/', methods=['GET'])

deftest_asyn_one():

print("asyn has a request!")

time.sleep(10)

return'hello asyn'

@app.route('/test/', methods=['GET'])

deftest():return'hello test'

if__name__ =="__main__":

# app.run()

http_server = WSGIServer(('',5000), app)

http_server.serve_forever()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容