1
0
mirror of https://github.com/mbirth/tcl_ota_check.git synced 2024-11-09 22:06:47 +00:00
tcl_ota_check/tcllib/requests/runner.py

60 lines
2.1 KiB
Python
Raw Permalink Normal View History

2018-02-11 01:38:38 +00:00
#!/usr/bin/env python3
2018-02-08 00:15:58 +00:00
# -*- coding: utf-8 -*-
2018-02-11 01:38:38 +00:00
"""Generic request executors."""
from . import http, serverselector
2018-02-10 01:38:06 +00:00
from .tclrequest import TclRequest
2018-02-11 01:38:38 +00:00
2018-02-08 00:15:58 +00:00
class UnknownMethodException(Exception):
2018-02-11 01:38:38 +00:00
"""Ignore unknown methods."""
2018-02-08 00:15:58 +00:00
pass
2018-02-11 01:38:38 +00:00
2018-02-08 00:15:58 +00:00
class RequestRunner:
2018-02-11 01:38:38 +00:00
"""Generic request executor."""
2018-02-08 00:15:58 +00:00
def __init__(self, server_selector: serverselector.ServerSelector, https=True):
2018-02-11 01:38:38 +00:00
"""Populate variables."""
2018-02-08 00:15:58 +00:00
self.server_selector = server_selector
self.protocol = "https://" if https else "http://"
self.max_tries = 5
def get_http(self, method="GET") -> http.HttpRequest:
2018-02-11 01:38:38 +00:00
"""Return the http class according to desired method."""
2018-02-08 00:15:58 +00:00
if method == "GET":
return http.HttpRequest
elif method == "POST":
return http.HttpPostRequest
raise UnknownMethodException("Unknown http method: {}".format(method))
def get_server(self) -> str:
2018-02-11 01:38:38 +00:00
"""Return a master server."""
2018-02-08 00:15:58 +00:00
return self.server_selector.get_master_server()
2018-02-10 01:38:06 +00:00
def run(self, query: TclRequest, timeout: int=10) -> bool:
2018-02-11 01:38:38 +00:00
"""Run the actual query."""
2018-02-08 00:15:58 +00:00
for _ in range(0, self.max_tries):
url = "{}{}{}".format(self.protocol, self.get_server(), query.uri)
http_handler = self.get_http(query.method)(url, timeout)
http_handler.headers = query.get_headers()
http_handler.params = query.get_params()
http_handler.reset_session()
self.server_selector.hook_prerequest()
try:
req = http_handler.run()
if query.rawmode:
done = query.is_done(req.status_code, req.content)
else:
req.encoding = "utf-8"
done = query.is_done(req.status_code, req.text)
2018-02-08 00:15:58 +00:00
self.server_selector.hook_postrequest(done)
if done:
return done
except http.TimeoutException:
self.server_selector.hook_postrequest(False)
query.error = "Timeout."
query.error = "Max tries ({}) reached.".format(self.max_tries)
return False