0

I would like to use Python's requests library to establish a REST connection and make a POST request separately (using the first connection).

Originally I started with this:

import requests

session = requests.Session()
# I start timing here
response = session.post("full url", headers={"header" : "header value"})
# Response includes a timestamp

but I soon realised post() must be creating the connection because Session() doesn't accept the URL.

Once a connection is already established I know the network latency to the recipient is about 95ms. This above request takes ~200ms to reach the recipient.

To create the connection before calling post() I found this answer:

https://stackoverflow.com/a/51026159/1107474

My second attempt:

import requests
import time
import urllib.request
from requests import Session
from urllib.parse import urljoin

class LiveServerSession(Session):
    def __init__(self, base_url=None):
        super().__init__()
        self.base_url = base_url

    def request(self, method, url, *args, **kwargs):
        joined_url = urljoin(self.base_url, url)
        return super().request(method, joined_url, *args, **kwargs)

if __name__ == "__main__":
    
    baseUrl = "https://api.domain.com"
    with LiveServerSession(baseUrl) as session:
        # Connection should already be created?
        # I start timing here
        response = session.post(baseUrl + "my sub url", headers={"header" : "header value"})

However, it still takes ~196ms.

Am I using this wrong? I would just like to have the connection established before calling post().

intrigued_66
  • 16,082
  • 51
  • 118
  • 189
  • `Session` doesn't establish a connection, but it is saving you resources in the background. `requests.[method]` will build a session and destroy it every time, whereas reusing the session doesn't – C.Nivs Jun 07 '23 at 20:02
  • @C.Nivs Thanks, that makes sense. However, how can I create the connection before I call `[method]`? – intrigued_66 Jun 07 '23 at 21:01
  • You can't. But the session will reuse the connection you establish with your first call. See [here](https://stackoverflow.com/a/34491383/7867968) – C.Nivs Jun 08 '23 at 03:58

0 Answers0