DEV Community

ipgleam
ipgleam

Posted on

A Python Session Is Not a Proxy Session: Build a Local Lab to See Why

A scraper keeps the same requests.Session() object, changes its proxy configuration, and continues working. Did the session change?

That question is ambiguous. The client may still hold the same cookies. The request may travel through a different proxy endpoint. A provider may maintain its own session identifier. The target application may use yet another mechanism to decide whether two requests belong together.

This tutorial separates two of those layers with a small experiment: a local target server and two local HTTP forwarders. You will switch the forwarder while retaining cookies, then retain the forwarder while replacing the client session.

Everything runs on your own machine. No proxy account, external target, or production credentials are required.

Define what you want to observe

The experiment answers two specific questions:

  • Does a cookie survive when the same Requests session sends a request through a different local proxy?
  • Does choosing the same proxy automatically give a new Requests session the previous session's cookie?

We will observe the route label and the Cookie header received by the target. Labels A and B identify our local forwarding processes. They do not represent different public exit IPs: all three servers bind to the loopback address.

Keeping this distinction explicit makes the result useful. We can demonstrate cookie and route separation without pretending to have measured residential-proxy rotation.

Understand the pieces before running them

A Requests Session maintains client-side state, including a cookie jar. Its official documentation also describes connection pooling and shared settings.

A proxy URL tells the client where to send traffic for a destination scheme. In the lab, the client sends an HTTP request through forwarder A or B. Each forwarder adds its own route label and relays the request to our target.

The target returns a cookie named lab_session. The value is intentionally constant because this is an observation tool, not an authentication system. The target reports the cookie it received in the incoming request, before the new response cookie can affect a later request.

That timing matters. The first response sets a cookie, but the first request did not already contain it. The second request can contain the cookie learned from the first response.

Set up a small Python environment

Use Python 3.10 or later. In a project folder, create an environment and install Requests:

python -m venv .venv
.\.venv\Scripts\python -m pip install requests
Enter fullscreen mode Exit fullscreen mode

Save the following code as session_proxy_lab.py, then run:

.\.venv\Scripts\python .\session_proxy_lab.py
Enter fullscreen mode Exit fullscreen mode

The command style above is for Windows PowerShell. On macOS or Linux, use .venv/bin/python for the environment's interpreter.

The server ports are selected automatically. A context manager shuts down each server when the experiment finishes, including when an assertion fails.

Build the target, forwarders, and client

from contextlib import contextmanager
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
from urllib.parse import urlsplit

import requests


class QuietHandler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass


class Origin(QuietHandler):
    def do_GET(self):
        if self.path != "/observe":
            self.send_error(404)
            return
        body = json.dumps({
            "route": self.headers.get("X-Lab-Route", "direct"),
            "cookie_received": self.headers.get("Cookie", ""),
        }).encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Set-Cookie", "lab_session=demo; Path=/; HttpOnly")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


@contextmanager
def serve(handler):
    server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
    worker = Thread(target=server.serve_forever, daemon=True)
    worker.start()
    try:
        yield server.server_port
    finally:
        server.shutdown()
        server.server_close()
        worker.join()


def proxy_handler(origin_port, label):
    class LocalProxy(QuietHandler):
        def do_GET(self):
            target = urlsplit(self.path)
            # Only forward this exact local lab URL; never arbitrary destinations.
            if (target.scheme != "http" or
                    target.netloc != f"127.0.0.1:{origin_port}" or
                    target.path != "/observe" or target.query or target.fragment):
                self.send_error(403)
                return
            headers = {"X-Lab-Route": label}
            cookie = self.headers.get("Cookie")
            if cookie:
                headers["Cookie"] = cookie
            connection = HTTPConnection("127.0.0.1", origin_port, timeout=3)
            try:
                connection.request("GET", "/observe", headers=headers)
                upstream = connection.getresponse()
                body = upstream.read()
                self.send_response(upstream.status)
                for key in ("Content-Type", "Set-Cookie"):
                    value = upstream.getheader(key)
                    if value is not None:
                        self.send_header(key, value)
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            finally:
                connection.close()
    return LocalProxy


def observe(session, target, proxy_port):
    proxy = f"http://127.0.0.1:{proxy_port}"
    with session.get(target, proxies={"http": proxy},
                     timeout=(3, 3), allow_redirects=False) as response:
        response.raise_for_status()
        return response.json()


def main():
    with serve(Origin) as origin_port:
        with serve(proxy_handler(origin_port, "A")) as a_port, \
                serve(proxy_handler(origin_port, "B")) as b_port:
            target = f"http://127.0.0.1:{origin_port}/observe"
            with requests.Session() as session:
                session.trust_env = False
                first = observe(session, target, a_port)
                second = observe(session, target, b_port)
            with requests.Session() as fresh:
                fresh.trust_env = False
                third = observe(fresh, target, b_port)
            assert first == {"route": "A", "cookie_received": ""}
            assert second == {"route": "B", "cookie_received": "lab_session=demo"}
            assert third == {"route": "B", "cookie_received": ""}
            for label, result in (("same session, proxy A", first),
                                  ("same session, proxy B", second),
                                  ("fresh session, proxy B", third)):
                print(f"{label}: {json.dumps(result)}")
            print("All three lab checks passed.")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Read the output one request at a time

