首页 > 编程语言 >python3之requests库使用

python3之requests库使用

时间:2024-07-25 11:30:16浏览次数:10  
标签:get url session 使用 print requests response python3

使用 https://www.cnblogs.com/caroline2016/p/17007956.html 建立的api测试下requests库怎么使用。

模拟登录时laravel api那边出现了  Session store not set on request. 错误。解决办法在app/Http/Kernel.php 中 api 中间件组中添加两行代码:

<?php
protected $middlewareGroups = [
        ...

        'api' => [
            ...
            
            \App\Http\Middleware\EncryptCookies::class,          // <------- 添加的代码
            \Illuminate\Session\Middleware\StartSession::class, // <------ 添加的代码
        ],
    ];

demo

import requests
import concurrent.futures
import requests.adapters
from requests.auth import HTTPBasicAuth

url = "http://127.0.0.1:8000"
url_get = "http://127.0.0.1:8000/api/data/getPoem?p=1"
url_post = "http://127.0.0.1:8000/login"

# 设置请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
}
headers_api = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
    "Authorization": "Bearer 69|3eSTphCsfIrv1gOg3fGqNmwouJEpRwxymUc6Bvt3",
}
params = {}
response = requests.get(url_get, headers=headers_api, params=params)
if response.status_code == 200:
    # 查看响应码
    print(response.status_code)  # 200
    # 查看完整url地址
    print(response.url)  # http://127.0.0.1:8000/api/data/getPoem?p=1
    # 查看响应头部字符编码
    print(response.encoding)  # utf-8
    # 查看响应头
    print(response.headers)
    # 查看cookies
    print(response.cookies)
    # 查看响应内容,返回Unicode格式的数据
    print(response.text)
    # 查看响应内容,返回字节流数据
    print(response.content)
    # 查看响应内容,返回JSON响应内容
    print(response.json())
    # 查看响应内容,返回原始响应内容
    print(response.raw)  # <urllib3.response.HTTPResponse object at 0x000001E38C6F00A0>

# 转换编码
response.encoding = "utf-8"

# cookies
cookiejar = response.cookies
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
print("cookiedict", cookiedict)  # {'laravel_session': 'VS6SDGagCeub2h9c4WYzODpLGBERCJNiz2r78ZE1'}

# 会话管理
data = {"key": "[email protected]", "password": "12345678"}
session = requests.session()
session.headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36",
}
response1 = session.get(url)
response2 = session.post(url_post, data=data)  # 模拟登录
r = session.get(url_get)
if r.status_code == 200:
    print(response2.text)  # {"token":"73|gxwyT2nV6RGLO7EuT6cncXaPryTTgouxyGTsIb7U","code":0,"userinfo":{"name":"bb","email":"[email protected]"}}


# 身份验证
response = requests.post(url_post, auth=HTTPBasicAuth("username", "password"), headers=headers)
if response.status_code == 200:
    print(response.text)

# 代理设置
proxy = {"http": "http://username:password@ip:port"}
proxy = {"http": "http://ip:port"}
response = requests.get(url_get, proxies=proxy)

# SSL验证
response = requests.get("https://www.baidu.com/", verify=True)
print("verify", response)

# 错误处理
try:
    response = requests.get(url_get, timeout=1, headers=headers_api)
    response.raise_for_status()
except requests.exceptions.ConnectionError:
    print("connect error")
except requests.exceptions.Timeout:
    print("time out")
except requests.exceptions.HTTPError as err:
    print("server error:", err)
else:
    print("get data")

# 连接池
session = requests.session()
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100)
session.mount("http://", adapter=adapter)
response = session.get(url_get)

# 持久连接
response = session.get(url_get, headers={"Connection": "keep-alive"})


# 并发
def fetch_data(url):
    response = requests.get(url)
    return response.text


urls = ["url1", "url2"]
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    results = executor.map(fetch_data, urls)
for result in results:
    print(result)

# 其它方法
response = requests.put(url, data=data)
response = requests.delete(url)
response = requests.head(url)
response = requests.options(url)

 

