所以我现在正在使用python-firebase
,我之前也使用过JavaScript和Firebase。在JS中有ref.on('child_added')
,但我希望用python-firebase
做同样的事情(每次添加节点时我都必须检查firebase,所以我假设我需要这样的东西)。
那么我到底该怎么做呢?
发布于 2016-04-11 16:03:11
使用Firebase's REST API (这是他们的python API的底层),使用POST请求保存元素,该请求返回添加的元素的is,因此可以将其保存在某个地方。检索您的元素并遍历它们以获取相关id:
# assume your instance is called phones and your username is jack, change as appropriate
def get_object(newest_id):
objects = requests.get('https://samplechat.firebaseio-demo.com/users/jack/phones.json').json()
added_object = [obj for obj in objects if obj == newest_id][0]
return added_object
def add_object(dictionary_representing_object):
newest_id = requests.post('https://samplechat.firebaseio-demo.com/users/jack/phones.json', json=json.dumps(dictionary_representing_object), verify=False).json()['name']
stored_object = get_object(newest_id) # stored_object will be a superset of what's in dictionary_representing_object -- it will have an additional entry representing firebase's unique id
希望这能有所帮助。
发布于 2016-04-11 21:21:46
@hd1的答案有效,并使用您已经使用的python-firebase库。但正如您所说,它确实必须轮询更新。
另一种方法是监听Firebase's REST streaming API。有一个Python example of how to consume the REST events (使用Python request和sseclient库)。读取循环是here
self.sse = ClosableSSEClient(URL)
for msg in self.sse:
msg_data = json.loads(msg.data)
if msg_data is None: # keep-alives
continue
path = msg_data['path']
data = msg_data['data']
if path == '/':
# initial update
if data:
keys = data.keys()
keys.sort()
for k in keys:
self.message_queue.put(data[k])
else:
# must be a push ID
self.message_queue.put(data)
虽然它不像您以前使用的原生JavaScript客户端那么简单,但它与Python中的功能非常接近。
https://stackoverflow.com/questions/36542632
复制相似问题