requests手动添加cookies

简介:在接口测试中,大多数项目的接口是需要登录后进行操作的,经常用到requests库进行模拟登录及登录后的操作。

相关文章:

1、sanic:读、写、删除cookies
2、http库三剑客:requests

案例解析:
1、本案例中,假设登录接口为:http://127.0.0.1:3031/cookie

2、登录完成后得到cookies

<RequestsCookieJar[<Cookie key=024f4347-cac8-4a01-9082-3e47378c697c for 127.0.0.1/>, <Cookie test="generate cookies" for 127.0.0.1/>]>

3、登录完成后通过手动新增cookies,并在再次请求时,将my_cookie 传给cookies

my_cookie = dict()
for k, v in res.cookies.items():
    my_cookie[k] = v
res2 = requests.get(url="http://127.0.0.1:3031/check_cookie", cookies=my_cookie)

4、服务端在检查cookies的正确性。

test_cookie = request.cookies.get('test')
key_cookie = request.cookies.get('key')

if test_cookie == 'generate cookies' and key_cookie == key:
    return response.redirect("/home")
else:
    return response.redirect("/login")

获取cookies:

import requests

response = requests.get("https://www.zhihu.com")
print(response.cookies)
for key, value in response.cookies.items():
    print(key + '=' + value)

# 执行结果
# <RequestsCookieJar[<Cookie _xsrf=4syf8BxI1p5x3pmf8PVbSvQOui001Lng for .zhihu.com/>]>
# _xsrf=4syf8BxI1p5x3pmf8PVbSvQOui001Lng

服务端源码:

import uuid
from sanic import Sanic
from sanic import response
from sanic.response import json, text

app = Sanic(__name__)

key = str(uuid.uuid4())


@app.get("/check_cookie")
async def check(request):
    test_cookie = request.cookies.get('test')
    key_cookie = request.cookies.get('key')

    if test_cookie == 'generate cookies' and key_cookie == key:
        return response.redirect("/home")
    else:
        return response.redirect("/login")


@app.route("/cookie")
async def test(request):
    response = text("There's a cookie up in this response")
    response.cookies['test'] = 'generate cookies'
    response.cookies['key'] = str(key)
    print("cookies:", response.cookies)
    return response


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=3031, auto_reload=True)

客户端源码:

import requests


def login1():
    url = 'http://127.0.0.1:3031/cookie'
    res = requests.get(url)
    print(res.status_code)
    print(res.cookies)
    res2 = requests.get(url="http://127.0.0.1:3031/check_cookie")
    print(res2.url)


def login2():
    url = 'http://127.0.0.1:3031/cookie'
    res = requests.get(url)
    print(res.status_code)
    print(res.cookies)

    my_cookie = dict()
    for k, v in res.cookies.items():
        my_cookie[k] = v
    print("my_cookie:", my_cookie)
    res2 = requests.get(url="http://127.0.0.1:3031/check_cookie", cookies=my_cookie)
    print(res2.url)


if __name__ == '__main__':
    login1()
    print("*" * 100)
    login2()

运行服务端:
requests手动添加cookies
运行客户端:
requests手动添加cookies
服务端生成cookies和检验cookies的正确性:
requests手动添加cookies

最终:
1、未登录成功的重定向到:http://127.0.0.1:3031/login
2、登录成功的重定向到:http://127.0.0.1:3031/home

微信公众号:玩转测试开发
欢迎关注,共同进步,谢谢!

上一篇:自然语言处理NLP:网络爬虫实战代码


下一篇:接口自动化测试--requests的基本使用