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().

3
  • 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 7 at 20:02
  • @C.Nivs Thanks, that makes sense. However, how can I create the connection before I call [method]? Jun 7 at 21:01
  • You can't. But the session will reuse the connection you establish with your first call. See here
    – C.Nivs
    Jun 8 at 3:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.