Skip to content

Commit

Permalink
refactor the util.ip.get_current_ip_address function (#29)
Browse files Browse the repository at this point in the history
- Close #2
- Lint the project with https://black.readthedocs.io/en/stable/
  • Loading branch information
Oreoxmt authored Oct 14, 2023
1 parent 4fcea06 commit ea70cff
Show file tree
Hide file tree
Showing 28 changed files with 383 additions and 311 deletions.
2 changes: 1 addition & 1 deletion .idea/tidbcloudy.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Python SDK for TiDB Cloud

[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

`tidbcloudy` is an **unofficial** Python SDK for [TiDB Cloud](https://tidbcloud.com). If you encounter any problems or have suggestions, feel free to open an issue on the GitHub repository [Oreoxmt/tidbcloudy](https://github.com/Oreoxmt/tidbcloudy).

## Table of contents
Expand Down Expand Up @@ -71,6 +73,23 @@ You can use this SDK to access [TiDB Cloud](https://tidbcloud.com) and manage yo
</tr>
</thead>
<tbody>
<tr>
<td><a href="https://github.com/Oreoxmt/tidbcloudy/releases/tag/v1.1.1" target="_blank" rel="noopener noreferrer">1.1.1</a></td>
<td>✅</td>
<td>❌</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>❌</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
<td>✅</td>
</tr>
<tr>
<td><a href="https://github.com/Oreoxmt/tidbcloudy/releases/tag/v1.1.0" target="_blank" rel="noopener noreferrer">1.1.0</a></td>
<td>✅</td>
Expand Down
18 changes: 11 additions & 7 deletions examples/1_list_provider_regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,19 @@
print(f" region: {spec.region}")
print(f" components:")
for tidb in spec.tidb:
print(f" - tidb: {tidb.node_size}; "
f"min={tidb.node_quantity_range.min} step={tidb.node_quantity_range.step}")
print(
f" - tidb: {tidb.node_size}; " f"min={tidb.node_quantity_range.min} step={tidb.node_quantity_range.step}"
)
for tikv in spec.tikv:
print(f" - tikv: {tikv.node_size}; "
f"min={tikv.node_quantity_range.min} "
f"step={tikv.node_quantity_range.step}; "
f"{tikv.storage_size_gib_range.min}..{tikv.storage_size_gib_range.max} GiB")
print(
f" - tikv: {tikv.node_size}; "
f"min={tikv.node_quantity_range.min} "
f"step={tikv.node_quantity_range.step}; "
f"{tikv.storage_size_gib_range.min}..{tikv.storage_size_gib_range.max} GiB"
)
for tiflash in spec.tiflash:
print(
f" - tiflash: {tiflash.node_size}; "
f"min={tiflash.node_quantity_range.min} step={tiflash.node_quantity_range.step}; "
f"{tiflash.storage_size_gib_range.min}..{tiflash.storage_size_gib_range.max} GiB")
f"{tiflash.storage_size_gib_range.min}..{tiflash.storage_size_gib_range.max} GiB"
)
17 changes: 9 additions & 8 deletions examples/2_1_create_serverless_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,16 @@
api = tidbcloudy.TiDBCloud(public_key=public_key, private_key=private_key)
project = api.get_project(project_id, update_from_server=True)

config = CreateClusterConfig()
config \
.set_name("serverless-0") \
.set_cluster_type("DEVELOPER") \
.set_cloud_provider("AWS") \
.set_region("us-west-2") \
.set_root_password("your_root_password") \
.add_ip_access(cidr="0.0.0.0/0") \
config = (
CreateClusterConfig()
.set_name("serverless-0")
.set_cluster_type("DEVELOPER")
.set_cloud_provider("AWS")
.set_region("us-west-2")
.set_root_password("your_root_password")
.add_ip_access(cidr="0.0.0.0/0")
.add_current_ip_access()
)
cluster = project.create_cluster(config)
print(cluster)

Expand Down
21 changes: 11 additions & 10 deletions examples/2_2_create_dedicated_cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@
api = tidbcloudy.TiDBCloud(public_key=public_key, private_key=private_key)
project = api.get_project(project_id, update_from_server=True)

config = CreateClusterConfig()
config \
.set_name("dedicated-1") \
.set_cluster_type("DEDICATED") \
.set_cloud_provider("AWS") \
.set_region("us-west-2") \
.set_port(4399) \
.set_root_password("your_root_password") \
.set_component("tidb", "4C16G", 1) \
.set_component("tikv", "4C16G", 3, 200) \
config = (
CreateClusterConfig()
.set_name("dedicated-1")
.set_cluster_type("DEDICATED")
.set_cloud_provider("AWS")
.set_region("us-west-2")
.set_port(4399)
.set_root_password("your_root_password")
.set_component("tidb", "4C16G", 1)
.set_component("tikv", "4C16G", 3, 200)
.add_current_ip_access()
)
cluster = project.create_cluster(config)
print(cluster)

Expand Down
5 changes: 3 additions & 2 deletions examples/3_connect_mysql.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@

if cluster.status.cluster_status == ClusterStatus.AVAILABLE:
connection_strings = cluster.status.connection_strings
connection = cluster.connect(type="standard", database="test",
password=os.environ.get("CLUSTER_PWD", "your_root_password"))
connection = cluster.connect(
type="standard", database="test", password=os.environ.get("CLUSTER_PWD", "your_root_password")
)
print(connection)
with connection:
with connection.cursor() as cursor:
Expand Down
21 changes: 11 additions & 10 deletions examples/5_backup_restore.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,18 @@
backup = cluster.create_backup(name="backup-1", description="automatically generated by tidbcloudy")
print(backup)

config = CreateClusterConfig()
config \
.set_cluster_type("DEDICATED") \
.set_cloud_provider("AWS") \
.set_region("us-west-2") \
.set_port(4399) \
.set_root_password("your_root_password") \
.set_component("tidb", "8C16G", 1) \
.set_component("tikv", "8C32G", 3, 500) \
.set_component("tiflash", "8C64G", 1, 500) \
config = (
CreateClusterConfig()
.set_cluster_type("DEDICATED")
.set_cloud_provider("AWS")
.set_region("us-west-2")
.set_port(4399)
.set_root_password("your_root_password")
.set_component("tidb", "8C16G", 1)
.set_component("tikv", "8C32G", 3, 500)
.set_component("tiflash", "8C64G", 1, 500)
.add_current_ip_access()
)
print("Create a restore task from backup_id={}".format(backup_id))
restore = project.create_restore(backup_id=backup_id, name="restore-1", cluster_config=config)
restore_task = project.get_restore(restore.id)
Expand Down
4 changes: 1 addition & 3 deletions mock_server/models/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ def create_billing_blueprint():

@bp.errorhandler(HTTPStatusError)
def handle_status_error(exc: HTTPStatusError):
return jsonify({
"error": exc.response.text
}), exc.response.status_code
return jsonify({"error": exc.response.text}), exc.response.status_code

@bp.route("<string:month>", methods=["GET"])
def tidbcloudy_get_monthly_bill(month: str) -> [Response, int]:
Expand Down
8 changes: 2 additions & 6 deletions mock_server/models/clusters.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ def create_clusters_blueprint():

@bp.errorhandler(HTTPStatusError)
def handle_status_error(exc: HTTPStatusError):
return jsonify({
"error": exc.response.text
}), exc.response.status_code
return jsonify({"error": exc.response.text}), exc.response.status_code

@bp.route("/provider/regions", methods=["GET"])
def tidbcloudy_provider() -> [Response, int]:
provider_regions = [CloudSpecification.from_object(contex, item) for item in CONFIG["provider_regions"]]
provider_regions_obj = pro_service.list_provider_regions(provider_regions)
resp = {
"items": [item.to_object() for item in provider_regions_obj]
}
resp = {"items": [item.to_object() for item in provider_regions_obj]}
return resp, 200

return bp
28 changes: 6 additions & 22 deletions mock_server/models/projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,38 +18,29 @@ def create_projects_blueprint():

@bp.errorhandler(HTTPStatusError)
def handle_status_error(exc: HTTPStatusError):
return jsonify({
"error": exc.response.text
}), exc.response.status_code
return jsonify({"error": exc.response.text}), exc.response.status_code

@bp.route("", methods=["GET"])
def tidbcloudy_list_projects() -> [Response, int]:
projects = [Project.from_object(contex, item) for item in CONFIG["projects"]]
page = request.args.get("page", default=1, type=int)
page_size = request.args.get("page_size", default=10, type=int)
return_projects = org_service.list_projects(projects, page, page_size)
resp = jsonify({
"items": [item.to_object() for item in return_projects],
"total": len(projects)
})
resp = jsonify({"items": [item.to_object() for item in return_projects], "total": len(projects)})
return resp, 200

@bp.route("", methods=["POST"])
def tidbcloudy_create_project() -> [Response, int]:
new_project = org_service.create_project(request.json)
CONFIG["projects"].append(new_project.to_object())
resp = jsonify({
"id": new_project.id
})
resp = jsonify({"id": new_project.id})
return resp, 200

@bp.route("/<string:project_id>/aws-cmek", methods=["GET"])
def tidbcloudy_list_project_aws_cmeks(project_id) -> [Response, int]:
projects = CONFIG["projects"]
project_cmeks = pro_service.list_project_aws_cmeks(projects, project_id)
resp = jsonify({
"items": project_cmeks
})
resp = jsonify({"items": project_cmeks})
return resp, 200

@bp.route("/<string:project_id>/aws-cmek", methods=["POST"])
Expand All @@ -65,21 +56,14 @@ def tidbcloudy_list_clusters(project_id) -> [Response, int]:
page = request.args.get("page", default=1, type=int)
page_size = request.args.get("page_size", default=10, type=int)
return_clusters, total = pro_service.list_clusters(clusters, project_id, page, page_size)
resp = jsonify(
{
"items": [item.to_object() for item in return_clusters],
"total": total
}
)
resp = jsonify({"items": [item.to_object() for item in return_clusters], "total": total})
return resp, 200

@bp.route("/<string:project_id>/clusters", methods=["POST"])
def tidbcloudy_create_cluster(project_id) -> [Response, int]:
new_cluster = pro_service.create_cluster(project_id, request.json)
CONFIG["clusters"].append(new_cluster.to_object())
resp = jsonify({
"id": new_cluster.id
})
resp = jsonify({"id": new_cluster.id})
return resp, 200

@bp.route("/<string:project_id>/clusters/<string:cluster_id>", methods=["GET"])
Expand Down
4 changes: 1 addition & 3 deletions mock_server/server_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ def load_config(filename: str = "mock_config.json") -> Dict[str, Any]:
with open(f"{os.path.dirname(__file__)}/{filename}", "r", encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
raise FileNotFoundError(
f"Configuration file '{filename}' not found in '{os.path.dirname(__file__)}'."
)
raise FileNotFoundError(f"Configuration file '{filename}' not found in '{os.path.dirname(__file__)}'.")
except json.JSONDecodeError:
raise ValueError(f"Fail to decode {filename}")

Expand Down
29 changes: 16 additions & 13 deletions mock_server/services/org_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,29 @@ def __init__(self):

@staticmethod
def list_projects(projects: List[Project], page: int, page_size: int) -> List[Project]:
return_projects = projects[(page - 1) * page_size: page * page_size]
return_projects = projects[(page - 1) * page_size : page * page_size]
return return_projects

def create_project(self, body: dict) -> Project:
new_project = Project.from_object(self._context, {
"id": str(uuid.uuid4().int % (10 ** 19)),
"org_id": self.org_id,
"name": body["name"],
"aws_cmek_enabled": body["aws_cmek_enabled"] if "aws_cmek_enabled" in body else False,
"cluster_count": 0,
"user_count": 1,
"create_timestamp": str(int(datetime.now().timestamp()))
})
new_project = Project.from_object(
self._context,
{
"id": str(uuid.uuid4().int % (10**19)),
"org_id": self.org_id,
"name": body["name"],
"aws_cmek_enabled": body["aws_cmek_enabled"] if "aws_cmek_enabled" in body else False,
"cluster_count": 0,
"user_count": 1,
"create_timestamp": str(int(datetime.now().timestamp())),
},
)
return new_project

@staticmethod
def get_monthly_bill(billings: List[BillingMonthSummary], month: str) -> BillingMonthSummary:
for billing in billings:
if billing.overview.billedMonth == month:
return billing
raise HTTPStatusError("",
request=Request("GET", ""),
response=Response(400, text="The billing month is not found"))
raise HTTPStatusError(
"", request=Request("GET", ""), response=Response(400, text="The billing month is not found")
)
Loading

0 comments on commit ea70cff

Please sign in to comment.