From b09695c0fd161b7346475e8738d9a1b39fe07bf2 Mon Sep 17 00:00:00 2001 From: KevinMidboe Date: Fri, 22 Dec 2017 11:41:03 +0100 Subject: [PATCH] Http utils now supports logging on our main logger torrentSearch. Changed indentation and added better error handling for requests.urlopen which is the function that fetches from the internet. --- torrentSearch/http_utils.py | 53 ++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 24 deletions(-) diff --git a/torrentSearch/http_utils.py b/torrentSearch/http_utils.py index 644c4b4..96bca64 100644 --- a/torrentSearch/http_utils.py +++ b/torrentSearch/http_utils.py @@ -1,38 +1,43 @@ #!/usr/bin/env python3.6 +import logging +import sys + from urllib import parse, request from urllib.error import URLError -import logging + +logger = logging.getLogger('torrentSearch') def build_url(ssl, baseUrl, path, args_dict=[]): - url_parts = list(parse.urlparse(baseUrl)) - url_parts[0] = 'https' if ssl else 'http' - if type(path) is list: - url_parts[2] = '/'.join(path) - else: - url_parts[2] = path - url_parts[4] = parse.urlencode(args_dict) - return parse.urlunparse(url_parts) + url_parts = list(parse.urlparse(baseUrl)) + url_parts[0] = 'https' if ssl else 'http' + if type(path) is list: + url_parts[2] = '/'.join(path) + else: + url_parts[2] = path + url_parts[4] = parse.urlencode(args_dict) + return parse.urlunparse(url_parts) # Converts a input string or list to percent-encoded string, # this is for encoding information in a Uniform Resource # Identifier (URI) using urllib def convert_query_to_percent_encoded_octets(input_query): - if type(input_query) is list: - input_query = ' '.join(input_query) + if type(input_query) is list: + input_query = ' '.join(input_query) - return parse.quote(input_query) + return parse.quote(input_query) def fetch_url(url): - req = request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) - try: - response = request.urlopen(req) - except URLError as e: - if hasattr(e, 'reason'): - logging.error('We failed to reach a server with request: %s' % req.full_url) - logging.error('Reason: %s' % e.reason) - elif hasattr(e, 'code'): - logging.error('The server couldn\'t fulfill the request.') - logging.error('Error code: ', e.code) - else: - return response + logger.debug('Fetching query: {}'.format(url)) + req = request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) + try: + response = request.urlopen(req, timeout=10) + return response + except URLError as e: + if hasattr(e, 'reason'): + logger.error('We failed to reach a server with request: %s' % req.full_url) + logger.error('Reason: %s' % e.reason) + elif hasattr(e, 'code'): + logger.error('The server couldn\'t fulfill the request.') + logger.error('Error code: ', e.code) + sys.exit()