[英]python-firebase get items when added
So I am working with python-firebase
at the moment, and I have been working with JavaScript and Firebase before. 因此,目前我正在使用
python-firebase
,并且之前一直在使用JavaScript和Firebase。 In JS there was the ref.on('child_added')
, but I am looking to do the same with python-firebase
(I have to check firebase each time a node is added, so I assume I would need something like this). 在JS中有
ref.on('child_added')
,但是我希望对python-firebase
ref.on('child_added')
做同样的事情(每次添加节点时我都必须检查firebase,所以我认为我需要这样的东西)。
So how exactly can I do this? 那么我该怎么做呢?
Using Firebase's REST API (which is what their python API is under the hood), you save the elements using a POST request, which returns the ids of the added elements, so persist that somewhere. 使用Firebase的REST API (这是他们的python API所使用的),您可以使用POST请求保存元素,该请求返回添加的元素的ID,因此将其保留在某个地方。 Retrieve your elements and iterate through them for the relevant id:
检索您的元素并遍历它们以获取相关的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
Hope that helps. 希望能有所帮助。
@hd1's answer works and uses the python-firebase library you already use. @ hd1的答案有效,并使用您已经使用的python-firebase库。 But as you say, it will indeed have to poll for updates.
但是正如您所说,它确实必须轮询更新。
An alternative would be to listen for Firebase's REST streaming API . 一种替代方法是侦听Firebase的REST流API 。 There is a Python example of how to consume the REST events (using the Python request and sseclient libraries).
有一个有关如何使用REST事件的Python示例 (使用Python请求和sseclient库)。 The read loop is 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)
While it is not as simple as the native JavaScript client that you've used before, it's as close as you can get to that functionality in Python. 尽管它不像以前使用的本机JavaScript客户端那么简单,但它与Python中的该功能非常接近。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.