The local run produces:

same session, proxy A: {"route": "A", "cookie_received": ""}
same session, proxy B: {"route": "B", "cookie_received": "lab_session=demo"}
fresh session, proxy B: {"route": "B", "cookie_received": ""}
All three lab checks passed.
Enter fullscreen mode Exit fullscreen mode
Request Client cookie jar Forwarder Cookie received by target
First Original session, initially empty A None
Second Original session, cookie retained B lab_session=demo
Third New session, initially empty B None

The second request is the important contrast. Changing the forwarder did not clear the original client's cookie jar. The third request shows the reverse: choosing forwarder B did not transfer the original session's cookie into a fresh client.

Each result is checked by an assertion. If you change the program and break one of these expectations, it fails rather than printing a misleading success message.

Why the cookie follows the target

In this lab, both routes reach the same target host and path. That is why the cookie learned through A is eligible to be sent through B by the original session.

The cookie is associated with the target's cookie scope, not a route label that our forwarder invents. RFC 6265 describes cookie storage and matching rules. Cookies are not generally isolated by TCP port, so choosing different local target ports is not a sound way to model separate cookie identities.

The experiment uses plain HTTP only. Its sample cookie is a marker, not a credential, and does not have the Secure attribute. Real websites can have additional cookie attributes and application rules. Do not infer that this lab reproduces browser cookie policies or every production authentication flow.

Why the forwarders are intentionally narrow

The local proxy accepts only the exact target URL created by the program. It forwards a GET to /observe, copies the Cookie header, and adds X-Lab-Route itself. Other destinations receive 403.

This makes the route label a controlled observation inside the experiment. It is not an IP detector or a trustworthy identity signal for a public application. A real client could forge a similarly named header outside this closed setup.

The forwarder uses Python's HTTPConnection to contact the target. It relays only the response information the experiment needs. It is not a complete HTTP proxy: it does not implement HTTPS CONNECT, authentication, arbitrary methods, or general-purpose header forwarding.

Both servers bind to 127.0.0.1. Keep the experiment local. Python's http.server documentation explicitly describes limitations that make this tool inappropriate as a production server.

Try a small change and predict the result

Before changing the code, predict what will happen if you insert this line between the first and second calls to observe:

session.cookies.clear()
Enter fullscreen mode Exit fullscreen mode

The second request will still travel through B, but its incoming Cookie header should now be empty. Update the corresponding assertion to expect an empty string and run the lab again.

This isolates a client-state change from a route change. Clearing the cookie jar does not select a different proxy, and selecting a different proxy does not perform that clear operation for you.

A second useful exercise is to send the third request through A. Its cookie should still be absent because the new client session starts empty. Change the expected route in the third assertion to A as well.

These exercises are small enough that a surprising result can be traced to a specific change. Avoid adding real targets until you can explain the baseline output.

Apply the distinction to collection workflows

Suppose a public price check opens a category page and then a product detail page. If the application depends on a location cookie established in the first step, keeping that cookie may matter even when both responses return 200.

Decide which requests share application state, which should use the same intended market, and whether your proxy provider offers a documented continuity mechanism. These are separate configuration decisions. Neither a Python Session nor a stable proxy hostname proves that an external exit address stayed unchanged.

Likewise, a fresh Python Session only resets the state owned by that new object. It does not reset a provider-side session, change a provider's routing choice, or erase the target application's server-side history.

For diagnostics, keep client context, configured route, and content acceptance separate. A route label can explain where a request was sent; a cookie snapshot can explain part of its application context; a content check can establish whether the returned observation is usable. Avoid logging real cookie values or credentials in production diagnostics.

What the experiment verifies

The included program was executed locally and passed its three assertions. It demonstrated that one Requests session retained a target cookie across two local forwarders, and that a fresh session did not inherit that cookie through the same forwarder.

The cookie-clear exercise and alternate-route exercise were also run with their corresponding assertions updated. Both produced the expected result.

Those results concern client cookies and local HTTP forwarding. The lab does not measure external exit IPs, provider sticky-session duration, HTTPS tunnels, browser fingerprints, or real-site acceptance. It gives you a reproducible starting point for reasoning about those additional layers.

Top comments (1)

Collapse
 
dosaygo profile image
DOSAYGO •

When you move from Python Requests to full browser sessions where IndexedDB, service workers, and TLS or canvas fingerprints persist alongside cookies, do you spin up a fresh disposable remote browser container per proxy session?