Beispiel #1
0
def test_cookies_update():
    cookies = httpx.Cookies()
    more_cookies = httpx.Cookies()
    more_cookies.set("name", "value", domain="example.com")

    cookies.update(more_cookies)
    assert dict(cookies) == {"name": "value"}
    assert cookies.get("name", domain="example.com") == "value"
Beispiel #2
0
async def getUp(uid, SESSDATA, CSRF):
    result = False
    count = 0
    while not result and count < 3:
        count += 1
        cookies = httpx.Cookies()
        cookies.set("SESSDATA", SESSDATA, domain=".bilibili.com")
        cookies.set("bili_jct", CSRF, domain=".bilibili.com")
        result = await request(durl.format(uid), header, cookies)
    if not result:
        return ({'success': False, 'name': 'name', "did": 0})

    code = json.loads(result.content).get('code')
    msg = json.loads(result.content).get('message')
    if code != 0:
        print(
            time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime()) + '[HTTP]' +
            'Code:{}  Msg:{}'.format(code, msg))
        return ({'success': False, 'name': 'name', "did": 0})
    data = json.loads(result.content).get('data')
    cards = data.get('cards')
    if not cards or len(cards) == 0:
        return ({'success': False, 'name': 'name', "did": 0})

    name = cards[0].get('desc').get('user_profile').get('info').get('uname')
    did = cards[0].get('desc').get('dynamic_id')

    return ({'success': True, 'name': name, "did": did})
Beispiel #3
0
async def getLive(uid, SESSDATA, CSRF):
    result = False
    count = 0
    while not result and count < 3:
        cookies = httpx.Cookies()
        cookies.set("SESSDATA", SESSDATA, domain=".bilibili.com")
        cookies.set("bili_jct", CSRF, domain=".bilibili.com")
        count += 1
        result = await request(lurl.format(uid), header, cookies)
    if not result:
        return False
    code = json.loads(result.content).get('code')
    msg = json.loads(result.content).get('message')
    if code != 0:
        print(
            time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime()) + '[直播]' +
            'Code:{}  Msg:{}'.format(code, msg))
        return False

    data = json.loads(result.content).get('data')
    if not data:
        return False
    if data.get('status') != 1:
        return False
    else:
        return data.get('url')
Beispiel #4
0
    def test_loads_dumps(self, logged_session, check_login):
        cookie = logged_session.cookies
        dumps = logged_session.dumps()

        sess = Session(_mocker_app=app)
        sess.loads({"username": "******", "password": "******"})
        assert check_login(sess)

        with pytest.warns(LoadWarning):
            sess.loads({})
        assert sess.cookies == httpx.Cookies({})
        assert not sess._username
        assert not sess._password

        sess = Session(_mocker_app=app)
        with pytest.raises(TypeError):
            sess.loads({"cookies": "Cookie☆"})
        with pytest.warns(LoadWarning):
            sess.loads({"cookies": {}})
            sess.loads({"cookies": cookie})
        assert check_login(sess)
        with pytest.warns(DumpWarning):
            sess.dumps()

        sess = Session(_mocker_app=app)
        sess.loads(dumps)
        assert check_login(sess)

        # test auto renew mechanism
        logged_session.logout()
        sess = Session(_mocker_app=app)
        sess.loads(dumps)
        assert check_login(sess)
Beispiel #5
0
def test_cookies_with_domain_and_path():
    cookies = httpx.Cookies()
    cookies.set("name", "value", domain="example.com", path="/subpath/1")
    cookies.set("name", "value", domain="example.com", path="/subpath/2")
    cookies.clear(domain="example.com", path="/subpath/1")
    assert len(cookies) == 1
    cookies.delete("name", domain="example.com", path="/subpath/2")
    assert len(cookies) == 0
Beispiel #6
0
 def get_cookies(self):
     cache_data = get_cache("session")
     cookies = httpx.Cookies()
     if cache_data:
         self.code = cache_data["yzm_code"]
         for index in cache_data["cookie"]:
             cookies.set(index, cache_data["cookie"][index])
     return cookies
Beispiel #7
0
def test_cookies_can_be_a_list_of_tuples():
    cookies_val = [("name1", "val1"), ("name2", "val2")]

    cookies = httpx.Cookies(cookies_val)

    assert len(cookies.items()) == 2
    for k, v in cookies_val:
        assert cookies[k] == v
Beispiel #8
0
 def __setstate__(self, d):
     try:
         del d["_cookies"]
     except LookupError:
         pass
     self.__dict__.update(d)
     # Need to create a new CookieJar when unpickling,
     # because it was killed on Pickle
     self._cookies = httpx.Cookies()
Beispiel #9
0
 def __init__(self, cookie: Optional[Dict[str, str]] = None) -> None:
     self._cookie = httpx.Cookies()
     self.__initCookie(cookie)
     self._ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36 Edg/85.0.564.51"
     self._api = "https://www.bigfun.cn/api/feweb"
     self._oauthKey: Optional[str] = None
     self._csrf = ""
     self._battleList = []
     self._bossList = []