标签:get,url,session,使用,print,requests,response,python3
From: https://www.cnblogs.com/caroline2016/p/18322608

相关文章

  • 反单引号 使用问题
    在使用vue编程中,组件里面绑定的事件如果有传入事件名称字符串/字符串参数,比如在路由跳转时书写成@click="$router.push('/detail/${item.id}')"乍一看是没有任何问题的,但实际上却会报错或者无法获得传入正确的id值为什么会出现这种情况?用反引号标识。它可以当作普通字符串使......
  • github的简单使用方法
    想要把代码托管到github上面,之前没有用过,简单记录一下:注册github账号注册github账号,这个使用邮箱就能注册,比较方便。安装git1.下载git安装包 进入官网Git(git-scm.com)下载对应版本就行2.安装通常全部点击下一步就行了3.创建密钥对右键点击OpenGitguihere-->help-->......
  • 字符串的相关案例和string库函数的使用
    字符串的存储特性:在存储过程中字符串都会在末尾自动添加一个结尾标志符\0                 来表示字符串结束字符串的定义方式有两种:方式一:利用字符数组+双引号的方式定义字符串例如:charstr[4]=“abc”;注意:这里的数组长度要么......
  • 如何使用DataFrameMapper删除特定列中具有空值的行?
    我正在使用sklearn-pandas.DataFrameMapper来预处理我的数据。我不想输入特定列。如果此列是Null,我只想删除该行。有没有办法做到这一点?虽然DataFrameMapper没有内置方法来删除具有空值的行,但你可以通过在DataFrameMapper管道之前使用P......
  • CI3使用加载类
    加载器类加载器,顾名思义,是用于加载元素的,加载的元素可以是库(类),视图文件 , 驱动器 ,辅助函数 , 模型 或其他你自己的文件。 应用程序包目录结构 /application/third_party/foo_bar//文件夹可选config/helpers/language/libraries/models/views/  读取视图......
  • Django get_or_create和update_or_create 的作用和使用
    Djangoget_or_create和update_or_create的作用和使用:get_or_create和update_or_create是Django中的两个有用的方法,用于在数据库中获取或创建记录。如果记录不存在,则创建它们;如果存在,则返回现有记录。这两个方法帮助简化了避免重复记录的逻辑,并提供了一种简洁的方法来更新......
  • 使用mybatis-plus拦截器MybatisPlusInterceptor进行分页查询案例
    在MyBatis-Plus中,分页功能通常是通过配置MybatisPlusInterceptor(或其前身PaginationInterceptor)来实现的,这是一个全局的拦截器,用于拦截MyBatis的SQL执行,并在其中添加分页逻辑。以下是一个使用MybatisPlusInterceptor进行分页查询的案例:添加依赖<dependencies><de......
  • 无法将两个字节从 pi 5 主设备发送到从设备 arduino mega(使用 smbus2 库)
    因此,我尝试使用smbus2库中的write_byte函数,并成功使用RaspberryPi5中的该函数来打开和关闭连接到ArduinoMega的LED。我的项目涉及3RPS平行轴机械手由3个步进器控制,我正在通过Pi5使用计算机视觉进行数据采集,计算我希望每个机械手电机达到的必要速度......
  • 使用 @Audited 增强Spring Boot 应用程序的数据审计能力
    介绍在SpringBoot开发的动态世界中,确保数据完整性和跟踪变化是至关重要的。实现这一目标的一个强大工具是@Audited注解。本文深入探讨了该注解的复杂性、其目的、实现步骤以及如何利用其功能进行有效的实体审计。理解@AuditedSpringBoot中的@Audited注解用于审计实体,提供对数......
  • ProcessPoolExecutor 的递归使用挂起
    问题我尝试将aProcessPoolExecutor与递归调用一起使用,但它不起作用。我在下面创建了一个最小的示例fromconcurrent.futuresimportProcessPoolExecutorfromtimeimportsleepexecutor=ProcessPoolExecutor()i=3deftest():globaliprint(......