Oracle oci python sdk简单使用

听说Oracle有个oracle always free计划,所以赶紧申请了个Oracle Cloud的账号,主要是用来FQ用的,之前用过Google的,不过只有1年的期限,由此看来这个很吸引人,搭建的V兔Ray也算稳定,看了看其它可用的东西,自治数据库(ADW)看起来也不错,不过个人感觉更适合大公司吧,目前只是把个人的数据库文件放上面,做个备份。

另外一个就是对象存储了,不过空间有点小,暂时我也用不到,主要是熟悉一下oci的SDK,体验一下Oracle的服务,上面说的自治数据库(ADW)是用的cx_Oracle库,当然这个库也是基于oci的,下面就记录一下oci的简单用法

1. 添加API秘钥

这一步很简单,主要就是会生成一些配置参数,然后把这些参数复制一下,粘贴到对应操作系统的~/.oci/config文件下(需要自行创建),除了会自动生成这个配置,还会让你下载一个私钥,下载完成后,放在和config文件相同路径即可,然后需要在config文件内修改最后一行内容,填写私钥的名称,最好填写私钥的绝对路径


2.代码

先装一下库,pip install oci,最需要注意的是代码中的compartment_id参数,我找了好半天,代码中有注释说明

#coding:utf-8
'''
@version: python3.6
@author: ‘eric‘
@license: Apache Licence
@contact: steinven@qq.com
@software: PyCharm
@file: oci_demo.py
@time: 2021/5/19 10:14
'''
import logging

from oci.object_storage.models import CreateBucketDetails

logging.getLogger().setLevel('INFO')
import oci
config = oci.config.from_file()
object_storage_client = oci.object_storage.ObjectStorageClient(config)
bucket_name = 'test_bucket'
upload_file = 'upload_example_file'

#此compartment_id至在【总菜单】--【身份和安全】--【身份】--【区间】--【对应的跟区间详情】--【ocid】
compartment_id="ocid1.tenancy.oc1..aaaaaaaaonmcrwabeoqpgnnsqkz4k6buf25p5i24sub3duct3iwqesb56roq"

#获取命名空间
name_space = object_storage_client.get_namespace().data
logging.info('【name_space】:%s'%name_space)

#获取Bucket列表
bucket_list = object_storage_client.list_buckets(name_space,compartment_id).data
logging.info('【bucket_list】:%s'%bucket_list)

#新建Bucket
request = CreateBucketDetails()
request.compartment_id = compartment_id
request.name = bucket_name
bucket = object_storage_client.create_bucket(name_space, request)
logging.info('Create Bucket:%s'%bucket.data)


# 上传
with open(upload_file, 'rb') as f:
    obj = object_storage_client.put_object(name_space,bucket_name, upload_file, f)

#文件列表
objects_list = object_storage_client.list_objects(name_space,bucket_name).data
logging.info('【objects_list】:%s'%objects_list)

#下载
with open('dl.file','wb') as f:
    get_obj = object_storage_client.get_object(name_space,bucket_name, objects_list.objects[0].name)
    for chunk in get_obj.data.raw.stream(1024 * 1024, decode_content=False):
        f.write(chunk)

# 删除文件
object_storage_client.delete_object(name_space,bucket_name,upload_file)
# 删除Bucket
object_storage_client.delete_bucket(name_space,bucket_name)
原文地址:https://www.cnblogs.com/steinven/p/14786012.html