Beispiel #10
0
    def cookies_for_url(self, url):
        if ('youtube.com' in url) or ('youtu.be' in url) or ('google.com'
                                                             in url):
            cookies = httpx.Cookies()
            cookies.set('CONSENT', 'YES', domain='.youtube.com')
            return cookies
#            return {'CONSENT': 'YES', 'Domain': '.youtube.com',
#                'Path': '/', 'SameSite' : 'None', 'Expires': 'Sun, 10 Jan 2038 07:59:59 GMT', 'Max-Age': '946080000'}
        return {}
Beispiel #11
0
def test_cookies_repr():
    cookies = httpx.Cookies()
    cookies.set(name="foo", value="bar", domain="http://blah.com")
    cookies.set(name="fizz", value="buzz", domain="http://hello.com")

    assert (
        repr(cookies) ==
        "<Cookies[<Cookie foo=bar for http://blah.com />, <Cookie fizz=buzz for http://hello.com />]>"
    )
Beispiel #12
0
def test_cookies_with_domain():
    cookies = httpx.Cookies()
    cookies.set("name", "value", domain="example.com")
    cookies.set("name", "value", domain="example.org")

    with pytest.raises(httpx.CookieConflict):
        cookies["name"]

    cookies.clear(domain="example.com")
    assert len(cookies) == 1
Beispiel #13
0
def test_cookies():
    cookies = httpx.Cookies({"name": "value"})
    assert cookies["name"] == "value"
    assert "name" in cookies
    assert len(cookies) == 1
    assert dict(cookies) == {"name": "value"}
    assert bool(cookies) is True

    del cookies["name"]
    assert "name" not in cookies
    assert len(cookies) == 0
    assert dict(cookies) == {}
    assert bool(cookies) is False
Beispiel #14
0
def test_set_cookie_with_cookies_model() -> None:
    """
    Send a request including a cookie, using a `Cookies` instance.
    """

    url = "http://example.org/echo_cookies"
    cookies = httpx.Cookies()
    cookies["example-name"] = "example-value"

    client = httpx.Client(transport=MockTransport())
    response = client.get(url, cookies=cookies)

    assert response.status_code == 200
    assert response.json() == {"cookies": "example-name=example-value"}
Beispiel #15
0
def _sanitize_response(response: Response):
    """
    When mutual authentication is required and an HTTP error is to be
    returned, this method is used to sanitize the response which cannot
    be trusted.
    """
    response.is_stream_consumed = True
    response._content = b""
    response._cookies = httpx.Cookies()
    headers = response.headers
    response.headers = httpx.Headers({'content-length': '0'})
    for header in ('date', 'server'):
        if header in headers:
            response.headers[header] = headers[header]
Beispiel #16
0
def test_multiple_set_cookie():
    jar = http.cookiejar.CookieJar()
    headers = [
        (
            b"Set-Cookie",
            b"1P_JAR=2020-08-09-18; expires=Tue, 08-Sep-2099 18:33:35 GMT; "
            b"path=/; domain=.example.org; Secure",
        ),
        (
            b"Set-Cookie",
            b"NID=204=KWdXOuypc86YvRfBSiWoW1dEXfSl_5qI7sxZY4umlk4J35yNTeNEkw15"
            b"MRaujK6uYCwkrtjihTTXZPp285z_xDOUzrdHt4dj0Z5C0VOpbvdLwRdHatHAzQs7"
            b"7TsaiWY78a3qU9r7KP_RbSLvLl2hlhnWFR2Hp5nWKPsAcOhQgSg; expires=Mon, "
            b"08-Feb-2099 18:33:35 GMT; path=/; domain=.example.org; HttpOnly",
        ),
    ]
    request = httpx.Request("GET", "https://www.example.org")
    response = httpx.Response(200, request=request, headers=headers)

    cookies = httpx.Cookies(jar)
    cookies.extract_cookies(response)

    assert len(cookies) == 2
