Skip to content
Snippets Groups Projects
Commit 0c68ceb8 authored by Moul's avatar Moul
Browse files

Merge branch 'dev' into 42_data_init

parents c340f6a6 893faa8f
No related branches found
No related tags found
1 merge request!85#42: Retrieve informations once and use them in the whole program
......@@ -3,10 +3,12 @@ from ipaddress import ip_address
from json import loads
import socket
import urllib.request
import logging
from sys import exit, stderr
from commandlines import Command
from silkaj.constants import G1_DEFAULT_ENDPOINT, G1_TEST_DEFAULT_ENDPOINT
CONNECTION_TIMEOUT = 10
def discover_peers(discover):
"""
......@@ -125,7 +127,7 @@ def get_request(path, ep=EndPoint().ep):
if ep["port"] == "443":
url = "https://" + ep[address] + "/" + path
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
response = urllib.request.urlopen(request, timeout=CONNECTION_TIMEOUT)
encoding = response.info().get_content_charset('utf8')
return loads(response.read().decode(encoding))
......@@ -138,7 +140,7 @@ def post_request(path, postdata):
url = "http://" + ep[address] + ":" + ep["port"] + "/" + path
if ep["port"] == "443":
url = "https://" + ep[address] + "/" + path
request = urllib.request.Request(url, bytes(postdata, 'utf-8'))
request = urllib.request.Request(url, bytes(postdata, 'utf-8'), timeout=CONNECTION_TIMEOUT)
try:
response = urllib.request.urlopen(request)
except urllib.error.URLError as e:
......@@ -150,15 +152,16 @@ def post_request(path, postdata):
def best_node(ep, main):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addresses, port = {"ip6", "ip4", "domain"}, int(ep["port"])
s.settimeout(CONNECTION_TIMEOUT)
addresses, port = ("domain", "ip6", "ip4"), int(ep["port"])
for address in addresses:
if address in ep:
try:
s.connect((ep[address], port))
s.close()
return address
except:
pass
except Exception as e:
logging.debug("Connection to endpoint %s (%s) failled (%s)" % (ep, address, e))
if main:
print("Wrong node given as argument", file=stderr)
exit(1)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment