OSS restful API 调用 put,上传文件,python发http request示例

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: 发送put 请求,向bucket中写入文件,代码中*** 的部分改成实际内容。rest请求主要问题在拼header时authorization可能会有问题,注意生成signature时的入参。#tested env: python version v3.9.6#author: Fred#2022-1-11import hmacimport hashlibimport base64im

发送put 请求,向bucket中写入文件,代码中*** 的部分改成实际内容。

rest请求主要问题在拼header时authorization可能会有问题,注意生成signature时的入参。

#tested env: python version v3.9.6
#author: Fred
#2022-1-11

import hmac
import hashlib
import base64
import datetime
import requests
from scrapy.utils.python import to_bytes

#this function is to get the md5 vaule for a file content,
#input argu: file path of the file you want to upload as the content of http request
#return: string of md5 vaule
#refer to https://www.alibabacloud.com/help/doc-detail/31951.html#section-i74-k35-5w4
def get_md5(file_name): 
    file = open(file_name, 'rb')
    hash = hashlib.md5()
    hash.update(file.read())
    return base64.b64encode(hash.digest()).decode('utf-8')

#this function is to calculate the signature, which is part of authentication, the info should be same with your http header
# argu refer to the link as below,
#refer to https://www.alibabacloud.com/help/en/doc-detail/31951.html
def get_sig(verb, content_md5, content_type, date, add_info_str, res):
    sig_param = verb + '\n' + content_md5 + '\n' + content_type + '\n' + date + '\n' + add_info_str + '\n' + res
    h = hmac.new(to_bytes(ak_secret), to_bytes(sig_param) , hashlib.sha1)
    return base64.b64encode(h.digest()).decode('utf-8')

#Here is the information provide by Cloud account owner, to access the Cloud resources
#ak_id means AccessKey ID
ak_id = '****'
#aksecret means AccessKey Secret
ak_secret = '****'
#host_addr means the url of the bucket
host_addr = '****.***.aliyuncs.com'
bucketname = '*****'
#dst_file_path should be the destination of your file, e.g. /SAP New/xxx.csv or /SAP Archived/xxx.csv
dst_file_path = '/***/samplefile.txt'

#Here is the infomation to fill the http request header
verb = 'PUT'
file_name = 'samplefile.txt'
content_md5 = get_md5(file_name)
content_type = 'text/plain'
#get GMT date
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
#CanonicalizedResource, destination bucketname and folder
res = '/****/***/samplefile.txt'
#CanonicalizedOSSHeaders, it's optional, if have multiple argu, need \n to seperate each
#https://www.alibabacloud.com/help/doc-detail/31951.html#section-rvv-dx2-xdb
author_info_key = 'x-oss-meta-author'
author_info_value = '***'
add_info_str = author_info_key + ':' + author_info_value

#Here to get the authentication so that our request will be permitted, the authentication info is necessary for http header
auth = "OSS " + ak_id + ":" + get_sig(verb, content_md5, content_type, date, add_info_str, res)

#Here to define the header include the authentication and other infomation
req_header = {
    'Host':host_addr,
    'Content-Md5':content_md5,
    'Content-Type':content_type,
    'Date':date,
    'Authorization':auth,
    author_info_key:author_info_value
}

##file_url = https://****.***.aliyuncs.com/***/samplefile.txt, url should include the folder name.
file_url ='https://' + host_addr + dst_file_path 
#send the request, file_url is the target full location of the file, headers is the http headers, data the the file content
req = requests.put(file_url, headers = req_header, data = open(file_name, 'rb').read())    

#show response
print(req)

相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
21天前
|
安全 前端开发 API
ThinkPHP5 API模块开发规范与示例
【7月更文挑战第6天】本技术文档旨在指导开发者如何完全遵循ThinkPHP5框架的开发规范来构建RESTful API模块。ThinkPHP5(简称TP5)是一款基于PHP的轻量级MVC框架,其简洁、高效的特点非常适合快速开发Web应用及API接口。以下是创建API模块的基本步骤、最佳实践以及代码示例。
35 0
|
8天前
|
Java API Python
python并发执行request请求
选择哪种并发方式取决于我们的具体需求。对于I/O密集型任务,多线程或异步I/O通常是更好的选择;对于CPU密集型任务,多进程可能是更好的选择。此外,异步I/O通常比多线程具有更好的性能,特别是在高并发的网络应用中。
|
9天前
|
监控 API 网络安全
​邮件通知提醒邮箱警告设置教程及API代码示例
**摘要:** 在系统管理中,邮件通知提醒用于及时报告异常和重要事件。本文提供AOKSend的设置教程和API代码示例,教你如何配置邮件警告。通过自动化邮件通知,可以提升响应速度,确保系统稳定性。步骤包括注册AOKSend账户、获取API密钥、设置SMTP配置、创建触发条件及编写Python API代码示例。利用AOKSend API发送警告邮件,如CPU使用率过高通知,可有效监控和测试,确保系统异常时能快速响应。
|
12天前
|
消息中间件 API 数据库
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
在微服务架构中,每个服务通常都是一个独立运行、独立部署、独立扩展的组件,它们之间通过轻量级的通信机制(如HTTP/RESTful API、gRPC等)进行通信。
|
18天前
|
API Python
【Python】已解决:urllib.error.HTTPError: HTTP Error 403: Forbidden
【Python】已解决:urllib.error.HTTPError: HTTP Error 403: Forbidden
40 1
|
1月前
|
JSON Serverless 对象存储
函数计算产品使用问题之如何创建一个同时具有HTTP触发器和OSS触发器的函数
函数计算产品作为一种事件驱动的全托管计算服务,让用户能够专注于业务逻辑的编写,而无需关心底层服务器的管理与运维。你可以有效地利用函数计算产品来支撑各类应用场景,从简单的数据处理到复杂的业务逻辑,实现快速、高效、低成本的云上部署与运维。以下是一些关于使用函数计算产品的合集和要点,帮助你更好地理解和应用这一服务。
|
1月前
|
JSON 中间件 API
中间件API示例(以Express.js为例)
【6月更文挑战第14天】
25 8
|
13天前
|
API Python
首先,我们导入了`http.client`模块,它是Python标准库中的一个模块,用于创建和发送HTTP请求。
首先,我们导入了`http.client`模块,它是Python标准库中的一个模块,用于创建和发送HTTP请求。
|
13天前
|
网络协议 安全 Python
我们将使用Python的内置库`http.server`来创建一个简单的Web服务器。虽然这个示例相对简单,但我们可以围绕它展开许多讨论,包括HTTP协议、网络编程、异常处理、多线程等。
我们将使用Python的内置库`http.server`来创建一个简单的Web服务器。虽然这个示例相对简单,但我们可以围绕它展开许多讨论,包括HTTP协议、网络编程、异常处理、多线程等。
|
13天前
|
API Python
Flask-RESTful基础示例
Flask-RESTful基础示例