装饰发布服务器函数和订阅服务器路由,必要时创建主题/订阅

Flask-PubSubDecorator的Python项目详细描述


烧瓶装饰工

根据需要装饰发布服务器函数和订阅服务器路由以创建主题/订阅。

安装

将此行添加到应用程序的requirements.txt中

Flask-PubSubDecorator

然后执行:

$ pip install -r requirements.txt

或自行安装为:

$ pip install Flask-PubSubDecorator

用法

使用pubsubdecorator非常简单。首先将google_application_credentials环境变量设置为指向有效的json creds文件。

$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/creds.json

下面的代码片段将帮助您编写代码

fromflaskimportFlask,requestfromPubSubDecoratorimportPubSubDecoratorimportbase64importjsonapp=Flask(__name__)# blueprint can optionally be passed in for registering subscribers in a blueprint endpointapp.pubsub=PubSubDecorator(app)# publisher decorator will inject publisher client and topic path@app.pubsub.publisher(topic='user_confirmed')defuser_confirmed(publisher,topic,user):publisher.publish(topic,data=json.dumps({'user_id':user.id}))# subscriber decorator will register the Flask route, prefixing /_ah/push-handlers# subscriber decorator will parse and inject pubsub message@app.pubsub.subscriber(subscription='process_user_confirmation',topic='user_confirmed',route='/process_user_confirmation',methods=['POST'])defprocess_user_confirmation(message,*args,**kwargs):try:user_id=message.get('user_id')# do some async work here!exceptException:_logger.exception('An unexpected error occurred processing subscription "{0}": {1}'.format(kwargs.get('__subscription__'),request.data))# Unexpected failure, do not ack messagereturn'',422return'',200

安全性

pubsub推送订阅本质上是面向公众的,因此应该受到保护。谷歌推荐的解决方案 将密钥附加到已注册的订阅pushendpoint。pubsubdecorator为您处理这个 提供以下内容:

  1. OS环境变量PUBSUB_DECORATOR_API_KEY
  2. 烧瓶应用程序配置PUBSUB_DECORATOR_API_KEY
  3. api_密钥被传递到pubsubdecorator构造函数中。

最佳实践:使用gcloud kms加密密钥,将其存储在gcloud数据存储中,并导出到os环境变量 在运行时。

日志记录

decorators将登录到“flask pubsub decorator”命名空间。

importsysimportloggingimportlogging.handlerslogger=logging.getLogger('flask-pubsub-decorator')logger.setLevel(logging.DEBUG)log_file=logging.handlers.RotatingFileHandler('log_file_name.log',maxBytes=5*1024*1024,backupCount=10)logger.addHandler(log_file)

测试

$ pytest -s tests.py

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Android使用两个后台服务错误   解压缩HTTPInputStream时,java GZIPInputStream过早关闭   javax和javax的区别是什么。网ssl。密钥库和服务器。ssl。为SpringBoot应用程序指定密钥库时的密钥库属性   java生成两个JPanel,而我只需要一个   java深度链接从play store安装应用程序时获取数据   java 安卓应用程序在退出时未正确释放蓝牙   java正确使用setCellValueFactory   java开放JdbcTemplate连接处于只读模式?   使用Spring MVC创建服务时发生java错误   JavaFX获取安装在计算机中的特定应用程序的版本   SecureRandom的安全问题:PRNG在java 1.5中不一致   windows我可以创建一个独立的。带Inno设置的Java应用程序的exe安装程序?   如何使用JavaServlet下载csv文件?   java从生成的缓冲图像中添加图像作为jasper中的数据记录?   java日期和时间解析