Beispiel #17
0
async def getCards(uid, SESSDATA, CSRF):
    avReg = r'^bilibili\:\/\/video\/(?P<av>[0-9]+)\/\?.*?'
    result = False
    count = 0
    while not result and count < 3:
        count += 1
        cookies = httpx.Cookies()
        cookies.set("SESSDATA", SESSDATA, domain=".bilibili.com")
        cookies.set("bili_jct", CSRF, domain=".bilibili.com")
        hh = header
        hh.update({
            "origin": "https://space.bilibili.com",
            "referer": "https://space.bilibili.com/"
        })
        result = await request(durl.format(uid), hh, cookies)
    if not result:
        print(
            time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime()) + '[动态]' +
            '获取失败')
        return False
    code = json.loads(result.content).get('code')
    msg = json.loads(result.content).get('message')
    if code != 0:
        print(
            time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime()) + '[动态]' +
            'Code:{}  Msg:{}'.format(code, msg))
        return False
    data = json.loads(result.content).get('data')
    if not data:
        return False
    cards = data.get('cards')
    if not cards:
        return False
    cc = []
    for card in cards:
        did = card['desc'].get('dynamic_id')
        ltime = card['desc'].get('timestamp')
        cd = json.loads(card.get('card'))
        item = cd.get('item') or cd
        description = item.get('description')
        content = item.get('content')
        if cd.get('origin'):
            origin = json.loads(cd.get('origin'))
            oitem = origin.get('item')
            ouser = cd.get('origin_user').get('info').get('uname')
            if oitem:
                odesc = oitem.get('description')
                ocont = oitem.get('content')
                course = origin.get('url')
                id_ = origin.get('id')
                vest = origin.get('vest')
                video = origin.get('jump_url')
                room = origin.get('roomid')
                if odesc:
                    opic = oitem.get('pictures')
                    cc.append({
                        "id": did,
                        "type": "update_forward_picture_dynamic",
                        "content": content,
                        "o_content": odesc,
                        "pic": opic,
                        "time": ltime,
                        "ouser": ouser
                    })
                elif ocont:
                    cc.append({
                        "id": did,
                        "type": "update_forward_dynamic",
                        "content": content,
                        "o_content": ocont,
                        "time": ltime,
                        "ouser": ouser
                    })
                elif course:
                    title = origin.get('title')
                    cc.append({
                        "id": did,
                        "type": "update_forward_course",
                        "title": title,
                        "url": course,
                        "time": ltime,
                        "ouser": ouser
                    })
                elif vest:
                    o_content = vest.get('content')
                    cc.append({
                        "id": did,
                        "type": "update_forward_vest",
                        "content": content,
                        "o_content": o_content,
                        "time": ltime,
                        "ouser": ouser
                    })
                elif id_:
                    title = origin.get('title')
                    cc.append({
                        "id":
                        did,
                        "type":
                        "update_forward_column",
                        "title":
                        title,
                        "url":
                        "https://www.bilibili.com/read/cv{}".format(id_),
                        "time":
                        ltime,
                        "ouser":
                        ouser
                    })
                elif video:
                    ee = enc(int(re.match(avReg, video).group('av')))
                    if not ee:
                        continue
                    video = "https://www.bilibili.com/video/{}".format(ee)
                    title = origin.get('title')
                    cc.append({
                        "id": did,
                        "type": "update_forward_video",
                        "content": content,
                        "title": title,
                        "url": video,
                        "time": ltime,
                        "ouser": ouser
                    })
                elif room:
                    cc.append({
                        "id":
                        did,
                        "type":
                        "update_forward_live",
                        "content":
                        content,
                        "url":
                        'https://live.bilibili.com/{}'.format(room),
                        "time":
                        ltime,
                        "ouser":
                        ouser
                    })
        else:
            id_ = cd.get('id')
            vest = cd.get('vest')
            video = cd.get('jump_url')
            if vest:
                content = vest.get('content')
                cc.append({
                    "id": did,
                    "type": "update_vest",
                    "content": content,
                    "time": ltime
                })
            elif id_:
                title = cd.get('title')
                cc.append({
                    "id":
                    did,
                    "type":
                    "update_column",
                    "title":
                    title,
                    "url":
                    "https://www.bilibili.com/read/cv{}".format(id_),
                    "time":
                    ltime
                })
            elif video:
                content = cd.get('dynamic')
                ee = enc(int(re.match(avReg, video).group('av')))
                if not ee:
                    continue
                video = "https://www.bilibili.com/video/{}".format(ee)
                title = cd.get('title')
                cc.append({
                    "id": did,
                    "type": "update_video",
                    "content": content,
                    "title": title,
                    "url": video,
                    "time": ltime
                })
            elif content:
                cc.append({
                    "id": did,
                    "type": "update_dynamic",
                    "content": content,
                    "time": ltime
                })
            elif description:
                pic = item.get('pictures')
                cc.append({
                    "id": did,
                    "type": "update_picture_dynamic",
                    "content": description,
                    "pic": pic,
                    "time": ltime
                })
    return cc
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   2_6_response_cookies.py
@Time    :   2021-02-23
@Author  :   EvilRecluse
@Contact :   https://github.com/RecluseXU
@Desc    :   Cookies
'''

# here put the import lib
import httpx

# 从响应中获取
r = httpx.get('http://httpbin.org/cookies/set?chocolate=chip',
              allow_redirects=False)
print(r.cookies['chocolate'])

# 请求时设置(简易)
cookies = {"peanut": "butter"}
r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
print(r.json())

# 请求时设置(标准)
cookies = httpx.Cookies()
cookies.set('cookie_on_domain', 'hello, there!', domain='httpbin.org')
cookies.set('cookie_off_domain', 'nope.', domain='example.org')
r = httpx.get('http://httpbin.org/cookies', cookies=cookies)
print(r.json())