Last active
February 23, 2017 05:20
-
-
Save DmitryBe/07305b2fa0f5809f5016e8e29df50f11 to your computer and use it in GitHub Desktop.
implement simple counter service using python && tornado sync
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
COUNTER_URL=http://172.17.6.114:8888/count | |
# get uniq increment val by key | |
curl ${COUNTER_URL}/my_key | |
# reset counter by key | |
curl -X DELETE ${COUNTER_URL}/my_key | |
# post key value | |
curl -X POST -d '{"key": "my_key", "val": "some_value"}' ${COUNTER_URL}/count |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#create hosts file with group && nodes; example: | |
[dev] | |
10.2.64.56 | |
10.2.75.206 | |
10.2.88.178 | |
10.2.85.248 | |
10.2.67.55 | |
# test ansible | |
ansible dev -i hosts -s -m raw -a "hostname -i" | |
# get uniq id on every node | |
ansible dev -i hosts -s -m raw -a "curl http://172.17.6.114:8888/count/my_key" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date | |
import tornado.escape | |
import tornado.ioloop | |
import tornado.web | |
import json | |
class Cache: | |
data = {} | |
@staticmethod | |
def get(key): | |
v = Cache.data.setdefault(key, 0) + 1 | |
Cache.data[key] = v | |
return v | |
@staticmethod | |
def delete(key): | |
Cache.data[key] = 0 | |
class CounterHandler(tornado.web.RequestHandler): | |
def get(self, key): | |
self.write(str(Cache.get(key))) | |
def post(self, *args, **kwargs): | |
v_str = self.request.body | |
# expected: {key: *, val: *} | |
v_json = json.loads(v_str) | |
v_json.setdefault('key', '-') | |
v_json.setdefault('val', '-') | |
print '{} -> {}'.format(v_json.get('key'), v_json.get('val')) | |
#self.write(v_json) | |
self.write('ok') | |
def delete(self, key): | |
Cache.delete(key) | |
self.write('ok') | |
application = tornado.web.Application([ | |
(r'/count/([\w]+)', CounterHandler), | |
(r'/count', CounterHandler) | |
]) | |
if __name__ == "__main__": | |
port = 8888 | |
application.listen(port) | |
print 'listening on {}'.format(port) | |
tornado.ioloop.IOLoop.instance().start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment