Cookies
Cookies in Zapros are implemented as a handler — wrapping another handler to automatically store and send cookies.
Setup
python
from zapros import (
AsyncClient,
CookieHandler,
AsyncStdNetworkHandler,
)
client = AsyncClient(
handler=CookieHandler(AsyncStdNetworkHandler())
)python
from zapros import (
Client,
CookieHandler,
StdNetworkHandler,
)
client = Client(handler=CookieHandler(StdNetworkHandler()))Basic usage
Cookies from Set-Cookie headers are automatically stored and sent with subsequent requests:
python
from zapros import (
AsyncClient,
CookieHandler,
AsyncStdNetworkHandler,
)
client = AsyncClient(
handler=CookieHandler(AsyncStdNetworkHandler())
)
async with client:
await client.request(
"GET",
"https://api.example.com/login",
)
# session cookie stored
response = await client.request(
"GET",
"https://api.example.com/profile",
)
# session cookie sent automaticallypython
from zapros import (
Client,
CookieHandler,
StdNetworkHandler,
)
client = Client(handler=CookieHandler(StdNetworkHandler()))
with client:
client.request(
"GET",
"https://api.example.com/login",
)
# session cookie stored
response = client.request(
"GET",
"https://api.example.com/profile",
)
# session cookie sent automaticallyCustom CookieJar
Share cookies across clients:
python
from http.cookiejar import CookieJar
from zapros import (
AsyncClient,
CookieHandler,
AsyncStdNetworkHandler,
)
shared_jar = CookieJar()
client1 = AsyncClient(
handler=CookieHandler(
AsyncStdNetworkHandler(),
jar=shared_jar,
)
)
client2 = AsyncClient(
handler=CookieHandler(
AsyncStdNetworkHandler(),
jar=shared_jar,
)
)Custom cookie handling
If you need custom cookie logic (e.g., encrypted cookies, JWT in cookies, cookie signing), write your own handler:
python
from zapros import (
AsyncBaseHandler,
BaseHandler,
Request,
Response,
)
class MyCookieHandler(AsyncBaseHandler, BaseHandler):
def __init__(self, handler):
self._handler = handler
async def ahandle(self, request: Request) -> Response:
request.headers.add(
"Cookie",
"mycookie=signedvalue",
)
return await self._handler.ahandle(request)
def handle(self, request: Request) -> Response:
request.headers.add(
"Cookie",
"mycookie=signedvalue",
)
return self._handler.handle(request)See Handlers for the full protocol.