· 6 years ago · Oct 20, 2019, 03:09 AM
1from flask import Flask, request
2from flask_restful import Resource, Api
3
4from azure.appconfiguration import AzureAppConfigurationClient
5
6app = Flask(__name__)
7api = Api(app)
8
9class Config(Resource):
10 def __init__(self):
11 self.client = AzureAppConfigurationClient.from_connection_string(connection_str)
12 self.cache = {}
13
14 def _refresh_cache():
15 # Let's have a thread running this in parallel every 10 seconds or so
16 # Shoudl lock but, meee, let's assume the cache is a locked one like.
17 for key, value in self.cache.items():
18 if (result := self.client.get_configuration_setting(key, etag=value.etag)) is not None:
19 self.cache[key] = result
20
21 def get(self, key_id):
22 cache = self.cache.get(key_id, None)
23 etag = cache.etag if cache else None # Means I have no etag, probably should be '*' under the hood? As a client, impl detail.
24 try:
25 # Assuming I get None
26 return (self.client.get_configuration_setting(mykey, etag=etag) or cache).value
27 except ResourceNotFoundError:
28 return f"Resource {key_id} doesn't exist", 404
29
30 def put(self, key_id):
31 value = request.form['value']
32 # I want to cache it first if it exists already, so I have the etag
33 try:
34 cache = self.cache.setdefault(key_id, self.client.get_configuration_setting(mykey))
35 etag = cache.etag
36 raise_condition = MatchConditions.IfModified
37 except ResourceNotFoundError:
38 etag = None # Means I have no etag, probably should be '*' under the hood? As a client, impl detail.
39 raise_condition = MatchConditions.IfExists
40 settings_to_send = ConfigurationSetting(
41 key=key_id,
42 value=value,
43 content_type="text/plain"
44 )
45 try:
46 self.set_configuration_setting(settings_to_send, etag=etag, raise_condition=raise_condition)
47 except ResourceExists:
48 return f"You can't create resource {key_id} anymore, someone did it before you", 400
49 except ResourceModifed:
50 return f"Since the last time you saw resource {key_id} it has changed, can't write", 400
51 except ResourceReadOnlyError:
52 return f"Resource {key_id} not writable, can't write", 400
53 return f"Resource {key_id} updated"
54
55api.add_resource(TodoSimple, '/<string:todo_id>')
56
57if __name__ == '__main__':
58 app.run(debug=True)