flask-uwsgi-websocket

我要开发同款
匿名用户2021年12月10日
67阅读
开发技术Python
所属分类Web应用开发、Web框架
授权协议MIT License

作品详情

Flask-uWSGI-WebSocket

High-performanceWebSocketsforyourFlaskappspoweredbyuWSGI.Low-leveluWSGIWebSocketAPIaccessandflexiblehigh-levelabstractionsforbuildingcomplexWebSocketapplicationswithFlask.SupportsseveraldifferentconcurrencymodelsincludingGevent.InspiredbyFlask-Sockets.

fromflaskimportFlaskfromflask_uwsgi_websocketimportGeventWebSocketapp=Flask(__name__)websocket=GeventWebSocket(app)@websocket.route('/echo')defecho(ws):whileTrue:msg=ws.receive()ws.send(msg)if__name__=='__main__':app.run(gevent=100)Installation

Preferredmethodofinstallationisviapip:

$pipinstallFlask-uWSGI-WebSocketInstallinguWSGI

Ofcourseyou'llalsoneeduWSGI(withSSLsupport,atminimum).Itcanalsobeinstalledwithpip:

$pipinstalluwsgi

Ifthatfailsoryouneedtoenabletheasyncioplugin,readon.

uWSGIonMacOSX

OnsomeversionsofMacOSX,OpenSSLheadersarenolongerincluded.IfyouuseHomebrew,installOpenSSLandensuretheyareavailable:

$brewinstallopenssl&&brewlinkopenssl--force

ThisshouldensurepipcaninstalluWSGI:

$LDFLAGS="-L/usr/local/lib"pipinstalluwsgi--no-use-wheel

Ifyouplantousetheasyncioplugin,you'llneedtoensurethatit'senabledwhenuWSGIiscompiled.YoucanuseUWSGI_PROFILEtodothis.WithHomebrewPython3.5installed:

$LDFLAGS="-L/usr/local/lib"CFLAGS="-I/usr/local/include/python3.5m"UWSGI_PROFLILE="asyncio"pip3installuwsgi--no-use-wheeluWSGIonLinux

IfyourLinuxdistributionincludesuWSGIwithspecificplugins,thatismanytimesyourbestbet.Ifthatfailsoryou'dprefertocompileuWSGIyourself,you'llneedtoensurethattherequisitebuildtools,OpenSSLheaders,etcareinstalled:

$apt-getinstallbuild-essentiallibssl-devpython3-devpython3-venv

AccordingtotheuWSGIasynciodocs,UWSGI_PROFILEandgreenlet.hlocationshouldbespecified.

IfyouareinstallinguWSGIintoavirtualenv,theprocessis:

$python3-mvenvpyvenv$.pyvenv/bin/activate(pyvenv)$pipinstallgreenlet

Now,greenlet.hshouldbeavailableat$VIRTUAL_ENV/include/site/python3.5.Tobuildwithpip:

$mkdir-p$VIRTUAL_ENV/include/site/python3.5/greenlet$ln-s../greenlet.h$VIRTUAL_ENV/include/site/python3.5/greenlet/$CFLAGS="-I$VIRTUAL_ENV/include/site/python3.5"UWSGI_PROFILE="asyncio"pipinstalluwsgi--no-use-wheelDeployment

YoucanuseuWSGI'sbuilt-inHTTProutertogetupandrunningquickly:

$uwsgi--master--http:8080--http-websockets--wsgiecho:app

...whichiswhatapp.rundoesafterwrappingyourFlaskapp:

app.run(debug=True,host='localhost',port=8080,master=true,processes=8)

uWSGIsupportsseveralconcurrencymodels,inparticularithasnicesupportforGevent.IfyouwanttouseGevent,importflask_uwsgi_websocket.GeventWebSocketandconfigureuWSGItousethegeventloopengine:

$uwsgi--master--http:8080--http-websockets--gevent100--wsgiecho:app

...or:

app.run(debug=True,gevent=100)

Notethatyoucannotusemultiplethreadswithgeventloopengine.

Toenableasyncioinstead:

$uwsgi--master--http:5000--http-websockets--asyncio100--greenlet--wsgichat:app

...or:

app.run(debug=True,asyncio=100,greenlet=True)

Forproductionyou'llprobablywanttorunuWSGIbehindHaproxyorNginx,insteadofusingthebuilt-intHTTProuter.ExploretheuWSGIdocumentationtolearnmoreaboutthevariousconcurrencyanddeploymentoptions.

Development

It'spossibletotakeadvantageofFlask'sinteractivedebuggerbyinstallingWerkzeug'sDebuggedApplicationmiddleware:

fromwerkzeug.debugimportDebuggedApplicationapp.wsgi_app=DebuggedApplication(app.wsgi_app,True)

...andrunninguWSGIwithonlyasingleworker:

$uwsgi--master--http:8080--http-websockets--wsgi-file--workers1--threads8app.py

Ifyouuseapp.run(debug=True)orexportFLASK_UWSGI_DEBUG,Flask-uWSGI-Websocketwilldothisautomaticallyforyou.

Examples

Thereareseveralexamplesavailablehere.

APIWebSocket

AppliesWebSocketMiddlewaretoyourFlaskApp,allowingyoutodecoraterouteswiththeroutemethod,turningthemintoWebSockethandlers.

Additionallymonkey-patchesapp.run,torunyourappdirectlyinuWSGI.

route(url)

run(debug,host,port,**kwargs)**kwargsarepassedtouWSGIascommandlinearguments.

WebSocketMiddleware

WebSocketMiddlewarewhichautomaticallyperformsWebSockethandshakeandpassesWebSocketClientinstancestoyourroute.

WebSocketClient

ExposestheuWSGIWebSocketAPI.

recv()(aliasWebSocket.receive())

recv_nb()

send(msg)

send_binary(msg)

recv_nb()

send_from_sharedarea(id,pos)

send_binary_from_sharedarea(id,pos)

GeventWebSocket

FancierWebSocketabstractionthattakesadvantageofGeventloopengine.RequiresuWSGItoberunwith--uwsgioption.

GeventWebSocketMiddleware

AutomaticallyperformsWebSockethandshakeandpassesaGeventWebSocketClientinstancetoyourroute.

GeventWebSocketClient

WebSocketclientabstractionwithfullynon-blockingmethods.

receive()

send(msg)

close()

connected

AsyncioWebSocket

FancierWebSocketabstractionthattakesadvantageofAsyncioloopengine.RequiresuWSGItoberunwith--asyncioand--greenletoption.

AsyncioWebSocketMiddleware

AutomaticallyperformsWebSockethandshakeandpassesaAsyncioWebSocketClientinstancetoyourroute.

AsyncioWebSocketClient

WebSocketclientabstractionwithasynciocoroutines.

coroutinea_recv()(aliasreceive(),recv())

coroutinea_send(msg)(aliassend())

recv_nb()(shouldbeuseless)

send_nb()(shouldbeuseless)

close()

connected

AdvancedUsage

Normallywebsocketrouteshappenoutsideofthenormalrequestcontext.Youcangetarequestcontextinyourwebsockethandlerbyusingapp.request_context:

app=Flask(__name__)ws=GeventWebSocket(app)@ws.route('/websocket')defwebsocket(ws):withapp.request_context(ws.environ):printrequest.args
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论