Putting a `Cookie` in a `CookieJar`

前端 未结 10 1453
谎友^
谎友^ 2020-11-30 01:45

I\'m using the new Python Requests library to make http requests. I obtain a cookie from the server as text. How do I turn that into a CookieJar with the cookie

10条回答
  •  -上瘾入骨i
    2020-11-30 02:23

    I think many of these answers are missing the point. Sometimes that other library isn't using requests under the hood. Or doesn't expose the cookiejar it's using. Sometimes all we have is the cookie string. In my case I'm trying to borrow the auth cookie from pyVmomi.

    import requests
    import http.cookies
    raw_cookie_line = 'foo="a secret value"; Path=/; HttpOnly; Secure; '
    simple_cookie = http.cookies.SimpleCookie(raw_cookie_line)
    cookie_jar = requests.cookies.RequestsCookieJar()
    cookie_jar.update(simple_cookie)
    

    Which gives us the following cookie_jar:

    In [5]: cookie_jar
    Out[5]: 
    

    Which we can use as normal:

    requests.get(..., cookies=cookie_jar)
    

提交回复
热议问题