推进器的烧瓶延伸
Flask-Pusher的Python项目详细描述
烧瓶推进器
推进器的烧瓶延伸部分。它是官方客户机的一个薄包装, 将烧瓶应用程序绑定到推送客户端。
安装
从pypi安装Flask-Pusher
模块。
pip install Flask-Pusher
配置
pusher的基本配置是app_id
、key
和secret
。这些值在pusher web界面中可用。
PUSHER_APP_ID='your-pusher-app-id'PUSHER_KEY='your-pusher-key'PUSHER_SECRET='your-pusher-secret'
您可以使用以下配置连接到自定义主机/端口:
PUSHER_HOST='api.pusherapp.com'PUSHER_PORT='80'
扩展自动配置pusher编码器以使用app.json_encoder
。
用法
此扩展简化了pusher配置并将客户端绑定到应用程序。
fromflaskimportFlaskfromflask_pusherimportPusherapp=Flask(__name__)pusher=Pusher(app)# Use pusher = Pusher(app, url_prefix="/yourpath") to mount the plugin in another path
扩展提供了两种访问pusher客户端的方法:
# you can just get the client from current_appclient=current_app.extensions["pusher"]# or you can get it from the extensionclient=pusher.client
在这两种情况下,它都是对推送客户机的引用。
client.trigger('channel_name', 'event', {
'message': msg,
})
在这里检查pusher python客户端的文档:http://pusher.com/docs/server_api_guide#/lang=python
推送器验证
pusher已经验证了私有和存在通道。Flask-Pusher
创建
处理它的/pusher/auth
路由。为了支持这些经过身份验证的路由,
只需用@pusher.auth
来修饰函数。
此函数必须返回True
表示已授权,返回False
表示未授权
用户。它发生在请求上下文中,因此您拥有所有的Flask
功能,
包括例如Flask-Login
当前用户。
设置PUSHER_AUTH
配置以更改身份验证终结点。默认值是/auth
。
fromflask_loginimportcurrent_user@pusher.authdefpusher_auth(channel_name,socket_id):if'foo'inchannel_name:# refuse foo channelsreturnFalse# authorize only authenticated usersreturncurrent_user.is_authenticated()
它还透明地支持基于pusher-js-auth
:https://github.com/dirkbonhomme/pusher-js-auth`的批处理身份验证。对批处理中的每个通道调用身份验证函数。
在此处阅读有关用户身份验证的详细信息:http://pusher.com/docs/authenticating_users
推进器通道数据
状态通道需要channel_data
。Flask-Pusher
默认情况下发送
user_id
使用socket_id
,因为它是一个必需字段。
@pusher.channel_data
提供了一种设置其他值的方法。如果user_id
键被返回,它覆盖默认的user_id
。
fromflask_loginimportcurrent_user@pusher.channel_datadefpusher_channel_data(channel_name,socket_id):return{"name":current_user.name}
推杆网钩
pusher有webhook来向服务器发送websocket事件。
烧瓶推进器创建处理这些webhook的路由,并验证头X-Pusher-Key
和X-Pusher-Signature
。
fromflaskimportrequest@pusher.webhooks.channel_existencedefchannel_existence_webhook():printrequest.json@pusher.webhooks.presencedefpresence_webhook():printrequest.json@pusher.webhooks.clientdefclient_webhook():printrequest.json
json请求记录在pusher文档中:http://pusher.com/docs/webhooks
这些webhook路由安装在/pusher/events/channel_existence
、/pusher/events/presence
和/pusher/events/client
中。配置您的Pusher应用程序以将Webhook发送到这些路由。
免责声明
本项目不隶属于推进器或烧瓶。