'Python requests: One Session per Server/Domain?
I am sending On and Off signals with http.GET to 5 smart sockets. Unfortunately they sometimes do not respond in time which leads to my script to error.
Now i want to use the Session Module to handle Timeouts. I hope that this will also lead to less open connections with better response times and less timeouts over all.
My questions: Do I need to setup one Session Object per Domain/Switch/Service ? Or will I create one Session Object which will then handle all requests to all sockets?
Some code for some background - which is currently based on one Session for all requests. But I could store the Session object also inside the switch dict and reuse it for each call Which version is correct?
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import json
import time
def get_switch_state(switch):
result=session.get(switch["URL"]+"cm?cmnd=Status").content
result=json.loads(result)
switch["state"]=result["Status"]["Power"]
switch["status"]=result
return switch
switches=[]
switch = {
"name":"H1000W",
"URL": "http://192.168.2.15/",
"command_on": "cm?cmnd=Power%20on",
"command_off":"cm?cmnd=Power%20Off",
"command_status" : "cm?cmnd=Status%201",
"assigned_load":1200,
"state":0} # 2120, 1180, 940
switches=switches+[switch]
switch = {
"name":"H500W",
"URL": "http://192.168.2.27/",
"command_on": "cm?cmnd=Power%20on",
"command_off":"cm?cmnd=Power%20Off",
"command_status" : "cm?cmnd=Status%201",
"assigned_load":465,
"state":0}
switches=switches+[switch]
scan_interval=10
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
while True:
[... determine "switch - desired_state" ...]
for switch in switches:
get_switch_state(switch)
if switch["state"]!=switch["desired_state"]:
if switch["desired_state"]:
result=session.get(switch["URL"]+switch["command_on"])
print("Switching On", result.content)
else:
result=session.get(switch["URL"]+switch["command_off"])
print("Switching Off",result.content)
print(requests)
time.sleep(scan_interval)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
