本文提供 MongoDB Python SDK 的代码示例供您参考。
使用 Python SDK 调用 MongoDB 接口,默认无超时时间限制。
您可以在发起接口调用请求时,在代码的最后加上 _request_timeout=${超时时间}
参数来指定请求的超时时间(单位:秒),若未在该时间内完成,请求即会终止并报超时错误。
例如,您可以在调用 CreateDBInstance 接口时,通过如下代码将超时时间设置为 10 秒。
resp = api_instance.create_db_instance( volcenginesdkmongodb.CreateDBInstanceRequest( count=1, vpc_id="vpc-13f24t16guqdc3n6nu4k5****", zone_id="cn-beijing-a", node_spec="mongo.1c2g", storage_space_gb=100, subnet_id="subnet-rr96lovl7f28v0x58tv****" ) ), _request_timeout=10) pprint(resp)
说明
关于下述 SDK 代码中所使用参数的定义、取值范围等信息,请参见 CreateDBInstance。
示例 1
使用如下示例代码创建 1 个分片集群实例,配置如下:
import volcenginesdkmongodb import volcenginesdkcore from pprint import pprint if __name__ == '__main__': configuration = volcenginesdkcore.Configuration() configuration.ak = "Your AK" configuration.sk = "Your SK" configuration.region = "Your Region" # set default configuration volcenginesdkcore.Configuration.set_default(configuration) # use global default configuration api_instance = volcenginesdkmongodb.MONGODBApi() # 创建 MonogoDB 实例 resp = api_instance.create_db_instance( volcenginesdkmongodb.CreateDBInstanceRequest( vpc_id="vpc-13f24t16guqdc3n6nu4k5****", zone_id="cn-beijing-a", node_spec="mongo.shard.2c4g", storage_space_gb=100, subnet_id="subnet-rr96lovl7f28v0x58tv****",instance_name="python_sdk_test_shard", mongos_node_spec="mongo.mongos.1c2g",instance_type="ShardedCluster", shard_number=2,mongos_node_number=2 ) ) pprint(resp)
示例 2
使用如下示例代码创建 1 个副本集实例(默认包含 3 个节点),配置如下:
import volcenginesdkmongodb import volcenginesdkcore from pprint import pprint if __name__ == '__main__': configuration = volcenginesdkcore.Configuration() configuration.ak = "Your AK" configuration.sk = "Your SK" configuration.region = "Your Region" # set default configuration volcenginesdkcore.Configuration.set_default(configuration) # use global default configuration api_instance = volcenginesdkmongodb.MONGODBApi() # 创建 MonogoDB 实例 resp = api_instance.create_db_instance( volcenginesdkmongodb.CreateDBInstanceRequest( vpc_id="vpc-13f24t16guqdc3n6nu4k5****", zone_id="cn-beijing-a", node_spec="mongo.1c2g", storage_space_gb=100, subnet_id="subnet-rr96lovl7f28v0x58tv****",instance_name="python_sdk_test_replica" ) ) pprint(resp)
说明
关于下述 SDK 请求中所使用参数的定义、取值范围等信息,请参见 DescribeDBInstanceDetail。
import volcenginesdkmongodb import volcenginesdkcore from pprint import pprint if __name__ == '__main__': configuration = volcenginesdkcore.Configuration() configuration.ak = "Your AK" configuration.sk = "Your SK" configuration.region = "Your Region" # set default configuration volcenginesdkcore.Configuration.set_default(configuration) # use global default configuration api_instance = volcenginesdkmongodb.MONGODBApi() # 查询 MongoDB 实例信息 resp = api_instance.describe_db_instance_detail( volcenginesdkmongodb.DescribeDBInstanceDetailRequest( instance_id="mongo-replica-e649ae42****" ) ) pprint(resp)