Advertisement
dredder_gun

async-requests-for-period-python

Jun 11th, 2017
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from flask import Flask
  4. from flask import request
  5. import config
  6. import requests
  7. import trollius as asyncio
  8.  
  9. app = Flask(__name__)
  10.  
  11.  
  12. def post_to_clojure():
  13.     try:
  14.         r = requests.post(config.uri)
  15.         print r.raw
  16.     except (RuntimeError, TypeError, NameError):
  17.         print "Error while query request"
  18.  
  19.  
  20. @asyncio.coroutine
  21. def periodic():
  22.     while True:
  23.         post_to_clojure()
  24.         yield asyncio.From(asyncio.sleep(3))
  25.  
  26.  
  27. def stop():
  28.     task.cancel()
  29.  
  30.  
  31. @app.route('/start-timer', methods=['GET'])
  32. def start_timer():
  33.     task = asyncio.Task(periodic())
  34.     loop = asyncio.get_event_loop()
  35.     try:
  36.         loop.run_until_complete(task)
  37.     except asyncio.CancelledError:
  38.         pass
  39.  
  40.  
  41. @app.route('/stop-timer', methods=['GET'])
  42. def stop_timer():
  43.     stop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement