【问题标题】:Subscribing PubNub in python在 python 中订阅 PubNub
【发布时间】:2014-10-31 23:03:52
【问题描述】:
我正在用 python 制作一个小型投票系统,我的计划是让客户要求用户在那里投票并使用 pubnub 将其发送出去。然后我想制作一个应用程序来接收选票并将它们全部计数,但我找不到接收消息的方法。我这样做是对的还是有更好的方法感谢您的时间。
【问题讨论】:
-
您有几个选择。建议通过您的服务器使用PubNub Storage and Playback 来汇总投票总数。您将获取频道上的历史记录并计算投票总数。 pubnub.history({ channel : "...", callback : function, start : "TIMETOKEN" })。使用 PubNub History 方法是最简单的选择。
标签:
python-2.7
publish-subscribe
pubnub
【解决方案1】:
使用 Python 进行 PubNub 投票统计
您有几个选择。建议通过您的服务器使用 PubNub 存储和播放来汇总投票总数。您将获取频道上的历史记录并计算投票总数。
PubNub PIP 包
pip install pubnub
在 Python 中统计投票
from Pubnub import Pubnub
## Init PubNub
pubnub = Pubnub( publish_key="demo", subscribe_key="demo", ssl_on=False )
## Total Votes
last_tt = 0
total_votes = 0
vote_chan = "my_vote_channel"
results_chan = "my_vote_channel.results"
## Tally Callback Function (Sum up the Votes...)
def tally(response):
print(response)
total_votes += len(response[0])
last_tt = response[1]
## Loop Continuously on the last known TIMETOKEN
pubnub.history({ channel : vote_chan, callback : tally, start : last_tt })
## Periodically Publish to the Results Channel
pubnub.publish({ channel : results_chan, message : { "total" : total_votes } })
使用 PubNub History 方法是最简单的选择。