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

本文涉及的产品
对象存储 OSS,OSS 加速器 50 GB 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快速上手——如何使用ossbrowser
本实验是对象存储OSS入门级实验。通过本实验,用户可学会如何用对象OSS的插件,进行简单的数据存、查、删等操作。
目录
相关文章
|
8月前
|
XML JSON API
识别这些API接口定义(http,https,api,RPC,webservice,Restful api ,OpenAPI)
本内容介绍了API相关的术语分类,包括传输协议(HTTP/HTTPS)、接口风格(RESTful、WebService、RPC)及开放程度(API、OpenAPI),帮助理解各类API的特点与应用场景。
|
10月前
|
JSON 编解码 API
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
|
API 开发者
了解 HTTP 的PUT 与 POST方法的综合指南
HTTP PUT 和 POST 方法是构建 Web 应用与 API 的核心工具,用于资源的创建与更新。PUT 方法通过指定 URL 更新或创建完整资源,具有幂等性;而 POST 方法更灵活,主要用于创建新资源,但不具备幂等性。本文详细对比了两者在请求体、URL 使用、资源处理等方面的区别,并提供了实际应用示例,帮助开发者根据场景选择合适的方法以优化 API 设计。
|
网络协议 JavaScript 安全
第十一篇 前沿趋势与展望:深入探索GraphQL、RESTful API、WebSocket、SSE及QUIC与HTTP/3
第十一篇 前沿趋势与展望:深入探索GraphQL、RESTful API、WebSocket、SSE及QUIC与HTTP/3
533 1
|
网络协议 物联网 网络性能优化
物联网协议比较 MQTT CoAP RESTful/HTTP XMPP
【10月更文挑战第18天】本文介绍了物联网领域中四种主要的通信协议:MQTT、CoAP、RESTful/HTTP和XMPP,分别从其特点、应用场景及优缺点进行了详细对比,并提供了简单的示例代码。适合开发者根据具体需求选择合适的协议。
678 5
|
JSON Go API
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
|
网络协议 物联网 网络性能优化
物联网江湖风云变幻!MQTT CoAP RESTful/HTTP XMPP四大门派谁主沉浮?
【9月更文挑战第3天】物联网(IoT)的兴起催生了多种通信协议,如MQTT、CoAP、RESTful/HTTP和XMPP,各自适用于不同场景。本文将对比这些协议的特点、优缺点,并提供示例代码。MQTT轻量级且支持QoS,适合大规模部署;CoAP基于UDP,适用于低功耗网络;RESTful/HTTP易于集成但不适合资源受限设备;XMPP支持双向通信,适合复杂交互应用。通过本文,开发者可更好地选择合适的物联网通信协议。
353 2
|
网络协议 物联网 网络性能优化
物联网江湖风云变幻!MQTT CoAP RESTful/HTTP XMPP四大门派谁主沉浮?
【8月更文挑战第14天】本文概览了MQTT、CoAP、RESTful/HTTP及XMPP四种物联网通信协议。MQTT采用发布/订阅模式,轻量高效;CoAP针对资源受限设备,基于UDP,低延迟;RESTful/HTTP易于集成现有Web基础设施;XMPP支持双向通信,扩展性强。每种协议均附有示例代码,助您根据不同场景和设备特性作出最佳选择。
269 5
|
存储 前端开发 API
Restful API 设计示例
Restful API 设计示例
205 0
|
前端开发 API 数据库
告别繁琐,拥抱简洁!Python RESTful API 设计实战,让 API 调用如丝般顺滑!
【7月更文挑战第23天】在Python的Flask框架下构建RESTful API,为在线商店管理商品、订单及用户信息。以商品管理为例,设计简洁API端点,如GET `/products`获取商品列表,POST `/products`添加商品,PUT和DELETE则分别用于更新和删除商品。使用SQLAlchemy ORM与SQLite数据库交互,确保数据一致性。实战中还应加入数据验证、错误处理和权限控制,使API既高效又安全,便于前端或其他服务无缝对接。
313 9