Debian Codegraph @

zaqarclient/queues/v2/subscription.py

raw
1 # Copyright (c) 2015 Catalyst IT Ltd.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 from zaqarclient.queues.v2 import core
17
18
19 class Subscription:
20
21 def __init__(self, client, queue_name, subscriber=None, ttl=60, id=None,
22 auto_create=True, **kwargs):
23 self.client = client
24
25 self.id = id
26 self.queue_name = queue_name
27 self.subscriber = subscriber
28 self.ttl = ttl
29 self.options = kwargs.get('options', {})
30 self.age = kwargs.get('age')
31 self.confirmed = kwargs.get('confirmed')
32
33 if auto_create:
34 self.ensure_exists()
35
36 def ensure_exists(self):
37 """Ensures subscription exists
38
39 This method is not race safe, the subscription could've been deleted
40 right after it was called.
41 """
42 req, trans = self.client._request_and_transport()
43
44 if not self.id and self.subscriber:
45 subscription_data = {'subscriber': self.subscriber,
46 'ttl': self.ttl,
47 'options': self.options
48 }
49 subscription = core.subscription_create(trans, req,
50 self.queue_name,
51 subscription_data)
52
53 if subscription and 'subscription_id' in subscription:
54 self.id = subscription['subscription_id']
55
56 if self.id:
57 sub = core.subscription_get(trans, req, self.queue_name, self.id)
58 self.subscriber = sub.get('subscriber')
59 self.ttl = sub.get('ttl')
60 self.options = sub.get('options')
61 self.age = sub.get('age')
62 self.confirmed = sub.get('confirmed')
63
64 def update(self, subscription_data):
65 req, trans = self.client._request_and_transport()
66 core.subscription_update(trans, req, self.queue_name,
67 self.id, subscription_data)
68
69 for key, value in subscription_data.items():
70 setattr(self, key, value)
71
72 def delete(self):
73 req, trans = self.client._request_and_transport()
74 core.subscription_delete(trans, req, self.queue_name, self.id)
75
76
77 def create_object(parent):
78 return lambda kwargs: Subscription(parent, kwargs.pop('source'),
79 subscriber=kwargs.pop('subscriber'),
80 ttl=kwargs.pop('ttl'),
81 id=kwargs.pop('id'),
82 age=kwargs.pop('age'),
83 confirmed=kwargs.pop('confirmed'),
84 auto_create=False,
85 **kwargs)