from tornado.httpclient import AsyncHTTPClient, HTTPClient, HTTPRequest
+import settings
+
+_snapshot_cache = {}
+
def _make_request(host, port, username, password, uri, method='GET', data=None, query=None):
url = '%(scheme)s://%(host)s:%(port)s%(uri)s' % {
if query:
url += '?' + '='.join(query.items())
- request = HTTPRequest(url, method, body=data, auth_username=username, auth_password=password)
+ request = HTTPRequest(url, method, body=data, auth_username=username, auth_password=password,
+ request_timeout=settings.REMOTE_REQUEST_TIMEOUT)
return request
def current_snapshot(host, port, username, password, camera_id, callback):
+ global _snapshot_cache
+
logging.debug('getting current snapshot for remote camera %(id)s on %(host)s:%(port)s' % {
'id': camera_id,
'host': host,
request = _make_request(host, port, username, password, '/snapshot/%(id)s/current/' % {'id': camera_id})
+ cached = _snapshot_cache.setdefault(request.url, {'pending': 0, 'jpg': None})
+ if cached['pending'] > 0: # a pending request for this snapshot exists
+ return callback(cached['jpg'])
+
def on_response(response):
+ cached['pending'] -= 1
+ cached['jpg'] = response.body
+
if response.error:
logging.error('failed to get current snapshot for remote camera %(id)s on %(host)s:%(port)s: %(msg)s' % {
'id': camera_id,
callback(response.body)
+ cached['pending'] += 1
+
http_client = AsyncHTTPClient()
http_client.fetch(request, on_response)