当前位置: 代码网 > it编程>前端脚本>Python > Python多种接口请求方式示例详解

Python多种接口请求方式示例详解

2024年08月09日 Python 我要评论
发送json数据如果你需要发送json数据,可以使用json参数。这会自动设置content-type为application/json。highlighter- goimport requestsi
  • 发送json数据

如果你需要发送json数据,可以使用json参数。这会自动设置content-type为application/json。

highlighter- go

import requests
import json
url = 'http://example.com/api/endpoint'
data = {
    "key": "value",
    "another_key": "another_value"
}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print(response.status_code)
print(response.json())
  • 发送表单数据 (form data)

如果你需要发送表单数据,可以使用data参数。这会自动设置content-type为application/x-www-form-urlencoded。

highlighter- go

import requests
url = 'http://example.com/api/endpoint'
data = {
    "key": "value",
    "another_key": "another_value"
}
response = requests.post(url, data=data)
print(response.status_code)
print(response.text)
  • 发送文件 (multipart form data)

当你需要上传文件时,通常会使用files参数。这会设置content-type为multipart/form-data。

highlighter- python

import requests
url = 'http://example.com/api/upload'
file = {'file': ('image.png', open('image.png', 'rb'))}
data = {
    'biz': 'temp',
    'needcompress': 'true'
}
response = requests.post(url, data=data, files=file)
print(response.status_code)
print(response.text)
  • 发送带有认证信息的请求

如果api需要认证信息,可以在请求中添加auth参数。

highlighter- go

import requests
url = 'http://example.com/api/endpoint'
username = 'your_username'
password = 'your_password'
response = requests.get(url, auth=(username, password))
print(response.status_code)
print(response.text)
  • 处理重定向

你可以选择是否允许重定向,默认情况下requests会自动处理重定向。

highlighter- python

import requests
url = 'http://example.com/api/endpoint'
allow_redirects = false
response = requests.get(url, allow_redirects=allow_redirects)
print(response.status_code)
print(response.history)
  • 设置超时

你可以设置请求的超时时间,防止长时间等待响应。

highlighter- python

import requests
url = 'http://example.com/api/endpoint'
timeout = 5
try:
    response = requests.get(url, timeout=timeout)
    print(response.status_code)
except requests.exceptions.timeout:
    print("the request timed out")
  • 使用cookies

如果你需要发送或接收cookies,可以通过cookies参数来实现。

highlighter- go

import requests
url = 'http://example.com/api/endpoint'
cookies = {'session': '1234567890'}
response = requests.get(url, cookies=cookies)
print(response.status_code)
print(response.cookies)
  • 自定义headers

除了默认的头部信息外,你还可以添加自定义的头部信息。

highlighter- go

import requests
url = 'http://example.com/api/endpoint'
headers = {
    'user-agent': 'myapp/0.0.1',
    'x-custom-header': 'my custom header value'
}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.headers)
  • 使用ssl验证

对于https请求,你可以指定验证证书的方式。

highlighter- python

import requests
url = 'https://example.com/api/endpoint'
verify = true  # 默认情况下,requests会验证ssl证书
response = requests.get(url, verify=verify)
print(response.status_code)
如果你要跳过ssl验证,可以将verify设置为false。但请注意,这样做可能会导致安全问题。
import requests
url = 'https://example.com/api/endpoint'
verify = false
response = requests.get(url, verify=verify)
print(response.status_code)
  • 上传多个文件

有时你可能需要同时上传多个文件。你可以通过传递多个files字典来实现这一点。

highlighter- python

import requests
url = 'http://example.com/api/upload'
files = [
    ('file1', ('image1.png', open('image1.png', 'rb'))),
    ('file2', ('image2.png', open('image2.png', 'rb')))
]
data = {
    'biz': 'temp',
    'needcompress': 'true'
}
response = requests.post(url, data=data, files=files)
print(response.status_code)
print(response.text)
  • 使用代理

如果你需要通过代理服务器访问互联网,可以使用proxies参数。

highlighter- go

import requests
url = 'http://example.com/api/endpoint'
proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080',
}
response = requests.get(url, proxies=proxies)
print(response.status_code)
  • 流式下载大文件

当下载大文件时,可以使用流式读取以避免内存不足的问题。

highlighter- python

import requests
url = 'http://example.com/largefile.zip'
response = requests.get(url, stream=true)
with open('largefile.zip', 'wb') as f:
    for chunk in response.iter_content(chunk_size=8192):
        if chunk:
            f.write(chunk)
  • 分块上传大文件

与流式下载类似,你也可以分块上传大文件以避免内存问题。

highlighter- python

import requests
url = 'http://example.com/api/upload'
file_path = 'path/to/largefile.zip'
chunk_size = 8192
with open(file_path, 'rb') as f:
    for chunk in iter(lambda: f.read(chunk_size), b''):
        files = {'file': ('largefile.zip', chunk)}
        response = requests.post(url, files=files)
        if response.status_code != 200:
            print("error uploading file:", response.status_code)
            break
  • 使用session对象

如果你需要多次请求同一个网站,并且希望保持状态(例如使用cookies),可以使用session对象。

highlighter- python

import requests
s = requests.session()
# 设置session的cookies
s.cookies['example_cookie'] = 'example_value'
# 发送get请求
response = s.get('http://example.com')
# 发送post请求
data = {'key': 'value'}
response = s.post('http://example.com/post', data=data)
print(response.status_code)
  • 处理错误

处理网络请求时,经常会遇到各种错误。可以使用异常处理来优雅地处理这些情况。

highlighter- python

import requests
url = 'http://example.com/api/endpoint'
try:
    response = requests.get(url)
    response.raise_for_status()  # 如果响应状态码不是200,则抛出httperror异常
except requests.exceptions.httperror as errh:
    print(f"http error: {errh}")
except requests.exceptions.connectionerror as errc:
    print(f"error connecting: {errc}")
except requests.exceptions.timeout as errt:
    print(f"timeout error: {errt}")
except requests.exceptions.requestexception as err:
    print(f"oops: something else: {err}")
  • 使用认证令牌

许多api使用认证令牌进行身份验证。你可以将认证令牌作为头部的一部分发送。

highlighter- python

import requests
url = 'http://example.com/api/endpoint'
token = 'your_auth_token_here'
headers = {
    'authorization': f'token {token}'
}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.json())
  • 使用oauth2认证

对于使用oauth2的api,你需要获取一个访问令牌并将其包含在请求头中。

highlighter- python

import requests
# 获取oauth2访问令牌
token_url = 'http://example.com/oauth/token'
data = {
    'grant_type': 'client_credentials',
    'client_id': 'your_client_id',
    'client_secret': 'your_client_secret'
}
response = requests.post(token_url, data=data)
access_token = response.json()['access_token']
# 使用访问令牌进行请求
api_url = 'http://example.com/api/endpoint'
headers = {
    'authorization': f'bearer {access_token}'
}
response = requests.get(api_url, headers=headers)
print(response.status_code)
print(response.json())

来源:https://www.iwmyx.cn/pythondzjkqqfb.html

到此这篇关于python多种接口请求方式示例 的文章就介绍到这了,更多相关python接口请求方式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com