开始了!
发送表单数据并携带文件和字段发送https请求, 无论在后端开发和爬虫开发中都是比较常见的。这篇使用Python中两个常用的HTTP库 aiohttp
和 requests 来举例实现
。
用例:
aiohttp
aiohttp
是一个基于异步的HTTP客户端/服务器框架,在异步程序中比较常用。
安装
pip3 install aiohttp
官方地址
https://docs.aiohttp.org/en/stable/
示例
# -*- coding: utf-8 -*-
# @Author: 胖胖很瘦
# @Date: 2024-03-15 15:56:39
# @LastEditors: 胖胖很瘦
# @LastEditTime: 2024-03-15 15:58:14
import asyncio
import aiohttp
async def start(url, data, file_path):
"""
http请求
:param url: 请求地址
:param data: 表单数据
:param file_path: 文件路径
"""
async with aiohttp.ClientSession() as session:
dataFrom = aiohttp.FormData(data)
with open(file_path, 'rb') as file:
dataFrom.add_field('file', file, filename=file_path)
async with session.post(url, data=data) as response:
if response.status == 200:
print("请求成功")
else:
print("请求失败")
if __name__ == "__main__":
url = 'http://example.com/upload'
file_path = 'example.txt'
data = {'field1': 'value1', 'field2': 'value2'}
asyncio.run(start(url, data, file_path))
requests:
requests
是一个同步的HTTP库, 在爬虫应用中requests排第二就没有模块排第一。可以使用loop.run_in_executor改为异步运行
官方地址
https://requests.readthedocs.io/en/latest/
示例
# -*- coding: utf-8 -*-
# @Author: 胖胖很瘦
# @Date: 2024-03-15 15:56:39
# @LastEditors: 胖胖很瘦
# @LastEditTime: 2024-03-15 15:58:14
import requests
import asyncio
def start(url, data, file_path):
"""
http请求
:param url: 请求地址
:param data: 表单数据
:param file_path: 文件路径
"""
try:
files = {'file': open(file_path, 'rb')}
response = requests.post(url, files=files, data=data)
if response.status_code == 200:
print("请求成功")
else:
print("请求失败")
except Exception as e:
print(e)
if __name__ == "__main__":
url = 'http://example.com/upload'
file_path = 'example.txt'
data = {'field1': 'value1', 'field2': 'value2'}
# 异步请求
loop = asyncio.get_event_loop()
loop.run_in_executor(None, start, url, data, file_path)
# 同步请求
# start(url, data, file_path)
完事了~
在本文中,介绍了如何使用aiohttp
和requests
库发送表单数据,携带文件和字段的POST请求。aiohttp
适用于异步环境,提供更好的性能和扩展性,而requests
是同步的,不适用于异步操作,但是可以通过run_in_executor
方法在异步环境中使用。选择适合您项目需求的库,并根据需要发送表单数据,携带文件和字段的请求。