Coder Social home page Coder Social logo

cmdb-sdk-python's Introduction

CMDB sdk for Python

中文 / English

build

build and install

> git clone https://github.com/veops/cmdb-sdk-python.git
> cd cmdb-sdk-python

> pip install build wheel setuptools  # requirements
> python -m build -n

veops_cmdb-0.0.1-py3-none-any.whl will be created at cmdb-sdk-python/dist/

tests

before running tests, please make sure you have created the ci model book and rank, they may looks like:

book
    id: int, unique
    book_id: int, unique, not null
    book_name: string, not null,
    author: string

rank:
    id: int, unique
    rank_id: int, unique, not null
    rank: int, not null,

and you alse need to form relationship between book and rank, and then you can run tests.

> pytest -s

usage

If you can ensure the security of your account, you can set the following parameters to environment variables, this way, you won't need to manually pass the initial parameters every time to set up the client.

CMDB_HOST=[your host]
CMDB_KEY=[your_key]
CMDB_SECRET=[your secret]

1.CI

"""
suppose a ci model is Book(id, book_id, book_name, author)
"""

import os

from cmdb.core.ci import CIClient, Option


class TestCI:

    def setup_method(self) -> None:
        opt = Option(
            os.environ["CMDB_HOST"],
            os.environ["CMDB_KEY"],
            os.environ["CMDB_SECRET"],
        )
        self.client = CIClient(opt=opt)

    def test_get(self):
        resp = self.client.get_ci(q="_type:book").result
        print("get")
        print(resp)

    def find_by_name(self, book_name: str):
        q = f"_type:book,book_name:{book_name}"
        resp = self.client.get_ci(q=q).result
        if not resp:
            return
        return resp[0]

    def test_add(self):
        ci = {
            "id": 1,
            "book_id": 1,
            "book_name": "平凡的世界",
            "author": "路遥",
        }
        if self.find_by_name("平凡的世界"):
            return
        resp = self.client.add_ci("book", ci)
        print("add")
        print(resp)

    def test_update(self):
        ci = self.find_by_name("平凡的世界")
        resp = self.client.update_ci("book", ci_id=ci["_id"], attrs={"author": "yao.lu"})
        print("update")
        print(resp)

    def test_delete(self):
        ci = self.find_by_name("平凡的世界")
        resp = self.client.delete_ci(ci["_id"])
        print("delete")
        print(resp)

2.CIRelation

"""
suppose a CI model book with field id, name and author,
suppose a CI model rank with field rank_id, book_id, rank
"""


import os

from cmdb.core.ci import CIClient, Option
from cmdb.core.ci_relations import CIRelationClient


class TestCI:

    def setup_method(self) -> None:
        opt = Option(
            os.environ["CMDB_HOST"],
            os.environ["CMDB_KEY"],
            os.environ["CMDB_SECRET"],
        )
        self.ci_client = CIClient(opt=opt)
        self.client = CIRelationClient(opt=opt)
        self.add_ci()
    
    def add_ci(self):
        book = {
            "id": 1,
            "book_id": 1,
            "book_name": "平凡的世界",
            "author": "路遥",
        }
        rank = {
            "id": 1,
            "rank_id": 1,
            "rank": 5,
        }
        if not self.find_ci(q="_type:book,book_id:1"):
            self.ci_client.add_ci("book", book)
        if not self.find_ci(q="_type:rank,rank_id:1"):
            self.ci_client.add_ci("rank", rank)

    def find_ci(self, q: str):
        resp = self.ci_client.get_ci(q=q).result
        if not resp:
            return
        return resp[0]

    def test_add_ci_relation(self):
        book = self.find_ci(q="_type:book,book_id:1")
        rank = self.find_ci(q="_type:rank,rank_id:1")
        resp = self.client.add_ci_relation(book["_id"], rank["_id"])
        print("add result", resp)

    def test_get_cli_relation(self):
        book = self.find_ci(q="_type:book,book_id:1")
        resp = self.client.get_ci_relation(root_id=book["_id"]).result
        print("get result", resp)

    def test_delete_relation(self):
        book = self.find_ci(q="_type:book,book_id:1")
        rank = self.find_ci(q="_type:rank,rank_id:1")
        resp = self.client.delete_ci_relation(src_ci_id=book["_id"], dst_ci_id=rank["_id"])
        print("delete result", resp)

examples

for full usage examples, please visit exmaples .

cmdb-sdk-python's People

Contributors

pengchuanc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

cmdb-sdk-python's Issues

api 测试“未认证”

测试代码

`"""
@Date: 2023-08-21
@desc:
suppose a CI model book with field book_id, name and author,
this file show how to add, get, update and delete books.
"""

from cmdb import Option, get_client

URL = "http://192.168.1.10:8000/api/v0.1"
KEY ="6786172015b047df81ab7753f027783b"
SECRET = "gSm9W2~D4Vu#$wsQ1OidaZzEo?c!6Y@X"

def add_book():
opt = Option(url=URL, key=KEY, secret=SECRET)
cli = get_client(opt)
book = {"id": 1, "book_id": 1, "book_name": "平凡的世界", "author": "路遥"}
resp = cli.add_ci("book", book)
print(resp.ci_id) # suppose the return ci_id is 2, will be used in update and delete

def update_book():
"""update with ci_id"""
opt = Option(url=URL, key=KEY, secret=SECRET)
cli = get_client(opt)
book = {"book_name": "《平凡的世界》"}
cli.update_ci("book", ci_id=2, attrs=book)

def update_book2():
"""update with unique key in model"""
opt = Option(url=URL, key=KEY, secret=SECRET)
cli = get_client(opt)
# suppose book_id is the unique key of book
book = {"book_name": "《平凡的世界》"}
cli.update_ci("book", attrs=book, book_id=1)

def get_book():
opt = Option(url=URL, key=KEY, secret=SECRET)
cli = get_client(opt)
resp = cli.get_ci(q="_type:book")
books = resp.result
print(books)

def delete_book():
opt = Option(url=URL, key=KEY, secret=SECRET)
cli = get_client(opt)
resp = cli.delete_ci(ci_id=2)
print(resp.message)

a = get_book()`

报错内容

 ~/Downloads/cmdb/demo/cmdb-sdk-python/exmaples/ [main*] python3 ci.py Traceback (most recent call last): File "/Users/hutong/Downloads/cmdb/demo/cmdb-sdk-python/exmaples/ci.py", line 56, in <module> a = get_book() ^^^^^^^^^^ File "/Users/hutong/Downloads/cmdb/demo/cmdb-sdk-python/exmaples/ci.py", line 44, in get_book resp = cli.get_ci(q="_type:book") ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/cmdb/client.py", line 85, in get_ci return self.ci.get_ci(q, fl, facet, count, page, sort, ret_key) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/cmdb/core/ci.py", line 134, in get_ci return self._get_ci(params) ^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/lib/python3.11/site-packages/cmdb/core/ci.py", line 58, in _get_ci self._check_err(resp) File "/opt/homebrew/lib/python3.11/site-packages/cmdb/core/ci.py", line 44, in _check_err raise CMDBError(msg) cmdb.core.exc.CMDBError: 未认证
是什么原因?

Mutable Default Arguments

def add_ci(
            self,
            ci_type: str,
            attrs: dict = {},
            no_attribute_policy: NoAttributePolicy = NoAttributePolicy.default(),
            exist_policy: ExistPolicy = ExistPolicy.default(),
        ) -> CICreateRsp:```

The argument `attrs`  has `{}` as default value which is mutable. 

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.