diff --git a/.github/workflows/black-docstr.yml b/.github/workflows/black-docstr.yml index 3c7a6b382..0718a0bf2 100644 --- a/.github/workflows/black-docstr.yml +++ b/.github/workflows/black-docstr.yml @@ -14,7 +14,7 @@ jobs: run: | sudo apt-get update sudo apt-get install git python3-pip -y - sudo pip3 install black==19.10b0 docstr-coverage + sudo pip3 install black==22.10.0 docstr-coverage FILES="$(git diff --name-only --diff-filter=A --diff-filter=M "origin/${{github.base_ref}}" '*.py')" black --check -l 120 -t py37 --exclude 'templates' $FILES for FILE in $FILES; do echo $FILE; docstr-coverage $FILE || true; done diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f93ad3945..a3961717d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,14 +3,14 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.4.0 + rev: v4.3.0 hooks: - id: check-yaml - id: end-of-file-fixer - id: trailing-whitespace - id: check-merge-conflict - repo: https://github.com/psf/black - rev: 19.10b0 + rev: 22.10.0 hooks: - id: black args: [--line-length=120, --target-version=py37] diff --git a/README.md b/README.md index f7f6229aa..ba5f0bc20 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ config management/automation framework ## Principles - pip installable -- facilities exposed under `god object`: `j` +- facilities exposed under `loader object`: `j` - pluggable - docs and tests are as important as code diff --git a/docs/api/jumpscale/clients/currencylayer/currencies.html b/docs/api/jumpscale/clients/currencylayer/currencies.html deleted file mode 100644 index 7456a57d9..000000000 --- a/docs/api/jumpscale/clients/currencylayer/currencies.html +++ /dev/null @@ -1,232 +0,0 @@ - - - - - - -jumpscale.clients.currencylayer.currencies API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.currencylayer.currencies

-
-
-
-Source code -
CURRENCIES = {
-    "aed": 3.672798,
-    "afn": 71.150002,
-    "all": 104.900002,
-    "amd": 482.799988,
-    "ang": 1.789542,
-    "aoa": 238.544006,
-    "ars": 24.896023,
-    "aud": 1.306702,
-    "awg": 1.78,
-    "azn": 1.699505,
-    "bam": 1.656031,
-    "bbd": 2,
-    "bdt": 84.099998,
-    "bgn": 1.6624,
-    "bhd": 0.377503,
-    "bif": 1750.97998,
-    "bmd": 1,
-    "bnd": 1.321296,
-    "bob": 6.859653,
-    "brl": 3.846501,
-    "bsd": 1,
-    "btc": 0.00013,
-    "btn": 66.925003,
-    "bwp": 9.995016,
-    "byn": 2.000042,
-    "byr": 19600,
-    "bzd": 1.997802,
-    "cad": 1.29528,
-    "cdf": 1565.499204,
-    "chf": 0.98171,
-    "clf": 0.02292,
-    "clp": 627.700012,
-    "cny": 6.392502,
-    "cop": 2828,
-    "crc": 564.749842,
-    "cuc": 1,
-    "cup": 26.5,
-    "cve": 93.239998,
-    "czk": 21.658998,
-    "djf": 177.498647,
-    "dkk": 6.29685,
-    "dop": 49.519768,
-    "dzd": 115.929789,
-    "egp": 17.809999,
-    "ern": 14.989959,
-    "etb": 27.209999,
-    "eth": 607.56,
-    "eur": 0.845101,
-    "fjd": 2.052503,
-    "fkp": 0.744398,
-    "gbp": 0.74283,
-    "gel": 2.436399,
-    "ggp": 0.74271,
-    "ghs": 4.708496,
-    "gip": 0.744601,
-    "gmd": 46.849998,
-    "gnf": 9005.00012,
-    "gtq": 7.336024,
-    "gyd": 207.479996,
-    "hkd": 7.84544,
-    "hnl": 23.865999,
-    "hrk": 6.239802,
-    "htg": 63.009998,
-    "huf": 267.98999,
-    "idr": 13863,
-    "ils": 3.570702,
-    "imp": 0.74271,
-    "inr": 67.037498,
-    "iqd": 1184,
-    "irr": 42189.999401,
-    "isk": 105.250285,
-    "jep": 0.74271,
-    "jmd": 127.459999,
-    "jod": 0.709596,
-    "jpy": 109.914001,
-    "kes": 100.599998,
-    "kgs": 68.425003,
-    "khr": 4070.000031,
-    "kmf": 416.950012,
-    "kpw": 900.000395,
-    "krw": 1067.319946,
-    "kwd": 0.301798,
-    "kyd": 0.819835,
-    "kzt": 333.399994,
-    "lak": 8340.000397,
-    "lbp": 1504.999817,
-    "lkr": 158.699997,
-    "lrd": 138.270004,
-    "lsl": 12.710279,
-    "ltl": 3.0487,
-    "lvl": 0.62055,
-    "lyd": 1.358105,
-    "mad": 9.413802,
-    "mdl": 16.724953,
-    "mga": 3270.000207,
-    "mkd": 51.770006,
-    "mmk": 1352.000157,
-    "mnt": 2406.000152,
-    "mop": 8.080397,
-    "mro": 354.000075,
-    "mur": 33.849998,
-    "mvr": 15.569619,
-    "mwk": 717.359985,
-    "mxn": 20.368401,
-    "myr": 3.974993,
-    "mzn": 58.820231,
-    "nad": 12.716026,
-    "ngn": 357.999747,
-    "nio": 31.447599,
-    "nok": 8.02761,
-    "npr": 107.099998,
-    "nzd": 1.418004,
-    "omr": 0.384801,
-    "pab": 1,
-    "pen": 3.260601,
-    "pgk": 3.260104,
-    "php": 52.450001,
-    "pkr": 115.599998,
-    "pln": 3.603797,
-    "pyg": 5668.399902,
-    "qar": 3.639797,
-    "ron": 3.9354,
-    "rsd": 99.820999,
-    "rub": 61.893799,
-    "rwf": 848.200012,
-    "sar": 3.749802,
-    "sbd": 7.933964,
-    "scr": 13.429735,
-    "sdg": 17.955099,
-    "sek": 8.65494,
-    "sgd": 1.33102,
-    "shp": 0.744596,
-    "sll": 7849.99989,
-    "sos": 562.999736,
-    "srd": 7.419726,
-    "std": 20718.800781,
-    "svc": 8.750051,
-    "syp": 514.97998,
-    "szl": 12.716961,
-    "thb": 31.909815,
-    "tjs": 9.049018,
-    "tmt": 3.41,
-    "tnd": 2.5476,
-    "top": 2.2843,
-    "try": 4.562502,
-    "ttd": 6.649497,
-    "twd": 29.684036,
-    "tzs": 2268.000038,
-    "uah": 26.163009,
-    "ugx": 3801.999988,
-    "usd": 1,
-    "uyu": 31.079742,
-    "uzs": 7924.999809,
-    "vef": 79800.000475,
-    "vnd": 22800,
-    "vuv": 106.209999,
-    "wst": 2.562898,
-    "xaf": 554.150024,
-    "xag": 0.059753,
-    "xau": 0.00077,
-    "xcd": 2.698788,
-    "xdr": 0.704103,
-    "xof": 554.150024,
-    "xpf": 100.903624,
-    "xrp": 0.6805,
-    "yer": 249.929993,
-    "zar": 12.723501,
-    "zmk": 9001.212517,
-    "zmw": 10.080297,
-    "zwl": 322.355011,
-}
-
-
-CURRNECIES_IDS = dict(zip(range(1, len(CURRENCIES)+1), CURRENCIES.keys()))
-IDS_CURRENCIES = dict(zip(CURRENCIES.keys(), range(1, len(CURRENCIES)+1)))
-
-
-
-
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/clients/currencylayer/currencylayer.html b/docs/api/jumpscale/clients/currencylayer/currencylayer.html deleted file mode 100644 index 763fada04..000000000 --- a/docs/api/jumpscale/clients/currencylayer/currencylayer.html +++ /dev/null @@ -1,454 +0,0 @@ - - - - - - -jumpscale.clients.currencylayer.currencylayer API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.currencylayer.currencylayer

-
-
-
-Source code -
from pprint import pprint as print
-import cryptocompare as cc
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-from jumpscale.loader import j
-from .currencies import CURRENCIES, CURRNECIES_IDS
-from pprint import pprint
-
-
-def get_currency_data(api_key, fake=False, fakeonerror=False):
-    if fake:
-        return CURRENCIES
-    else:
-        url = "http://apilayer.net/api/live?access_key={}".format(api_key)
-        r = j.tools.http.get(url)
-        try:
-            json_res = r.json()
-            data = json_res["quotes"]
-
-            data["USDETH"] = 1 / cc.get_price("ETH", "USD")["ETH"]["USD"]
-            data["USDXRP"] = cc.get_price("USD", "XRP")["USD"]["XRP"]
-            data["USDBTC"] = 1 / cc.get_price("BTC", "USD")["BTC"]["USD"]
-
-            normalized_data = {k.lower().lstrip("usd"):v for k,v in data.items()}
-            return normalized_data
-
-        except Exception as e:
-            print("error happened")
-            if not fakeonerror:
-                raise e
-            else:
-                return CURRENCIES
-
-class CurrencyLayerClient(Client):
-
-    name = fields.String()
-    api_key = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-        self._data_cur = {}
-        self._id2cur = {}
-        self._cur2id = {}
-        self.fake = True
-
-    def load(self):
-        # data = self._cache.get("currency_data", get, expire=3600 * 24)
-        data = get_currency_data(self.api_key, fake=False)
-        self._data_cur = data
-
-    @property
-    def cur2usd(self):
-        """
-        e.g. AED = 3,672 means 3,6... times AED=1 USD
-        """
-        if not self._data_cur:
-            self.load()
-        return self._data_cur
-
-    def cur2usd_print(self):
-        print(self.cur2usd)
-
-    @property
-    def id2cur(self):
-        if not self._id2cur:
-            self._id2cur = CURRNECIES_IDS
-        return self._id2cur
-
-    @property
-    def cur2id(self):
-        if not self._cur2id:
-            self._cur2id = dict(zip(self.id2cur.values(), self.id2cur.keys()))
-        return self._cur2id
-
-    def id2cur_print(self):
-        pprint(self.id2cur)
-
-    def cur2id_print(self):
-        pprint(self.cur2id)
-
-    def test(self):
-        self._log_info(self.cur2usd)
-        assert "aed" in self.cur2usd
-
-
-
-
-
-
-
-

Functions

-
-
-def get_currency_data(api_key, fake=False, fakeonerror=False) -
-
-
-
-Source code -
def get_currency_data(api_key, fake=False, fakeonerror=False):
-    if fake:
-        return CURRENCIES
-    else:
-        url = "http://apilayer.net/api/live?access_key={}".format(api_key)
-        r = j.tools.http.get(url)
-        try:
-            json_res = r.json()
-            data = json_res["quotes"]
-
-            data["USDETH"] = 1 / cc.get_price("ETH", "USD")["ETH"]["USD"]
-            data["USDXRP"] = cc.get_price("USD", "XRP")["USD"]["XRP"]
-            data["USDBTC"] = 1 / cc.get_price("BTC", "USD")["BTC"]["USD"]
-
-            normalized_data = {k.lower().lstrip("usd"):v for k,v in data.items()}
-            return normalized_data
-
-        except Exception as e:
-            print("error happened")
-            if not fakeonerror:
-                raise e
-            else:
-                return CURRENCIES
-
-
-
-
-
-

Classes

-
-
-class CurrencyLayerClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class CurrencyLayerClient(Client):
-
-    name = fields.String()
-    api_key = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-        self._data_cur = {}
-        self._id2cur = {}
-        self._cur2id = {}
-        self.fake = True
-
-    def load(self):
-        # data = self._cache.get("currency_data", get, expire=3600 * 24)
-        data = get_currency_data(self.api_key, fake=False)
-        self._data_cur = data
-
-    @property
-    def cur2usd(self):
-        """
-        e.g. AED = 3,672 means 3,6... times AED=1 USD
-        """
-        if not self._data_cur:
-            self.load()
-        return self._data_cur
-
-    def cur2usd_print(self):
-        print(self.cur2usd)
-
-    @property
-    def id2cur(self):
-        if not self._id2cur:
-            self._id2cur = CURRNECIES_IDS
-        return self._id2cur
-
-    @property
-    def cur2id(self):
-        if not self._cur2id:
-            self._cur2id = dict(zip(self.id2cur.values(), self.id2cur.keys()))
-        return self._cur2id
-
-    def id2cur_print(self):
-        pprint(self.id2cur)
-
-    def cur2id_print(self):
-        pprint(self.cur2id)
-
-    def test(self):
-        self._log_info(self.cur2usd)
-        assert "aed" in self.cur2usd
-
-

Ancestors

- -

Instance variables

-
-
var api_key
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var cur2id
-
-
-
-Source code -
@property
-def cur2id(self):
-    if not self._cur2id:
-        self._cur2id = dict(zip(self.id2cur.values(), self.id2cur.keys()))
-    return self._cur2id
-
-
-
var cur2usd
-
-

e.g. AED = 3,672 means 3,6… times AED=1 USD

-
-Source code -
@property
-def cur2usd(self):
-    """
-    e.g. AED = 3,672 means 3,6... times AED=1 USD
-    """
-    if not self._data_cur:
-        self.load()
-    return self._data_cur
-
-
-
var id2cur
-
-
-
-Source code -
@property
-def id2cur(self):
-    if not self._id2cur:
-        self._id2cur = CURRNECIES_IDS
-    return self._id2cur
-
-
-
var name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def cur2id_print(self) -
-
-
-
-Source code -
def cur2id_print(self):
-    pprint(self.cur2id)
-
-
-
-def cur2usd_print(self) -
-
-
-
-Source code -
def cur2usd_print(self):
-    print(self.cur2usd)
-
-
-
-def id2cur_print(self) -
-
-
-
-Source code -
def id2cur_print(self):
-    pprint(self.id2cur)
-
-
-
-def load(self) -
-
-
-
-Source code -
def load(self):
-    # data = self._cache.get("currency_data", get, expire=3600 * 24)
-    data = get_currency_data(self.api_key, fake=False)
-    self._data_cur = data
-
-
-
-def test(self) -
-
-
-
-Source code -
def test(self):
-    self._log_info(self.cur2usd)
-    assert "aed" in self.cur2usd
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/currencylayer/index.html b/docs/api/jumpscale/clients/currencylayer/index.html deleted file mode 100644 index 4cd249156..000000000 --- a/docs/api/jumpscale/clients/currencylayer/index.html +++ /dev/null @@ -1,1519 +0,0 @@ - - - - - - -jumpscale.clients.currencylayer API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.currencylayer

-
-
-
-
JS-NG> fake = j.clients.currencylayer.new('fake')
-
JS-NG> fake.cur2id_print()
-
{'aed': 1,
-
'afn': 2,
-
'all': 3,
-
'amd': 4,
-
'ang': 5,
-
'aoa': 6,
-
'ars': 7,
-
'aud': 8,
-
'awg': 9,
-
'azn': 10,
-
'bam': 11,
-
'bbd': 12,
-
'bdt': 13,
-
'bgn': 14,
-
'bhd': 15,
-
'bif': 16,
-
'bmd': 17,
-
'bnd': 18,
-
'bob': 19,
-
'brl': 20,
-
'bsd': 21,
-
'btc': 22,
-
'btn': 23,
-
'bwp': 24,
-
'byn': 25,
-
'byr': 26,
-
'bzd': 27,
-
'cad': 28,
-
'cdf': 29,
-
'chf': 30,
-
'clf': 31,
-
'clp': 32,
-
'cny': 33,
-
'cop': 34,
-
'crc': 35,
-
'cuc': 36,
-
'cup': 37,
-
'cve': 38,
-
'czk': 39,
-
'djf': 40,
-
'dkk': 41,
-
'dop': 42,
-
'dzd': 43,
-
'egp': 44,
-
'ern': 45,
-
'etb': 46,
-
'eth': 47,
-
'eur': 48,
-
'fjd': 49,
-
'fkp': 50,
-
'gbp': 51,
-
'gel': 52,
-
'ggp': 53,
-
'ghs': 54,
-
'gip': 55,
-
'gmd': 56,
-
'gnf': 57,
-
'gtq': 58,
-
'gyd': 59,
-
'hkd': 60,
-
'hnl': 61,
-
'hrk': 62,
-
'htg': 63,
-
'huf': 64,
-
'idr': 65,
-
'ils': 66,
-
'imp': 67,
-
'inr': 68,
-
'iqd': 69,
-
'irr': 70,
-
'isk': 71,
-
'jep': 72,
-
'jmd': 73,
-
'jod': 74,
-
'jpy': 75,
-
'kes': 76,
-
'kgs': 77,
-
'khr': 78,
-
'kmf': 79,
-
'kpw': 80,
-
'krw': 81,
-
'kwd': 82,
-
'kyd': 83,
-
'kzt': 84,
-
'lak': 85,
-
'lbp': 86,
-
'lkr': 87,
-
'lrd': 88,
-
'lsl': 89,
-
'ltl': 90,
-
'lvl': 91,
-
'lyd': 92,
-
'mad': 93,
-
'mdl': 94,
-
'mga': 95,
-
'mkd': 96,
-
'mmk': 97,
-
'mnt': 98,
-
'mop': 99,
-
'mro': 100,
-
'mur': 101,
-
'mvr': 102,
-
'mwk': 103,
-
'mxn': 104,
-
'myr': 105,
-
'mzn': 106,
-
'nad': 107,
-
'ngn': 108,
-
'nio': 109,
-
'nok': 110,
-
'npr': 111,
-
'nzd': 112,
-
'omr': 113,
-
'pab': 114,
-
'pen': 115,
-
'pgk': 116,
-
'php': 117,
-
'pkr': 118,
-
'pln': 119,
-
'pyg': 120,
-
'qar': 121,
-
'ron': 122,
-
'rsd': 123,
-
'rub': 124,
-
'rwf': 125,
-
'sar': 126,
-
'sbd': 127,
-
'scr': 128,
-
'sdg': 129,
-
'sek': 130,
-
'sgd': 131,
-
'shp': 132,
-
'sll': 133,
-
'sos': 134,
-
'srd': 135,
-
'std': 136,
-
'svc': 137,
-
'syp': 138,
-
'szl': 139,
-
'thb': 140,
-
'tjs': 141,
-
'tmt': 142,
-
'tnd': 143,
-
'top': 144,
-
'try': 145,
-
'ttd': 146,
-
'twd': 147,
-
'tzs': 148,
-
'uah': 149,
-
'ugx': 150,
-
'usd': 151,
-
'uyu': 152,
-
'uzs': 153,
-
'vef': 154,
-
'vnd': 155,
-
'vuv': 156,
-
'wst': 157,
-
'xaf': 158,
-
'xag': 159,
-
'xau': 160,
-
'xcd': 161,
-
'xdr': 162,
-
'xof': 163,
-
'xpf': 164,
-
'xrp': 165,
-
'yer': 166,
-
'zar': 167,
-
'zmk': 168,
-
'zmw': 169,
-
'zwl': 170}
-
JS-NG> fake.id2cur_print()
-
{1: 'aed',
-
2: 'afn',
-
3: 'all',
-
4: 'amd',
-
5: 'ang',
-
6: 'aoa',
-
7: 'ars',
-
8: 'aud',
-
9: 'awg',
-
10: 'azn',
-
11: 'bam',
-
12: 'bbd',
-
13: 'bdt',
-
14: 'bgn',
-
15: 'bhd',
-
16: 'bif',
-
17: 'bmd',
-
18: 'bnd',
-
19: 'bob',
-
20: 'brl',
-
21: 'bsd',
-
22: 'btc',
-
23: 'btn',
-
24: 'bwp',
-
25: 'byn',
-
26: 'byr',
-
27: 'bzd',
-
28: 'cad',
-
29: 'cdf',
-
30: 'chf',
-
31: 'clf',
-
32: 'clp',
-
33: 'cny',
-
34: 'cop',
-
35: 'crc',
-
36: 'cuc',
-
37: 'cup',
-
38: 'cve',
-
39: 'czk',
-
40: 'djf',
-
41: 'dkk',
-
42: 'dop',
-
43: 'dzd',
-
44: 'egp',
-
45: 'ern',
-
46: 'etb',
-
47: 'eth',
-
48: 'eur',
-
49: 'fjd',
-
50: 'fkp',
-
51: 'gbp',
-
52: 'gel',
-
53: 'ggp',
-
54: 'ghs',
-
55: 'gip',
-
56: 'gmd',
-
57: 'gnf',
-
58: 'gtq',
-
59: 'gyd',
-
60: 'hkd',
-
61: 'hnl',
-
62: 'hrk',
-
63: 'htg',
-
64: 'huf',
-
65: 'idr',
-
66: 'ils',
-
67: 'imp',
-
68: 'inr',
-
69: 'iqd',
-
70: 'irr',
-
71: 'isk',
-
72: 'jep',
-
73: 'jmd',
-
74: 'jod',
-
75: 'jpy',
-
76: 'kes',
-
77: 'kgs',
-
78: 'khr',
-
79: 'kmf',
-
80: 'kpw',
-
81: 'krw',
-
82: 'kwd',
-
83: 'kyd',
-
84: 'kzt',
-
85: 'lak',
-
86: 'lbp',
-
87: 'lkr',
-
88: 'lrd',
-
89: 'lsl',
-
90: 'ltl',
-
91: 'lvl',
-
92: 'lyd',
-
93: 'mad',
-
94: 'mdl',
-
95: 'mga',
-
96: 'mkd',
-
97: 'mmk',
-
98: 'mnt',
-
99: 'mop',
-
100: 'mro',
-
101: 'mur',
-
102: 'mvr',
-
103: 'mwk',
-
104: 'mxn',
-
105: 'myr',
-
106: 'mzn',
-
107: 'nad',
-
108: 'ngn',
-
109: 'nio',
-
110: 'nok',
-
111: 'npr',
-
112: 'nzd',
-
113: 'omr',
-
114: 'pab',
-
115: 'pen',
-
116: 'pgk',
-
117: 'php',
-
118: 'pkr',
-
119: 'pln',
-
120: 'pyg',
-
121: 'qar',
-
122: 'ron',
-
123: 'rsd',
-
124: 'rub',
-
125: 'rwf',
-
126: 'sar',
-
127: 'sbd',
-
128: 'scr',
-
129: 'sdg',
-
130: 'sek',
-
131: 'sgd',
-
132: 'shp',
-
133: 'sll',
-
134: 'sos',
-
135: 'srd',
-
136: 'std',
-
137: 'svc',
-
138: 'syp',
-
139: 'szl',
-
140: 'thb',
-
141: 'tjs',
-
142: 'tmt',
-
143: 'tnd',
-
144: 'top',
-
145: 'try',
-
146: 'ttd',
-
147: 'twd',
-
148: 'tzs',
-
149: 'uah',
-
150: 'ugx',
-
151: 'usd',
-
152: 'uyu',
-
153: 'uzs',
-
154: 'vef',
-
155: 'vnd',
-
156: 'vuv',
-
157: 'wst',
-
158: 'xaf',
-
159: 'xag',
-
160: 'xau',
-
161: 'xcd',
-
162: 'xdr',
-
163: 'xof',
-
164: 'xpf',
-
165: 'xrp',
-
166: 'yer',
-
167: 'zar',
-
168: 'zmk',
-
169: 'zmw',
-
170: 'zwl'}
-
JS-NG> fake.id2cur
-
{1: 'aed', 2: 'afn', 3: 'all', 4: 'amd', 5: 'ang', 6: 'aoa', 7: 'ars', 8: 'aud', 9: 'awg', 10: 'azn', 11: 'bam', 12: 'b
-
bd', 13: 'bdt', 14: 'bgn', 15: 'bhd', 16: 'bif', 17: 'bmd', 18: 'bnd', 19: 'bob', 20: 'brl', 21: 'bsd', 22: 'btc', 23:
-
'btn', 24: 'bwp', 25: 'byn', 26: 'byr', 27: 'bzd', 28: 'cad', 29: 'cdf', 30: 'chf', 31: 'clf', 32: 'clp', 33: 'cny', 34
-
'cop', 35: 'crc', 36: 'cuc', 37: 'cup', 38: 'cve', 39: 'czk', 40: 'djf', 41: 'dkk', 42: 'dop', 43: 'dzd', 44: 'egp', -45: 'ern', 46: 'etb', 47: 'eth', 48: 'eur', 49: 'fjd', 50: 'fkp', 51: 'gbp', 52: 'gel', 53: 'ggp', 54: 'ghs', 55: 'gip' -, 56: 'gmd', 57: 'gnf', 58: 'gtq', 59: 'gyd', 60: 'hkd', 61: 'hnl', 62: 'hrk', 63: 'htg', 64: 'huf', 65: 'idr', 66: 'ils', 67: 'imp', 68: 'inr', 69: 'iqd', 70: 'irr', 71: 'isk', 72: 'jep', 73: 'jmd', 74: 'jod', 75: 'jpy', 76: 'kes', 77: 'kgs', 78: 'khr', 79: 'kmf', 80: 'kpw', 81: 'krw', 82: 'kwd', 83: 'kyd', 84: 'kzt', 85: 'lak', 86: 'lbp', 87: 'lkr', 88: 'lrd', 89: 'lsl', 90: 'ltl', 91: 'lvl', 92: 'lyd', 93: 'mad', 94: 'mdl', 95: 'mga', 96: 'mkd', 97: 'mmk', 98: 'mnt', 99: 'mop', 100: 'mro', 101: 'mur', 102: 'mvr', 103: 'mwk', 104: 'mxn', 105: 'myr', 106: 'mzn', 107: 'nad', 108: 'ngn', 109: 'nio', 110: 'nok', 111: 'npr', 112: 'nzd', 113: 'omr', 114: 'pab', 115: 'pen', 116: 'pgk', 117: 'php', 118: 'pkr', 119: 'pln', 120: 'pyg', 121: 'qar', 122: 'ron', 123: 'rsd', 124: 'rub', 125: 'rwf', 126: 'sar', 127: 'sbd', 128: 'scr', 129: 'sdg', 130: 'sek', 131: 'sgd', 132: 'shp', 133: 'sll', 134: 'sos', 135: 'srd', 136: 'std', 137: 'svc', 138: 'syp', 139: 'szl', 140: 'thb', 141: 'tjs', 142: 'tmt', 143: 'tnd', 144: 'top', 145: 'try', 146: 'ttd', 147: 'twd', 148: 'tzs', 149: 'uah', 150: 'ugx', 151: 'usd', 152: 'uyu', 153: 'uzs', 154: 'vef', 155: 'vnd', 156: 'vuv', 157: 'wst', 158: 'xaf', 159: 'xag', 160: 'xau', 161: 'xcd', 162: 'xdr', 163: 'xof', 164: 'xpf', 165: 'xrp', 166: 'yer', 167: 'zar', 168: 'zmk', 169: 'zmw', 170: 'zwl'}
-
-

JS-NG> fake.cur2id -
-{'aed': 1, 'afn': 2, 'all': 3, 'amd': 4, 'ang': 5, 'aoa': 6, 'ars': 7, 'aud': 8, 'awg': 9, 'azn': 10, 'bam': 11, 'bbd': -12, 'bdt': 13, 'bgn': 14, 'bhd': 15, 'bif': 16, 'bmd': 17, 'bnd': 18, 'bob': 19, 'brl': 20, 'bsd': 21, 'btc': 22, 'btn -': 23, 'bwp': 24, 'byn': 25, 'byr': 26, 'bzd': 27, 'cad': 28, 'cdf': 29, 'chf': 30, 'clf': 31, 'clp': 32, 'cny': 33, 'c -op': 34, 'crc': 35, 'cuc': 36, 'cup': 37, 'cve': 38, 'czk': 39, 'djf': 40, 'dkk': 41, 'dop': 42, 'dzd': 43, 'egp': 44, -'ern': 45, 'etb': 46, 'eth': 47, 'eur': 48, 'fjd': 49, 'fkp': 50, 'gbp': 51, 'gel': 52, 'ggp': 53, 'ghs': 54, 'gip': 55 -, 'gmd': 56, 'gnf': 57, 'gtq': 58, 'gyd': 59, 'hkd': 60, 'hnl': 61, 'hrk': 62, 'htg': 63, 'huf': 64, 'idr': 65, 'ils': 66, 'imp': 67, 'inr': 68, 'iqd': 69, 'irr': 70, 'isk': 71, 'jep': 72, 'jmd': 73, 'jod': 74, 'jpy': 75, 'kes': 76, 'kgs': 77, 'khr': 78, 'kmf': 79, 'kpw': 80, 'krw': 81, 'kwd': 82, 'kyd': 83, 'kzt': 84, 'lak': 85, 'lbp': 86, 'lkr': 87, 'lrd': 88, 'lsl': 89, 'ltl': 90, 'lvl': 91, 'lyd': 92, 'mad': 93, 'mdl': 94, 'mga': 95, 'mkd': 96, 'mmk': 97, 'mnt': 98, 'mop': 99, 'mro': 100, 'mur': 101, 'mvr': 102, 'mwk': 103, 'mxn': 104, 'myr': 105, 'mzn': 106, 'nad': 107, 'ngn': 108, 'nio': 109, 'nok': 110, 'npr': 111, 'nzd': 112, 'omr': 113, 'pab': 114, 'pen': 115, 'pgk': 116, 'php': 117, 'pkr': 118, 'pln': 119, 'pyg': 120, 'qar': 121, 'ron': 122, 'rsd': 123, 'rub': 124, 'rwf': 125, 'sar': 126, 'sbd': 127, 'scr': 128, 'sdg': 129, 'sek': 130, 'sgd': 131, 'shp': 132, 'sll': 133, 'sos': 134, 'srd': 135, 'std': 136, 'svc': 137, 'syp': 138, 'szl': 139, 'thb': 140, 'tjs': 141, 'tmt': 142, 'tnd': 143, 'top': 144, 'try': 145, 'ttd': 146, 'twd': 147, 'tzs': 148, 'uah': 149, 'ugx': 150, 'usd': 151, 'uyu': 152, 'uzs': 153, 'vef': 154, 'vnd': 155, 'vuv': 156, 'wst': 157, 'xaf': 158, 'xag': 159, 'xau': 160, 'xcd': 161, 'xdr': 162, 'xof': 163, 'xpf': 164, 'xrp': 165, 'yer': 166, 'zar': 167, 'zmk': 168, 'zmw': 169, 'zwl': 170}

-

JS-NG> -
-JS-NG> fake.api_key="VALID KEY" -
-JS-NG> j.clients.currencylayer.fake.load() -
-JS-NG> j.clients.currencylayer.fake.id2cur_print() -
-{1: 'aed', -2: 'afn', -3: 'all', -4: 'amd', -5: 'ang', -6: 'aoa', -7: 'ars', -8: 'aud', -9: 'awg', -10: 'azn', -11: 'bam', -12: 'bbd', -13: 'bdt', -14: 'bgn', -15: 'bhd', -16: 'bif', -17: 'bmd', -18: 'bnd', -19: 'bob', -20: 'brl', -21: 'bsd', -22: 'btc', -23: 'btn', -24: 'bwp', -25: 'byn', -26: 'byr', -27: 'bzd', -28: 'cad', -29: 'cdf', -30: 'chf', -31: 'clf', -32: 'clp', -33: 'cny', -34: 'cop', -35: 'crc', -36: 'cuc', -37: 'cup', -38: 'cve', -39: 'czk', -40: 'djf', -41: 'dkk', -42: 'dop', -43: 'dzd', -44: 'egp', -45: 'ern', -46: 'etb', -47: 'eth', -48: 'eur', -49: 'fjd', -50: 'fkp', -51: 'gbp', -52: 'gel', -53: 'ggp', -54: 'ghs', -55: 'gip', -56: 'gmd', -57: 'gnf', -58: 'gtq', -59: 'gyd', -60: 'hkd', -61: 'hnl', -62: 'hrk', -63: 'htg', -64: 'huf', -65: 'idr', -66: 'ils', -67: 'imp', -68: 'inr', -69: 'iqd', -70: 'irr', -71: 'isk', -72: 'jep', -73: 'jmd', -74: 'jod', -75: 'jpy', -76: 'kes', -77: 'kgs', -78: 'khr', -79: 'kmf', -80: 'kpw', -81: 'krw', -82: 'kwd', -83: 'kyd', -84: 'kzt', -85: 'lak', -86: 'lbp', -87: 'lkr', -88: 'lrd', -89: 'lsl', -90: 'ltl', -91: 'lvl', -92: 'lyd', -93: 'mad', -94: 'mdl', -95: 'mga', -96: 'mkd', -97: 'mmk', -98: 'mnt', -99: 'mop', -100: 'mro', -101: 'mur', -102: 'mvr', -103: 'mwk', -104: 'mxn', -105: 'myr', -106: 'mzn', -107: 'nad', -108: 'ngn', -109: 'nio', -110: 'nok', -111: 'npr', -112: 'nzd', -113: 'omr', -114: 'pab', -115: 'pen', -116: 'pgk', -117: 'php', -118: 'pkr', -119: 'pln', -120: 'pyg', -121: 'qar', -122: 'ron', -123: 'rsd', -124: 'rub', -125: 'rwf', -126: 'sar', -127: 'sbd', -128: 'scr', -129: 'sdg', -130: 'sek', -131: 'sgd', -132: 'shp', -133: 'sll', -134: 'sos', -135: 'srd', -136: 'std', -137: 'svc', -138: 'syp', -139: 'szl', -140: 'thb', -141: 'tjs', -142: 'tmt', -143: 'tnd', -144: 'top', -145: 'try', -146: 'ttd', -147: 'twd', -148: 'tzs', -149: 'uah', -150: 'ugx', -151: 'usd', -152: 'uyu', -153: 'uzs', -154: 'vef', -155: 'vnd', -156: 'vuv', -157: 'wst', -158: 'xaf', -159: 'xag', -160: 'xau', -161: 'xcd', -162: 'xdr', -163: 'xof', -164: 'xpf', -165: 'xrp', -166: 'yer', -167: 'zar', -168: 'zmk', -169: 'zmw', -170: 'zwl'} -JS-NG> j.clients.currencylayer.fake.cur2usd_print() -
-{'': 1, -'aed': 3.672979, -'afn': 78.296617, -'ah': 24.914996, -'all': 109.150047, -'amd': 476.210221, -'ang': 1.78525, -'aoa': 362.0025, -'ar': 3.75045, -'ars': 55.394992, -'aud': 1.474703, -'awg': 1.8, -'azn': 1.704964, -'bam': 1.758993, -'bbd': 2.0194, -'bd': 8.221403, -'bdt': 83.745499, -'bgn': 1.760801, -'bhd': 0.375961, -'bif': 1855, -'bmd': 1, -'bnd': 1.350696, -'bob': 6.86065, -'brl': 4.152695, -'bsd': 0.99205, -'btc': 9.948852946999476e-05, -'btn': 71.884502, -'bwp': 10.961999, -'byn': 2.060501, -'byr': 19600, -'bzd': 2.01595, -'cad': 1.32733, -'cdf': 1659.99946, -'chf': 0.978545, -'clf': 0.026094, -'clp': 720.00501, -'cny': 7.151304, -'cop': 3431.55, -'cr': 13.669974, -'crc': 567.080062, -'cuc': 1, -'cup': 26.5, -'cve': 98.749501, -'czk': 23.208988, -'egp': 16.53602, -'ek': 9.67235, -'ern': 14.999484, -'etb': 29.000284, -'eth': 0.005395489370885939, -'eur': 0.900035, -'fjd': 2.17495, -'fkp': 0.81691, -'g': 45.119039, -'gbp': 0.81752, -'gd': 1.38792, -'gel': 2.925034, -'ggp': 0.81764, -'ghs': 5.402501, -'gip': 0.81691, -'gmd': 50.415037, -'gnf': 9239.999966, -'gtq': 7.680957, -'gx': 3685.496424, -'gyd': 209.244968, -'hkd': 7.84595, -'hnl': 24.674984, -'hp': 1.320898, -'hrk': 6.653399, -'htg': 95.361503, -'huf': 296.280997, -'idr': 14258.25, -'ils': 3.52095, -'imp': 0.81764, -'inr': 71.792403, -'iqd': 1190, -'irr': 42104.999481, -'isk': 124.829491, -'jep': 0.81764, -'jf': 177.720165, -'jmd': 134.559965, -'jod': 0.7084, -'jpy': 106.015996, -'kes': 103.389937, -'kgs': 69.8159, -'khr': 4140.000279, -'kk': 6.71151, -'kmf': 443.249767, -'kpw': 900.052015, -'krw': 1214.824979, -'kwd': 0.303901, -'kyd': 0.83355, -'kzt': 383.110385, -'lak': 8735.000017, -'lbp': 1507.949729, -'lkr': 179.605474, -'ll': 9299.999946, -'lrd': 205.000232, -'lsl': 15.250149, -'ltl': 2.95274, -'lvl': 0.60489, -'lyd': 1.40503, -'mad': 9.5685, -'mdl': 17.887498, -'mga': 3674.999563, -'mkd': 55.324023, -'mmk': 1516.702673, -'mnt': 2669.391245, -'mop': 8.080496, -'mro': 357.000024, -'mur': 36.043506, -'mvr': 15.410297, -'mwk': 731.210149, -'mxn': 19.92145, -'myr': 4.198897, -'mzn': 61.020166, -'nad': 15.270055, -'ngn': 362.000148, -'nio': 33.602406, -'nok': 8.988065, -'npr': 115.010199, -'nzd': 1.56365, -'omr': 0.384976, -'op': 51.294983, -'os': 579.999893, -'pab': 0.99205, -'pen': 3.37635, -'pgk': 3.397801, -'php': 52.438012, -'pkr': 157.249855, -'pln': 3.92254, -'pyg': 6217.103241, -'qar': 3.64175, -'rd': 7.457963, -'ron': 4.256202, -'rsd': 106.069758, -'rub': 66.06102, -'rwf': 910, -'td': 21560.79, -'thb': 30.589849, -'tjs': 9.696302, -'tmt': 3.5, -'tnd': 2.857701, -'top': 2.320597, -'try': 5.81132, -'ttd': 6.71695, -'twd': 31.400972, -'tzs': 2298.149889, -'vc': 8.75195, -'vef': 9.987501, -'vnd': 23199, -'vuv': 117.90362, -'wst': 2.675215, -'xaf': 589.959986, -'xag': 0.056555, -'xau': 0.000653, -'xcd': 2.70245, -'xdr': 0.729108, -'xof': 584.499865, -'xpf': 106.950279, -'xrp': 3.771, -'yer': 250.349819, -'yp': 515.000236, -'yu': 36.34003, -'zar': 15.26498, -'zd': 119.879946, -'zl': 15.269489, -'zmk': 9001.202171, -'zmw': 13.112024, -'zs': 9376.306597, -'zwl': 322.000001}

-
-Source code -
"""
-JS-NG> fake = j.clients.currencylayer.new('fake')
-JS-NG> fake.cur2id_print()
-{'aed': 1,
- 'afn': 2,
- 'all': 3,
- 'amd': 4,
- 'ang': 5,
- 'aoa': 6,
- 'ars': 7,
- 'aud': 8,
- 'awg': 9,
- 'azn': 10,
- 'bam': 11,
- 'bbd': 12,
- 'bdt': 13,
- 'bgn': 14,
- 'bhd': 15,
- 'bif': 16,
- 'bmd': 17,
- 'bnd': 18,
- 'bob': 19,
- 'brl': 20,
- 'bsd': 21,
- 'btc': 22,
- 'btn': 23,
- 'bwp': 24,
- 'byn': 25,
- 'byr': 26,
- 'bzd': 27,
- 'cad': 28,
- 'cdf': 29,
- 'chf': 30,
- 'clf': 31,
- 'clp': 32,
- 'cny': 33,
- 'cop': 34,
- 'crc': 35,
- 'cuc': 36,
- 'cup': 37,
- 'cve': 38,
- 'czk': 39,
- 'djf': 40,
- 'dkk': 41,
- 'dop': 42,
- 'dzd': 43,
- 'egp': 44,
- 'ern': 45,
- 'etb': 46,
- 'eth': 47,
- 'eur': 48,
- 'fjd': 49,
- 'fkp': 50,
- 'gbp': 51,
- 'gel': 52,
- 'ggp': 53,
- 'ghs': 54,
- 'gip': 55,
- 'gmd': 56,
- 'gnf': 57,
- 'gtq': 58,
- 'gyd': 59,
- 'hkd': 60,
- 'hnl': 61,
- 'hrk': 62,
- 'htg': 63,
- 'huf': 64,
- 'idr': 65,
- 'ils': 66,
- 'imp': 67,
- 'inr': 68,
- 'iqd': 69,
- 'irr': 70,
- 'isk': 71,
- 'jep': 72,
- 'jmd': 73,
- 'jod': 74,
- 'jpy': 75,
- 'kes': 76,
- 'kgs': 77,
- 'khr': 78,
- 'kmf': 79,
- 'kpw': 80,
- 'krw': 81,
- 'kwd': 82,
- 'kyd': 83,
- 'kzt': 84,
- 'lak': 85,
- 'lbp': 86,
- 'lkr': 87,
- 'lrd': 88,
- 'lsl': 89,
- 'ltl': 90,
- 'lvl': 91,
- 'lyd': 92,
- 'mad': 93,
- 'mdl': 94,
- 'mga': 95,
- 'mkd': 96,
- 'mmk': 97,
- 'mnt': 98,
- 'mop': 99,
- 'mro': 100,
- 'mur': 101,
- 'mvr': 102,
- 'mwk': 103,
- 'mxn': 104,
- 'myr': 105,
- 'mzn': 106,
- 'nad': 107,
- 'ngn': 108,
- 'nio': 109,
- 'nok': 110,
- 'npr': 111,
- 'nzd': 112,
- 'omr': 113,
- 'pab': 114,
- 'pen': 115,
- 'pgk': 116,
- 'php': 117,
- 'pkr': 118,
- 'pln': 119,
- 'pyg': 120,
- 'qar': 121,
- 'ron': 122,
- 'rsd': 123,
- 'rub': 124,
- 'rwf': 125,
- 'sar': 126,
- 'sbd': 127,
- 'scr': 128,
- 'sdg': 129,
- 'sek': 130,
- 'sgd': 131,
- 'shp': 132,
- 'sll': 133,
- 'sos': 134,
- 'srd': 135,
- 'std': 136,
- 'svc': 137,
- 'syp': 138,
- 'szl': 139,
- 'thb': 140,
- 'tjs': 141,
- 'tmt': 142,
- 'tnd': 143,
- 'top': 144,
- 'try': 145,
- 'ttd': 146,
- 'twd': 147,
- 'tzs': 148,
- 'uah': 149,
- 'ugx': 150,
- 'usd': 151,
- 'uyu': 152,
- 'uzs': 153,
- 'vef': 154,
- 'vnd': 155,
- 'vuv': 156,
- 'wst': 157,
- 'xaf': 158,
- 'xag': 159,
- 'xau': 160,
- 'xcd': 161,
- 'xdr': 162,
- 'xof': 163,
- 'xpf': 164,
- 'xrp': 165,
- 'yer': 166,
- 'zar': 167,
- 'zmk': 168,
- 'zmw': 169,
- 'zwl': 170}
-JS-NG> fake.id2cur_print()
-{1: 'aed',
- 2: 'afn',
- 3: 'all',
- 4: 'amd',
- 5: 'ang',
- 6: 'aoa',
- 7: 'ars',
- 8: 'aud',
- 9: 'awg',
- 10: 'azn',
- 11: 'bam',
- 12: 'bbd',
- 13: 'bdt',
- 14: 'bgn',
- 15: 'bhd',
- 16: 'bif',
- 17: 'bmd',
- 18: 'bnd',
- 19: 'bob',
- 20: 'brl',
- 21: 'bsd',
- 22: 'btc',
- 23: 'btn',
- 24: 'bwp',
- 25: 'byn',
- 26: 'byr',
- 27: 'bzd',
- 28: 'cad',
- 29: 'cdf',
- 30: 'chf',
- 31: 'clf',
- 32: 'clp',
- 33: 'cny',
- 34: 'cop',
- 35: 'crc',
- 36: 'cuc',
- 37: 'cup',
- 38: 'cve',
- 39: 'czk',
- 40: 'djf',
- 41: 'dkk',
- 42: 'dop',
- 43: 'dzd',
- 44: 'egp',
- 45: 'ern',
- 46: 'etb',
- 47: 'eth',
- 48: 'eur',
- 49: 'fjd',
- 50: 'fkp',
- 51: 'gbp',
- 52: 'gel',
- 53: 'ggp',
- 54: 'ghs',
- 55: 'gip',
- 56: 'gmd',
- 57: 'gnf',
- 58: 'gtq',
- 59: 'gyd',
- 60: 'hkd',
- 61: 'hnl',
- 62: 'hrk',
- 63: 'htg',
- 64: 'huf',
- 65: 'idr',
- 66: 'ils',
- 67: 'imp',
- 68: 'inr',
- 69: 'iqd',
- 70: 'irr',
- 71: 'isk',
- 72: 'jep',
- 73: 'jmd',
- 74: 'jod',
- 75: 'jpy',
- 76: 'kes',
- 77: 'kgs',
- 78: 'khr',
- 79: 'kmf',
- 80: 'kpw',
- 81: 'krw',
- 82: 'kwd',
- 83: 'kyd',
- 84: 'kzt',
- 85: 'lak',
- 86: 'lbp',
- 87: 'lkr',
- 88: 'lrd',
- 89: 'lsl',
- 90: 'ltl',
- 91: 'lvl',
- 92: 'lyd',
- 93: 'mad',
- 94: 'mdl',
- 95: 'mga',
- 96: 'mkd',
- 97: 'mmk',
- 98: 'mnt',
- 99: 'mop',
- 100: 'mro',
- 101: 'mur',
- 102: 'mvr',
- 103: 'mwk',
- 104: 'mxn',
- 105: 'myr',
- 106: 'mzn',
- 107: 'nad',
- 108: 'ngn',
- 109: 'nio',
- 110: 'nok',
- 111: 'npr',
- 112: 'nzd',
- 113: 'omr',
- 114: 'pab',
- 115: 'pen',
- 116: 'pgk',
- 117: 'php',
- 118: 'pkr',
- 119: 'pln',
- 120: 'pyg',
- 121: 'qar',
- 122: 'ron',
- 123: 'rsd',
- 124: 'rub',
- 125: 'rwf',
- 126: 'sar',
- 127: 'sbd',
- 128: 'scr',
- 129: 'sdg',
- 130: 'sek',
- 131: 'sgd',
- 132: 'shp',
- 133: 'sll',
- 134: 'sos',
- 135: 'srd',
- 136: 'std',
- 137: 'svc',
- 138: 'syp',
- 139: 'szl',
- 140: 'thb',
- 141: 'tjs',
- 142: 'tmt',
- 143: 'tnd',
- 144: 'top',
- 145: 'try',
- 146: 'ttd',
- 147: 'twd',
- 148: 'tzs',
- 149: 'uah',
- 150: 'ugx',
- 151: 'usd',
- 152: 'uyu',
- 153: 'uzs',
- 154: 'vef',
- 155: 'vnd',
- 156: 'vuv',
- 157: 'wst',
- 158: 'xaf',
- 159: 'xag',
- 160: 'xau',
- 161: 'xcd',
- 162: 'xdr',
- 163: 'xof',
- 164: 'xpf',
- 165: 'xrp',
- 166: 'yer',
- 167: 'zar',
- 168: 'zmk',
- 169: 'zmw',
- 170: 'zwl'}
-JS-NG> fake.id2cur
-{1: 'aed', 2: 'afn', 3: 'all', 4: 'amd', 5: 'ang', 6: 'aoa', 7: 'ars', 8: 'aud', 9: 'awg', 10: 'azn', 11: 'bam', 12: 'b
-bd', 13: 'bdt', 14: 'bgn', 15: 'bhd', 16: 'bif', 17: 'bmd', 18: 'bnd', 19: 'bob', 20: 'brl', 21: 'bsd', 22: 'btc', 23:
-'btn', 24: 'bwp', 25: 'byn', 26: 'byr', 27: 'bzd', 28: 'cad', 29: 'cdf', 30: 'chf', 31: 'clf', 32: 'clp', 33: 'cny', 34
-: 'cop', 35: 'crc', 36: 'cuc', 37: 'cup', 38: 'cve', 39: 'czk', 40: 'djf', 41: 'dkk', 42: 'dop', 43: 'dzd', 44: 'egp',
-45: 'ern', 46: 'etb', 47: 'eth', 48: 'eur', 49: 'fjd', 50: 'fkp', 51: 'gbp', 52: 'gel', 53: 'ggp', 54: 'ghs', 55: 'gip'
-, 56: 'gmd', 57: 'gnf', 58: 'gtq', 59: 'gyd', 60: 'hkd', 61: 'hnl', 62: 'hrk', 63: 'htg', 64: 'huf', 65: 'idr', 66: 'ils', 67: 'imp', 68: 'inr', 69: 'iqd', 70: 'irr', 71: 'isk', 72: 'jep', 73: 'jmd', 74: 'jod', 75: 'jpy', 76: 'kes', 77: 'kgs', 78: 'khr', 79: 'kmf', 80: 'kpw', 81: 'krw', 82: 'kwd', 83: 'kyd', 84: 'kzt', 85: 'lak', 86: 'lbp', 87: 'lkr', 88: 'lrd', 89: 'lsl', 90: 'ltl', 91: 'lvl', 92: 'lyd', 93: 'mad', 94: 'mdl', 95: 'mga', 96: 'mkd', 97: 'mmk', 98: 'mnt', 99: 'mop', 100: 'mro', 101: 'mur', 102: 'mvr', 103: 'mwk', 104: 'mxn', 105: 'myr', 106: 'mzn', 107: 'nad', 108: 'ngn', 109: 'nio', 110: 'nok', 111: 'npr', 112: 'nzd', 113: 'omr', 114: 'pab', 115: 'pen', 116: 'pgk', 117: 'php', 118: 'pkr', 119: 'pln', 120: 'pyg', 121: 'qar', 122: 'ron', 123: 'rsd', 124: 'rub', 125: 'rwf', 126: 'sar', 127: 'sbd', 128: 'scr', 129: 'sdg', 130: 'sek', 131: 'sgd', 132: 'shp', 133: 'sll', 134: 'sos', 135: 'srd', 136: 'std', 137: 'svc', 138: 'syp', 139: 'szl', 140: 'thb', 141: 'tjs', 142: 'tmt', 143: 'tnd', 144: 'top', 145: 'try', 146: 'ttd', 147: 'twd', 148: 'tzs', 149: 'uah', 150: 'ugx', 151: 'usd', 152: 'uyu', 153: 'uzs', 154: 'vef', 155: 'vnd', 156: 'vuv', 157: 'wst', 158: 'xaf', 159: 'xag', 160: 'xau', 161: 'xcd', 162: 'xdr', 163: 'xof', 164: 'xpf', 165: 'xrp', 166: 'yer', 167: 'zar', 168: 'zmk', 169: 'zmw', 170: 'zwl'}
-
-JS-NG> fake.cur2id
-{'aed': 1, 'afn': 2, 'all': 3, 'amd': 4, 'ang': 5, 'aoa': 6, 'ars': 7, 'aud': 8, 'awg': 9, 'azn': 10, 'bam': 11, 'bbd':
- 12, 'bdt': 13, 'bgn': 14, 'bhd': 15, 'bif': 16, 'bmd': 17, 'bnd': 18, 'bob': 19, 'brl': 20, 'bsd': 21, 'btc': 22, 'btn
-': 23, 'bwp': 24, 'byn': 25, 'byr': 26, 'bzd': 27, 'cad': 28, 'cdf': 29, 'chf': 30, 'clf': 31, 'clp': 32, 'cny': 33, 'c
-op': 34, 'crc': 35, 'cuc': 36, 'cup': 37, 'cve': 38, 'czk': 39, 'djf': 40, 'dkk': 41, 'dop': 42, 'dzd': 43, 'egp': 44,
-'ern': 45, 'etb': 46, 'eth': 47, 'eur': 48, 'fjd': 49, 'fkp': 50, 'gbp': 51, 'gel': 52, 'ggp': 53, 'ghs': 54, 'gip': 55
-, 'gmd': 56, 'gnf': 57, 'gtq': 58, 'gyd': 59, 'hkd': 60, 'hnl': 61, 'hrk': 62, 'htg': 63, 'huf': 64, 'idr': 65, 'ils': 66, 'imp': 67, 'inr': 68, 'iqd': 69, 'irr': 70, 'isk': 71, 'jep': 72, 'jmd': 73, 'jod': 74, 'jpy': 75, 'kes': 76, 'kgs': 77, 'khr': 78, 'kmf': 79, 'kpw': 80, 'krw': 81, 'kwd': 82, 'kyd': 83, 'kzt': 84, 'lak': 85, 'lbp': 86, 'lkr': 87, 'lrd': 88, 'lsl': 89, 'ltl': 90, 'lvl': 91, 'lyd': 92, 'mad': 93, 'mdl': 94, 'mga': 95, 'mkd': 96, 'mmk': 97, 'mnt': 98, 'mop': 99, 'mro': 100, 'mur': 101, 'mvr': 102, 'mwk': 103, 'mxn': 104, 'myr': 105, 'mzn': 106, 'nad': 107, 'ngn': 108, 'nio': 109, 'nok': 110, 'npr': 111, 'nzd': 112, 'omr': 113, 'pab': 114, 'pen': 115, 'pgk': 116, 'php': 117, 'pkr': 118, 'pln': 119, 'pyg': 120, 'qar': 121, 'ron': 122, 'rsd': 123, 'rub': 124, 'rwf': 125, 'sar': 126, 'sbd': 127, 'scr': 128, 'sdg': 129, 'sek': 130, 'sgd': 131, 'shp': 132, 'sll': 133, 'sos': 134, 'srd': 135, 'std': 136, 'svc': 137, 'syp': 138, 'szl': 139, 'thb': 140, 'tjs': 141, 'tmt': 142, 'tnd': 143, 'top': 144, 'try': 145, 'ttd': 146, 'twd': 147, 'tzs': 148, 'uah': 149, 'ugx': 150, 'usd': 151, 'uyu': 152, 'uzs': 153, 'vef': 154, 'vnd': 155, 'vuv': 156, 'wst': 157, 'xaf': 158, 'xag': 159, 'xau': 160, 'xcd': 161, 'xdr': 162, 'xof': 163, 'xpf': 164, 'xrp': 165, 'yer': 166, 'zar': 167, 'zmk': 168, 'zmw': 169, 'zwl': 170}
-
-JS-NG>
-JS-NG> fake.api_key="VALID KEY"
-JS-NG> j.clients.currencylayer.fake.load()
-JS-NG> j.clients.currencylayer.fake.id2cur_print()
-{1: 'aed',
- 2: 'afn',
- 3: 'all',
- 4: 'amd',
- 5: 'ang',
- 6: 'aoa',
- 7: 'ars',
- 8: 'aud',
- 9: 'awg',
- 10: 'azn',
- 11: 'bam',
- 12: 'bbd',
- 13: 'bdt',
- 14: 'bgn',
- 15: 'bhd',
- 16: 'bif',
- 17: 'bmd',
- 18: 'bnd',
- 19: 'bob',
- 20: 'brl',
- 21: 'bsd',
- 22: 'btc',
- 23: 'btn',
- 24: 'bwp',
- 25: 'byn',
- 26: 'byr',
- 27: 'bzd',
- 28: 'cad',
- 29: 'cdf',
- 30: 'chf',
- 31: 'clf',
- 32: 'clp',
- 33: 'cny',
- 34: 'cop',
- 35: 'crc',
- 36: 'cuc',
- 37: 'cup',
- 38: 'cve',
- 39: 'czk',
- 40: 'djf',
- 41: 'dkk',
- 42: 'dop',
- 43: 'dzd',
- 44: 'egp',
- 45: 'ern',
- 46: 'etb',
- 47: 'eth',
- 48: 'eur',
- 49: 'fjd',
- 50: 'fkp',
- 51: 'gbp',
- 52: 'gel',
- 53: 'ggp',
- 54: 'ghs',
- 55: 'gip',
- 56: 'gmd',
- 57: 'gnf',
- 58: 'gtq',
- 59: 'gyd',
- 60: 'hkd',
- 61: 'hnl',
- 62: 'hrk',
- 63: 'htg',
- 64: 'huf',
- 65: 'idr',
- 66: 'ils',
- 67: 'imp',
- 68: 'inr',
- 69: 'iqd',
- 70: 'irr',
- 71: 'isk',
- 72: 'jep',
- 73: 'jmd',
- 74: 'jod',
- 75: 'jpy',
- 76: 'kes',
- 77: 'kgs',
- 78: 'khr',
- 79: 'kmf',
- 80: 'kpw',
- 81: 'krw',
- 82: 'kwd',
- 83: 'kyd',
- 84: 'kzt',
- 85: 'lak',
- 86: 'lbp',
- 87: 'lkr',
- 88: 'lrd',
- 89: 'lsl',
- 90: 'ltl',
- 91: 'lvl',
- 92: 'lyd',
- 93: 'mad',
- 94: 'mdl',
- 95: 'mga',
- 96: 'mkd',
- 97: 'mmk',
- 98: 'mnt',
- 99: 'mop',
- 100: 'mro',
- 101: 'mur',
- 102: 'mvr',
- 103: 'mwk',
- 104: 'mxn',
- 105: 'myr',
- 106: 'mzn',
- 107: 'nad',
- 108: 'ngn',
- 109: 'nio',
- 110: 'nok',
- 111: 'npr',
- 112: 'nzd',
- 113: 'omr',
- 114: 'pab',
- 115: 'pen',
- 116: 'pgk',
- 117: 'php',
- 118: 'pkr',
- 119: 'pln',
- 120: 'pyg',
- 121: 'qar',
- 122: 'ron',
- 123: 'rsd',
- 124: 'rub',
- 125: 'rwf',
- 126: 'sar',
- 127: 'sbd',
- 128: 'scr',
- 129: 'sdg',
- 130: 'sek',
- 131: 'sgd',
- 132: 'shp',
- 133: 'sll',
- 134: 'sos',
- 135: 'srd',
- 136: 'std',
- 137: 'svc',
- 138: 'syp',
- 139: 'szl',
- 140: 'thb',
- 141: 'tjs',
- 142: 'tmt',
- 143: 'tnd',
- 144: 'top',
- 145: 'try',
- 146: 'ttd',
- 147: 'twd',
- 148: 'tzs',
- 149: 'uah',
- 150: 'ugx',
- 151: 'usd',
- 152: 'uyu',
- 153: 'uzs',
- 154: 'vef',
- 155: 'vnd',
- 156: 'vuv',
- 157: 'wst',
- 158: 'xaf',
- 159: 'xag',
- 160: 'xau',
- 161: 'xcd',
- 162: 'xdr',
- 163: 'xof',
- 164: 'xpf',
- 165: 'xrp',
- 166: 'yer',
- 167: 'zar',
- 168: 'zmk',
- 169: 'zmw',
- 170: 'zwl'}
-JS-NG> j.clients.currencylayer.fake.cur2usd_print()
-{'': 1,
- 'aed': 3.672979,
- 'afn': 78.296617,
- 'ah': 24.914996,
- 'all': 109.150047,
- 'amd': 476.210221,
- 'ang': 1.78525,
- 'aoa': 362.0025,
- 'ar': 3.75045,
- 'ars': 55.394992,
- 'aud': 1.474703,
- 'awg': 1.8,
- 'azn': 1.704964,
- 'bam': 1.758993,
- 'bbd': 2.0194,
- 'bd': 8.221403,
- 'bdt': 83.745499,
- 'bgn': 1.760801,
- 'bhd': 0.375961,
- 'bif': 1855,
- 'bmd': 1,
- 'bnd': 1.350696,
- 'bob': 6.86065,
- 'brl': 4.152695,
- 'bsd': 0.99205,
- 'btc': 9.948852946999476e-05,
- 'btn': 71.884502,
- 'bwp': 10.961999,
- 'byn': 2.060501,
- 'byr': 19600,
- 'bzd': 2.01595,
- 'cad': 1.32733,
- 'cdf': 1659.99946,
- 'chf': 0.978545,
- 'clf': 0.026094,
- 'clp': 720.00501,
- 'cny': 7.151304,
- 'cop': 3431.55,
- 'cr': 13.669974,
- 'crc': 567.080062,
- 'cuc': 1,
- 'cup': 26.5,
- 'cve': 98.749501,
- 'czk': 23.208988,
- 'egp': 16.53602,
- 'ek': 9.67235,
- 'ern': 14.999484,
- 'etb': 29.000284,
- 'eth': 0.005395489370885939,
- 'eur': 0.900035,
- 'fjd': 2.17495,
- 'fkp': 0.81691,
- 'g': 45.119039,
- 'gbp': 0.81752,
- 'gd': 1.38792,
- 'gel': 2.925034,
- 'ggp': 0.81764,
- 'ghs': 5.402501,
- 'gip': 0.81691,
- 'gmd': 50.415037,
- 'gnf': 9239.999966,
- 'gtq': 7.680957,
- 'gx': 3685.496424,
- 'gyd': 209.244968,
- 'hkd': 7.84595,
- 'hnl': 24.674984,
- 'hp': 1.320898,
- 'hrk': 6.653399,
- 'htg': 95.361503,
- 'huf': 296.280997,
- 'idr': 14258.25,
- 'ils': 3.52095,
- 'imp': 0.81764,
- 'inr': 71.792403,
- 'iqd': 1190,
- 'irr': 42104.999481,
- 'isk': 124.829491,
- 'jep': 0.81764,
- 'jf': 177.720165,
- 'jmd': 134.559965,
- 'jod': 0.7084,
- 'jpy': 106.015996,
- 'kes': 103.389937,
- 'kgs': 69.8159,
- 'khr': 4140.000279,
- 'kk': 6.71151,
- 'kmf': 443.249767,
- 'kpw': 900.052015,
- 'krw': 1214.824979,
- 'kwd': 0.303901,
- 'kyd': 0.83355,
- 'kzt': 383.110385,
- 'lak': 8735.000017,
- 'lbp': 1507.949729,
- 'lkr': 179.605474,
- 'll': 9299.999946,
- 'lrd': 205.000232,
- 'lsl': 15.250149,
- 'ltl': 2.95274,
- 'lvl': 0.60489,
- 'lyd': 1.40503,
- 'mad': 9.5685,
- 'mdl': 17.887498,
- 'mga': 3674.999563,
- 'mkd': 55.324023,
- 'mmk': 1516.702673,
- 'mnt': 2669.391245,
- 'mop': 8.080496,
- 'mro': 357.000024,
- 'mur': 36.043506,
- 'mvr': 15.410297,
- 'mwk': 731.210149,
- 'mxn': 19.92145,
- 'myr': 4.198897,
- 'mzn': 61.020166,
- 'nad': 15.270055,
- 'ngn': 362.000148,
- 'nio': 33.602406,
- 'nok': 8.988065,
- 'npr': 115.010199,
- 'nzd': 1.56365,
- 'omr': 0.384976,
- 'op': 51.294983,
- 'os': 579.999893,
- 'pab': 0.99205,
- 'pen': 3.37635,
- 'pgk': 3.397801,
- 'php': 52.438012,
- 'pkr': 157.249855,
- 'pln': 3.92254,
- 'pyg': 6217.103241,
- 'qar': 3.64175,
- 'rd': 7.457963,
- 'ron': 4.256202,
- 'rsd': 106.069758,
- 'rub': 66.06102,
- 'rwf': 910,
- 'td': 21560.79,
- 'thb': 30.589849,
- 'tjs': 9.696302,
- 'tmt': 3.5,
- 'tnd': 2.857701,
- 'top': 2.320597,
- 'try': 5.81132,
- 'ttd': 6.71695,
- 'twd': 31.400972,
- 'tzs': 2298.149889,
- 'vc': 8.75195,
- 'vef': 9.987501,
- 'vnd': 23199,
- 'vuv': 117.90362,
- 'wst': 2.675215,
- 'xaf': 589.959986,
- 'xag': 0.056555,
- 'xau': 0.000653,
- 'xcd': 2.70245,
- 'xdr': 0.729108,
- 'xof': 584.499865,
- 'xpf': 106.950279,
- 'xrp': 3.771,
- 'yer': 250.349819,
- 'yp': 515.000236,
- 'yu': 36.34003,
- 'zar': 15.26498,
- 'zd': 119.879946,
- 'zl': 15.269489,
- 'zmk': 9001.202171,
- 'zmw': 13.112024,
- 'zs': 9376.306597,
- 'zwl': 322.000001}
-
-
-"""
-
-
-def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .currencylayer import CurrencyLayerClient
-    return StoredFactory(CurrencyLayerClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.currencylayer.currencies
-
-
-
-
jumpscale.clients.currencylayer.currencylayer
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .currencylayer import CurrencyLayerClient
-    return StoredFactory(CurrencyLayerClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/digitalocean/digitalocean.html b/docs/api/jumpscale/clients/digitalocean/digitalocean.html deleted file mode 100644 index d49353961..000000000 --- a/docs/api/jumpscale/clients/digitalocean/digitalocean.html +++ /dev/null @@ -1,2822 +0,0 @@ - - - - - - -jumpscale.clients.digitalocean.digitalocean API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.digitalocean.digitalocean

-
-
-

This module is used to manage your digital ocean account, create droplet,list all the droplets, destroy droplets, create project, list all the projects and delete project

-

prerequisites

-
## Sshkey client and loaded with you public key
-
-

'''python -ssh = j.clients.sshkey.get(name= "test") -ssh.private_key_path = "/home/rafy/.ssh/id_rsa" -ssh.load_from_file_system() -'''

-

Create Digital Ocean client and set your token and load your sshkey

-
dg = j.clients.digitalocean.get("testDG")
-dg.token_ = ""
-
-

Set sshclient you have created

-
dg.set_default_sshkey(ssh)
-
-

Use Digital Ocean client

-

Create and deploy Project to Digital Ocean

-

Create Project (name must not contian spaces or start with number)

-
 project = dg.projects.new("test_DG_client")
-
-

Set the name you want to deploy with on Digital Ocean

-
project.set_digital_ocean_name("test project DO client")
-
-

Deploy the project (you have to specific the purpose)

-
project.deploy(purpose="testing digital ocean client")
-
-

Delete the project from Digital Ocean

-
project.delete_remote()
-
-

Create and deploy Droplet to Digital Ocean

-

Create Droplet (name must not contian spaces or start with number)

-
droplet = dg.droplets.new("test_droplet_dg")
-
-

Set the name you want to deploy with on Digital Ocean

-
droplet.set_digital_ocean_name("droplet-test-DO")
-
-

Deploy the Droplet

-
droplet.deploy()
-
-

Delete the Droplet from Digital Ocean

-
droplet.delete_remote()
-
-

Get digital ocean regions

-
dg.regions
-
-

Get digital ocean images

-
dg.images
-
-

In the below examples, I have supposed that you followed the above steps -and you got digital ocean client with the name (dg)

-
-Source code -
"""This module is used to manage your digital ocean account, create droplet,list all the droplets, destroy droplets, create project, list all the projects and delete project
-# prerequisites
-    ## Sshkey client and loaded with you public key
-'''python
-ssh = j.clients.sshkey.get(name= "test")
-ssh.private_key_path = "/home/rafy/.ssh/id_rsa"
-ssh.load_from_file_system()
-'''
-## Create Digital Ocean client and set your token and load your sshkey
-```python
-dg = j.clients.digitalocean.get("testDG")
-dg.token_ = ""
-```
-## Set sshclient you have created
-``` python
-dg.set_default_sshkey(ssh)
-```
-## Use Digital Ocean client
-
-### Create and deploy Project to Digital Ocean
-
-#### Create Project (name must not contian spaces or start with number)
-``` python
- project = dg.projects.new("test_DG_client")
-```
-#### Set the name you want to deploy with on Digital Ocean
-``` python
-project.set_digital_ocean_name("test project DO client")
-```
-#### Deploy the project (you have to specific the purpose)
-``` python
-project.deploy(purpose="testing digital ocean client")
-```
-#### Delete the project from Digital Ocean
-``` python
-project.delete_remote()
-```
-
-### Create and deploy Droplet to Digital Ocean
-
-#### Create Droplet (name must not contian spaces or start with number)
-``` python
-droplet = dg.droplets.new("test_droplet_dg")
-```
-#### Set the name you want to deploy with on Digital Ocean
-``` python
-droplet.set_digital_ocean_name("droplet-test-DO")
-```
-#### Deploy the Droplet
-```python
-droplet.deploy()
-```
-#### Delete the Droplet from Digital Ocean
-```python
-droplet.delete_remote()
-```
-
-### Get digital ocean regions
-```python
-dg.regions
-```
-
-### Get digital ocean images
-```python
-dg.images
-```
-
-In the below examples, I have supposed that you followed the above steps
-and you got digital ocean client with the name (dg)
-"""
-
-from jumpscale.loader import j
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-from jumpscale.core.base import StoredFactory
-from .project import ProjectManagement
-import digitalocean
-
-
-class ProjectFactory(StoredFactory):
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def list_remote(self):
-        """
-        Returns list of projects on Digital Ocean
-
-        e.g
-            dg.projects.list_remote()  -> list of projects
-
-        Returns
-            list(projects): list of projects on digital ocean
-
-        """
-        return ProjectManagement.list(self.parent_instance.client)
-
-    def check_project_exist_remote(self, name):
-        """
-        Check a project with specific name exits on Digital Ocean
-
-        e.g
-            dg.projects.check_project_exist_remote("codescalers")  -> True
-            dg.projects.check_project_exist_remote("dsrfjsdfjl")  -> False
-
-        Args
-            name (str): name of the project
-
-        Returns
-            bool : True if the project exits and False if the project does not exist on digital ocean
-        """
-        for project in self.list_remote():
-            if project.name == name:
-                return True
-        return False
-
-    def get_project_exist_remote(self, name):
-        """
-        Get a project with specifc name from  Digital Ocean.
-
-        e.g
-            dg.projects.get_project_exist_remote("codescalers")  -> project
-
-        Args
-            name (str): name of the project
-
-        Returns
-            Project : a project from digital ocean with the name specified
-        """
-        for project in self.list_remote():
-            if project.name == name:
-                return project
-        raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-
-class Project(Client):
-    do_name = fields.String()
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def set_digital_ocean_name(self, name):
-        """Set a name for your project to be used on Digital Ocean
-        e.g
-            project.set_digital_ocean_name("test project DO client")
-
-        Args:
-            name (str): name to be used on digital ocean
-        """
-        self.do_name = name
-
-    def get_digital_ocean_name(self):
-        """Get a name for the project which is used on digital ocean
-        e.g
-            project.get_digital_ocean_name()  ->  "test project DO client"
-
-        Returns:
-            str: name for the project which is used on digital ocean
-        """
-        return self.do_name
-
-    def deploy(self, purpose, description="", environment="", is_default=False):
-        """Create a digital ocean project
-        e.g
-            project.deploy(purpose="testing digital ocean client")  -> project
-        Args:
-            purpose(str): purpose of the project (not optional)
-            description(str): description of the project, defaults to ""
-            environment(str): environment of project's resources, defaults to ""
-            is_default(bool): make this the default project for your user
-
-        Returns:
-            project: The project object that has been created
-        """
-
-        if self.parent.projects.check_project_exist_remote(self.do_name):
-            raise j.exceptions.Value("A project with the same name already exists")
-
-        project = ProjectManagement(
-            token=self.parent.projects.parent_instance.token_,
-            name=self.do_name,
-            purpose=purpose,
-            description=description,
-            environment=environment,
-            is_default=is_default,
-        )
-        project.create()
-
-        if is_default:
-            project.update(is_default=True)
-
-        return project
-
-    def delete_remote(self):
-        """Delete the project from Digital Ocean (A project can't be deleted unless it has no resources.)
-
-        e.g
-            project.delete_remote()
-        """
-        project = self.parent.projects.get_project_exist_remote(self.do_name)
-        project.delete()
-
-
-class DropletFactory(StoredFactory):
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def list_remote(self, project_name=None):
-        """
-        List all remote droplet or list droplets for a project if it is specified
-
-        e.g
-            dg.droplets.list_remote()  -> list of droplets
-            dg.droplets.list_remote("codescalers")  -> list of droplets on codescalers project
-
-        Args:
-            project_name (str) : name of project on digital ocean (optional)
-
-        Returns
-            list (Droplet) : list of droplets on digital ocean
-
-
-        """
-        if project_name:
-            project = self.parent_instance.projects.get_project_exist_remote(project_name)
-            return project.list_droplets()
-
-        return self.parent_instance.client.get_all_droplets()
-
-    def check_droplet_exist_remote(self, name):
-        """
-        Check droplet exists on digital ocean
-
-        e.g
-            dg.droplets.check_droplet_exist_remote("3git")  -> True
-            dg.droplets.check_droplet_exist_remote("sdfgdfed")  -> False
-
-        Args:
-            name (str) : name of droplet
-
-        Returns
-            bool : True if the droplet exist or False if the droplet does not exist
-        """
-        for droplet in self.list_remote():
-            if droplet.name.lower() == name.lower():
-                return True
-        return False
-
-    def get_droplet_exist_remote(self, name):
-        """
-        Get Droplet exists from Digital Ocean
-
-        e.g
-            dg.droplets.get_droplet_exist_remote("3git")
-
-        Args:
-            name (str) : name of droplet
-
-        Returns
-            droplet : droplet with the name specified
-
-        """
-        for droplet in self.list_remote():
-            if droplet.name.lower() == name.lower():
-                return droplet
-        raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-    def shutdown_all(self, project_name=None):
-        """
-        Shutdown all the droplets or droplets in specific project
-
-        e.g
-            dg.droplets.shutdown_all("codescalers")
-            dg.droplets.shutdown_all()
-
-        Args:
-            name (str) : name of the project
-
-        """
-        for droplet in self.list_remote(project_name):
-            droplet.shutdown()
-
-    def delete_all(self, ignore=None, interactive=True, project_name=None):
-        """
-        Delete all the droplets or delete all the droplets in specific project
-
-        e.g
-            dg.droplets.delete_all(project_name = "codescalers")
-            dg.droplets.delete_all()
-
-        Args:
-            project_name (str) : name of the project
-            ignore (list): list of ignored droplets to prevent their deletion
-            interactive (bool): if True the deletion will be interactive and
-                                confirm if you want to delete but if False it
-                                will delete directly
-        """
-        if not ignore:
-            ignore = []
-
-        def test(ignore, name):
-            if name.startswith("TF-"):
-                return False
-            for item in ignore:
-                if name.lower().find(item.lower()) != -1:
-                    return False
-            return True
-
-        todo = []
-        for droplet in self.list_remote(project_name):
-            if test(ignore, droplet.name):
-                todo.append(droplet)
-        if todo != []:
-            todotxt = ",".join([i.name for i in todo])
-            if not interactive or j.tools.console.ask_yes_no("ok to delete:%s" % todotxt):
-                for droplet in todo:
-                    droplet.destroy()
-
-
-class Droplet(Client):
-    do_name = fields.String()
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def set_digital_ocean_name(self, name):
-        """Set a name for your Droplet to be used on Digital Ocean
-
-        e.g
-            droplet.set_digital_ocean_name("test-name")
-
-        Args:
-            name (str): name to be used on digital ocean
-        """
-        self.do_name = name
-
-    def get_digital_ocean_name(self):
-        """Get a name for the Droplet which is used on digital ocean
-
-        e.g
-            droplet.get_digital_ocean_name()  ->  "test-name"
-
-        Returns
-            str: name for the droplet which is used on digital ocean
-        """
-        return self.do_name
-
-    def deploy(
-        self,
-        sshkey=None,
-        region="Amsterdam 3",
-        image="ubuntu 18.04",
-        size_slug="s-1vcpu-2gb",
-        delete=True,
-        project_name=None,
-    ):
-        """
-        Deploy your Droplet to Digital Ocean
-
-        Args
-            sshkey (string): sshkey name used on digital ocean (if not set it will use the default one which already loaded)
-            region (string): region name to deploy to
-            image (string): Image name to be used
-            size_slug (string): size of the droplet  (s-1vcpu-2gb,s-6vcpu-16gb,gd-8vcpu-32gb)
-            delete (bool): delete the droplet if it is already deployed on digital ocean
-            project_name (string): project to add this droplet it. If not specified the default project will be used.
-
-        """
-        project = None
-        if project_name:
-            project = self.parent.projects.get_project_exist_remote(self.do_name)
-            if not project:
-                raise j.exceptions.Input("could not find project with name:%s" % project_name)
-
-        # Get ssh
-        if not sshkey:
-            sshkey_do = self.parent.get_default_sshkey()
-
-            if not sshkey_do:
-                # means we did not find the sshkey on digital ocean yet, need to create
-                sshkey = self.parent.sshkey
-                key = digitalocean.SSHKey(
-                    token=self.parent.projects.parent_instance.token_, name=sshkey.name, public_key=sshkey.public_key
-                )
-                key.create()
-            sshkey_do = self.parent.get_default_sshkey()
-            assert sshkey_do
-            sshkey = sshkey_do.name
-
-        if self.parent.droplets.check_droplet_exist_remote(self.do_name):
-            dr0 = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-            if delete:
-                dr0.destroy()
-            else:
-                sshcl = j.clients.sshclient.get(name="do_%s" % self.do_name, host=dr0.ip_address, sshkey=sshkey)
-                return dr0, sshcl
-
-        sshkey = self.parent.droplets.parent_instance.get_sshkey(sshkey)
-        region = self.parent.droplets.parent_instance.get_region(region)
-        imagedo = self.parent.droplets.parent_instance.get_image(image)
-
-        img_slug_or_id = imagedo.slug if imagedo.slug else imagedo.id
-
-        droplet = digitalocean.Droplet(
-            token=self.parent.droplets.parent_instance.token_,
-            name=self.do_name,
-            region=region.slug,
-            image=img_slug_or_id,
-            size_slug=size_slug,
-            ssh_keys=[sshkey],
-            backups=False,
-        )
-        droplet.create()
-
-        if project:
-            project.assign_resources(["do:droplet:%s" % droplet.id])
-
-    def delete_remote(self):
-        """Delete Droplet from digital ocean
-
-        e.g
-            droplet.delete_remote()
-
-        """
-        droplet = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-        droplet.destroy()
-
-
-class DigitalOcean(Client):
-    name = fields.String()
-    token_ = fields.String()
-    projects = fields.Factory(Project, factory_type=ProjectFactory)
-    droplets = fields.Factory(Droplet, factory_type=DropletFactory)
-
-    def __init__(self):
-        super().__init__()
-        self._client = None
-
-    @property
-    def client(self):
-        """Return a new client if it is not set or it will return the already existed one
-
-        e.g
-            dg.client  -> <Manager>
-        Returns
-            Manager: client form digital ocean manager
-        """
-
-        if not self._client:
-            self._client = digitalocean.Manager(token=self.token_)
-        return self._client
-
-    # Images
-    @property
-    def images(self):
-        """Return a list of digital ocean availabe images
-
-        e.g
-            dg.images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                         <Image: 34902021 CentOS 6.9 x64>,...]
-
-        Returns
-            List : list of images on digital ocean available
-        """
-        return self.client.get_distro_images()
-
-    @property
-    def myimages(self):
-        """Return a list of digital ocean images, you have created
-
-        e.g
-            dg.myimages  -> [<Image: 48614453 Unknown Zero_OS>,
-                                        <Image: 50898718 Ubuntu JumpScale>,...]
-
-        Returns
-            List : list of images on digital ocean, you have created
-        """
-        return self.client.get_images(private=True)
-
-    @property
-    def account_images(self):
-        """Return a list of digital ocean images and the images you have created
-
-        e.g
-            dg.account_images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                             <Image: 34902021 CentOS 6.9 x64>,...]
-
-        Returns
-            List : list of images on digital ocean images and the images you have created
-        """
-
-        return self.images + self.myimages
-
-    def get_image(self, name):
-        """Return an image
-
-        e.g
-            dg.get_image(name="CentOS")  -> <Image: 31354013 CentOS 6.9 x32>
-
-        Args
-            name (str): name of the  required image
-        Returns
-            Image : list of images on digital ocean images and the images you have created
-        """
-        for item in self.account_images:
-            if item.description:
-                name_do1 = item.description.lower()
-            else:
-                name_do1 = ""
-            name_do2 = item.distribution + " " + item.name
-            print(f" - {name_do1}--{name_do2}")
-            if name_do1.lower().find(name.lower()) != -1 or name_do2.lower().find(name.lower()) != -1:
-                return item
-        raise j.exceptions.Base("did not find image:%s" % name)
-
-    def get_image_names(self, name=""):
-        """ Return all the image  or images with a specified name
-         e.g
-            dg.get_image_names()  -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602',...]
-            dg.get_image_names("centos") -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602']
-
-        Args
-            name (str): name of the  required image
-        Returns
-            Image : list of images
-        """
-        res = []
-        name = name.lower()
-        for item in self.images:
-            if item.description:
-                name_do = item.description.lower()
-            else:
-                name_do = item.distribution + " " + item.name
-            if name_do.find(name) != -1:
-                res.append(name_do)
-        return res
-
-    # Size
-
-    @property
-    def sizes(self):
-        """Return a list sizes available on digital ocean
-
-        e.g
-            dg.sizes -> [s-1vcpu-1gb, 512mb, s-1vcpu-2gb, 1gb, s-3vcpu-1gb,.....]
-
-        Returns
-            List : list of sizes
-        """
-        return self.client.get_all_sizes()
-
-    # Regions
-
-    @property
-    def regions(self):
-        """Return a list regions available on digital ocean
-
-        e.g
-            dg.regions  -> [<Region: nyc1 New York 1>, <Region: sgp1 Singapore 1>,...]
-
-        Returns
-            List : list of regions
-        """
-        return self.client.get_all_regions()
-
-    @property
-    def region_names(self):
-        """Returns Digital Ocean regions
-
-        e.g
-            dg.region_names  -> ['nyc1', 'sgp1', 'lon1', 'nyc3', 'ams3', 'fra1', 'tor1', 'sfo2', 'blr1']
-
-        Returns
-            list : list of digital ocean regions
-        """
-        return [i.slug for i in self.regions]
-
-    def get_region(self, name):
-        """
-        Returns specific region
-
-        e.g
-            dg.get_region(name = 'nyc1')  -> <Region: nyc1 New York 1>
-
-        Args
-            name (str) : name of the required region
-        Returns
-            Region : the region with the name specified
-        """
-        for item in self.regions:
-            if name == item.slug:
-                return item
-            if name == item.name:
-                return item
-        raise j.exceptions.Base("did not find region:%s" % name)
-
-    # SSHkeys
-    @property
-    def sshkeys(self):
-        """
-        Return list of sshkeys on digital ocean
-
-        e.g
-            dg.sshkeys  -> [<SSHKey: 25882170 3bot_container_sandbox>,
-                             <SSHKey: 27130645 Geert-root>,...]
-
-        Returns
-            list : list of sshkeys
-        """
-
-        return self.client.get_all_sshkeys()
-
-    def get_default_sshkey(self):
-        """
-        Return sshkey you have added to your Digital Ocean client
-
-        e.g
-            dg.get_default_sshkey()  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Returns
-            list : list of sshkeys
-        """
-        pubkeyonly = self.sshkey.public_key
-        for item in self.sshkeys:
-            if item.public_key.find(pubkeyonly) != -1:
-                return item
-        return None
-
-    def set_default_sshkey(self, default_sshkey):
-        """
-        Set sshkey you  Digital Ocean client
-
-        e.g
-            dg.set_default_sshkey(ssh)  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Args
-            default_sshkey (SSHKeyClient) : sshkey client you have created
-        """
-        self.sshkey = default_sshkey
-
-    def get_sshkey(self, name):
-        """
-        get sshkey from  Digital Ocean
-
-        e.g
-            dg.get_sshkey("rafy@rafy-Inspiron-3576")   ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Args
-            name (string) : sshkey name
-
-        Returns
-            SSHKey : return the specified sshkey
-        """
-        for item in self.sshkeys:
-            if name == item.name:
-                return item
-        raise j.exceptions.Base("did not find key:%s" % name)
-
-    def __str__(self):
-        return "digital ocean client:%s" % self.name
-
-    __repr__ = __str__
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class DigitalOcean -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class DigitalOcean(Client):
-    name = fields.String()
-    token_ = fields.String()
-    projects = fields.Factory(Project, factory_type=ProjectFactory)
-    droplets = fields.Factory(Droplet, factory_type=DropletFactory)
-
-    def __init__(self):
-        super().__init__()
-        self._client = None
-
-    @property
-    def client(self):
-        """Return a new client if it is not set or it will return the already existed one
-
-        e.g
-            dg.client  -> <Manager>
-        Returns
-            Manager: client form digital ocean manager
-        """
-
-        if not self._client:
-            self._client = digitalocean.Manager(token=self.token_)
-        return self._client
-
-    # Images
-    @property
-    def images(self):
-        """Return a list of digital ocean availabe images
-
-        e.g
-            dg.images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                         <Image: 34902021 CentOS 6.9 x64>,...]
-
-        Returns
-            List : list of images on digital ocean available
-        """
-        return self.client.get_distro_images()
-
-    @property
-    def myimages(self):
-        """Return a list of digital ocean images, you have created
-
-        e.g
-            dg.myimages  -> [<Image: 48614453 Unknown Zero_OS>,
-                                        <Image: 50898718 Ubuntu JumpScale>,...]
-
-        Returns
-            List : list of images on digital ocean, you have created
-        """
-        return self.client.get_images(private=True)
-
-    @property
-    def account_images(self):
-        """Return a list of digital ocean images and the images you have created
-
-        e.g
-            dg.account_images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                             <Image: 34902021 CentOS 6.9 x64>,...]
-
-        Returns
-            List : list of images on digital ocean images and the images you have created
-        """
-
-        return self.images + self.myimages
-
-    def get_image(self, name):
-        """Return an image
-
-        e.g
-            dg.get_image(name="CentOS")  -> <Image: 31354013 CentOS 6.9 x32>
-
-        Args
-            name (str): name of the  required image
-        Returns
-            Image : list of images on digital ocean images and the images you have created
-        """
-        for item in self.account_images:
-            if item.description:
-                name_do1 = item.description.lower()
-            else:
-                name_do1 = ""
-            name_do2 = item.distribution + " " + item.name
-            print(f" - {name_do1}--{name_do2}")
-            if name_do1.lower().find(name.lower()) != -1 or name_do2.lower().find(name.lower()) != -1:
-                return item
-        raise j.exceptions.Base("did not find image:%s" % name)
-
-    def get_image_names(self, name=""):
-        """ Return all the image  or images with a specified name
-         e.g
-            dg.get_image_names()  -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602',...]
-            dg.get_image_names("centos") -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602']
-
-        Args
-            name (str): name of the  required image
-        Returns
-            Image : list of images
-        """
-        res = []
-        name = name.lower()
-        for item in self.images:
-            if item.description:
-                name_do = item.description.lower()
-            else:
-                name_do = item.distribution + " " + item.name
-            if name_do.find(name) != -1:
-                res.append(name_do)
-        return res
-
-    # Size
-
-    @property
-    def sizes(self):
-        """Return a list sizes available on digital ocean
-
-        e.g
-            dg.sizes -> [s-1vcpu-1gb, 512mb, s-1vcpu-2gb, 1gb, s-3vcpu-1gb,.....]
-
-        Returns
-            List : list of sizes
-        """
-        return self.client.get_all_sizes()
-
-    # Regions
-
-    @property
-    def regions(self):
-        """Return a list regions available on digital ocean
-
-        e.g
-            dg.regions  -> [<Region: nyc1 New York 1>, <Region: sgp1 Singapore 1>,...]
-
-        Returns
-            List : list of regions
-        """
-        return self.client.get_all_regions()
-
-    @property
-    def region_names(self):
-        """Returns Digital Ocean regions
-
-        e.g
-            dg.region_names  -> ['nyc1', 'sgp1', 'lon1', 'nyc3', 'ams3', 'fra1', 'tor1', 'sfo2', 'blr1']
-
-        Returns
-            list : list of digital ocean regions
-        """
-        return [i.slug for i in self.regions]
-
-    def get_region(self, name):
-        """
-        Returns specific region
-
-        e.g
-            dg.get_region(name = 'nyc1')  -> <Region: nyc1 New York 1>
-
-        Args
-            name (str) : name of the required region
-        Returns
-            Region : the region with the name specified
-        """
-        for item in self.regions:
-            if name == item.slug:
-                return item
-            if name == item.name:
-                return item
-        raise j.exceptions.Base("did not find region:%s" % name)
-
-    # SSHkeys
-    @property
-    def sshkeys(self):
-        """
-        Return list of sshkeys on digital ocean
-
-        e.g
-            dg.sshkeys  -> [<SSHKey: 25882170 3bot_container_sandbox>,
-                             <SSHKey: 27130645 Geert-root>,...]
-
-        Returns
-            list : list of sshkeys
-        """
-
-        return self.client.get_all_sshkeys()
-
-    def get_default_sshkey(self):
-        """
-        Return sshkey you have added to your Digital Ocean client
-
-        e.g
-            dg.get_default_sshkey()  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Returns
-            list : list of sshkeys
-        """
-        pubkeyonly = self.sshkey.public_key
-        for item in self.sshkeys:
-            if item.public_key.find(pubkeyonly) != -1:
-                return item
-        return None
-
-    def set_default_sshkey(self, default_sshkey):
-        """
-        Set sshkey you  Digital Ocean client
-
-        e.g
-            dg.set_default_sshkey(ssh)  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Args
-            default_sshkey (SSHKeyClient) : sshkey client you have created
-        """
-        self.sshkey = default_sshkey
-
-    def get_sshkey(self, name):
-        """
-        get sshkey from  Digital Ocean
-
-        e.g
-            dg.get_sshkey("rafy@rafy-Inspiron-3576")   ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-        Args
-            name (string) : sshkey name
-
-        Returns
-            SSHKey : return the specified sshkey
-        """
-        for item in self.sshkeys:
-            if name == item.name:
-                return item
-        raise j.exceptions.Base("did not find key:%s" % name)
-
-    def __str__(self):
-        return "digital ocean client:%s" % self.name
-
-    __repr__ = __str__
-
-

Ancestors

- -

Instance variables

-
-
var account_images
-
-

Return a list of digital ocean images and the images you have created

-

e.g -dg.account_images --> [, -,…]

-

Returns -List : list of images on digital ocean images and the images you have created

-
-Source code -
@property
-def account_images(self):
-    """Return a list of digital ocean images and the images you have created
-
-    e.g
-        dg.account_images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                         <Image: 34902021 CentOS 6.9 x64>,...]
-
-    Returns
-        List : list of images on digital ocean images and the images you have created
-    """
-
-    return self.images + self.myimages
-
-
-
var client
-
-

Return a new client if it is not set or it will return the already existed one

-

e.g -dg.client --> -Returns -Manager: client form digital ocean manager

-
-Source code -
@property
-def client(self):
-    """Return a new client if it is not set or it will return the already existed one
-
-    e.g
-        dg.client  -> <Manager>
-    Returns
-        Manager: client form digital ocean manager
-    """
-
-    if not self._client:
-        self._client = digitalocean.Manager(token=self.token_)
-    return self._client
-
-
-
var droplets
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var images
-
-

Return a list of digital ocean availabe images

-

e.g -dg.images --> [, -,…]

-

Returns -List : list of images on digital ocean available

-
-Source code -
@property
-def images(self):
-    """Return a list of digital ocean availabe images
-
-    e.g
-        dg.images  -> [<Image: 31354013 CentOS 6.9 x32>,
-                                     <Image: 34902021 CentOS 6.9 x64>,...]
-
-    Returns
-        List : list of images on digital ocean available
-    """
-    return self.client.get_distro_images()
-
-
-
var myimages
-
-

Return a list of digital ocean images, you have created

-

e.g -dg.myimages --> [, -,…]

-

Returns -List : list of images on digital ocean, you have created

-
-Source code -
@property
-def myimages(self):
-    """Return a list of digital ocean images, you have created
-
-    e.g
-        dg.myimages  -> [<Image: 48614453 Unknown Zero_OS>,
-                                    <Image: 50898718 Ubuntu JumpScale>,...]
-
-    Returns
-        List : list of images on digital ocean, you have created
-    """
-    return self.client.get_images(private=True)
-
-
-
var name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var projects
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var region_names
-
-

Returns Digital Ocean regions

-

e.g -dg.region_names --> ['nyc1', 'sgp1', 'lon1', 'nyc3', 'ams3', 'fra1', 'tor1', 'sfo2', 'blr1']

-

Returns -list : list of digital ocean regions

-
-Source code -
@property
-def region_names(self):
-    """Returns Digital Ocean regions
-
-    e.g
-        dg.region_names  -> ['nyc1', 'sgp1', 'lon1', 'nyc3', 'ams3', 'fra1', 'tor1', 'sfo2', 'blr1']
-
-    Returns
-        list : list of digital ocean regions
-    """
-    return [i.slug for i in self.regions]
-
-
-
var regions
-
-

Return a list regions available on digital ocean

-

e.g -dg.regions --> [, ,…]

-

Returns -List : list of regions

-
-Source code -
@property
-def regions(self):
-    """Return a list regions available on digital ocean
-
-    e.g
-        dg.regions  -> [<Region: nyc1 New York 1>, <Region: sgp1 Singapore 1>,...]
-
-    Returns
-        List : list of regions
-    """
-    return self.client.get_all_regions()
-
-
-
var sizes
-
-

Return a list sizes available on digital ocean

-

e.g -dg.sizes -> [s-1vcpu-1gb, 512mb, s-1vcpu-2gb, 1gb, s-3vcpu-1gb,.....]

-

Returns -List : list of sizes

-
-Source code -
@property
-def sizes(self):
-    """Return a list sizes available on digital ocean
-
-    e.g
-        dg.sizes -> [s-1vcpu-1gb, 512mb, s-1vcpu-2gb, 1gb, s-3vcpu-1gb,.....]
-
-    Returns
-        List : list of sizes
-    """
-    return self.client.get_all_sizes()
-
-
-
var sshkeys
-
-

Return list of sshkeys on digital ocean

-

e.g -dg.sshkeys --> [, -,…]

-

Returns -list : list of sshkeys

-
-Source code -
@property
-def sshkeys(self):
-    """
-    Return list of sshkeys on digital ocean
-
-    e.g
-        dg.sshkeys  -> [<SSHKey: 25882170 3bot_container_sandbox>,
-                         <SSHKey: 27130645 Geert-root>,...]
-
-    Returns
-        list : list of sshkeys
-    """
-
-    return self.client.get_all_sshkeys()
-
-
-
var token_
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def get_default_sshkey(self) -
-
-

Return sshkey you have added to your Digital Ocean client

-

e.g -dg.get_default_sshkey() --> -

-

Returns -list : list of sshkeys

-
-Source code -
def get_default_sshkey(self):
-    """
-    Return sshkey you have added to your Digital Ocean client
-
-    e.g
-        dg.get_default_sshkey()  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-    Returns
-        list : list of sshkeys
-    """
-    pubkeyonly = self.sshkey.public_key
-    for item in self.sshkeys:
-        if item.public_key.find(pubkeyonly) != -1:
-            return item
-    return None
-
-
-
-def get_image(self, name) -
-
-

Return an image

-

e.g -dg.get_image(name="CentOS") -->

-

Args -name (str): name of the -required image -Returns -Image : list of images on digital ocean images and the images you have created

-
-Source code -
def get_image(self, name):
-    """Return an image
-
-    e.g
-        dg.get_image(name="CentOS")  -> <Image: 31354013 CentOS 6.9 x32>
-
-    Args
-        name (str): name of the  required image
-    Returns
-        Image : list of images on digital ocean images and the images you have created
-    """
-    for item in self.account_images:
-        if item.description:
-            name_do1 = item.description.lower()
-        else:
-            name_do1 = ""
-        name_do2 = item.distribution + " " + item.name
-        print(f" - {name_do1}--{name_do2}")
-        if name_do1.lower().find(name.lower()) != -1 or name_do2.lower().find(name.lower()) != -1:
-            return item
-    raise j.exceptions.Base("did not find image:%s" % name)
-
-
-
-def get_image_names(self, name='') -
-
-

Return all the image -or images with a specified name -e.g -dg.get_image_names() --> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602',…] -dg.get_image_names("centos") -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602']

-

Args -name (str): name of the -required image -Returns -Image : list of images

-
-Source code -
def get_image_names(self, name=""):
-    """ Return all the image  or images with a specified name
-     e.g
-        dg.get_image_names()  -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602',...]
-        dg.get_image_names("centos") -> ['centos 6.9 x32 20180130', 'centos 6.9 x64 20180602']
-
-    Args
-        name (str): name of the  required image
-    Returns
-        Image : list of images
-    """
-    res = []
-    name = name.lower()
-    for item in self.images:
-        if item.description:
-            name_do = item.description.lower()
-        else:
-            name_do = item.distribution + " " + item.name
-        if name_do.find(name) != -1:
-            res.append(name_do)
-    return res
-
-
-
-def get_region(self, name) -
-
-

Returns specific region

-

e.g -dg.get_region(name = 'nyc1') -->

-

Args -name (str) : name of the required region -Returns -Region : the region with the name specified

-
-Source code -
def get_region(self, name):
-    """
-    Returns specific region
-
-    e.g
-        dg.get_region(name = 'nyc1')  -> <Region: nyc1 New York 1>
-
-    Args
-        name (str) : name of the required region
-    Returns
-        Region : the region with the name specified
-    """
-    for item in self.regions:
-        if name == item.slug:
-            return item
-        if name == item.name:
-            return item
-    raise j.exceptions.Base("did not find region:%s" % name)
-
-
-
-def get_sshkey(self, name) -
-
-

get sshkey from -Digital Ocean

-

e.g -dg.get_sshkey("rafy@rafy-Inspiron-3576") --> -

-

Args -name (string) : sshkey name

-

Returns -SSHKey : return the specified sshkey

-
-Source code -
def get_sshkey(self, name):
-    """
-    get sshkey from  Digital Ocean
-
-    e.g
-        dg.get_sshkey("rafy@rafy-Inspiron-3576")   ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-    Args
-        name (string) : sshkey name
-
-    Returns
-        SSHKey : return the specified sshkey
-    """
-    for item in self.sshkeys:
-        if name == item.name:
-            return item
-    raise j.exceptions.Base("did not find key:%s" % name)
-
-
-
-def set_default_sshkey(self, default_sshkey) -
-
-

Set sshkey you -Digital Ocean client

-

e.g -dg.set_default_sshkey(ssh) --> -

-

Args -default_sshkey (SSHKeyClient) : sshkey client you have created

-
-Source code -
def set_default_sshkey(self, default_sshkey):
-    """
-    Set sshkey you  Digital Ocean client
-
-    e.g
-        dg.set_default_sshkey(ssh)  ->  <SSHKey: 25589987 rafy@rafy-Inspiron-3576>
-
-    Args
-        default_sshkey (SSHKeyClient) : sshkey client you have created
-    """
-    self.sshkey = default_sshkey
-
-
-
-

Inherited members

- -
-
-class Droplet -(*args, **kwargs) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class Droplet(Client):
-    do_name = fields.String()
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def set_digital_ocean_name(self, name):
-        """Set a name for your Droplet to be used on Digital Ocean
-
-        e.g
-            droplet.set_digital_ocean_name("test-name")
-
-        Args:
-            name (str): name to be used on digital ocean
-        """
-        self.do_name = name
-
-    def get_digital_ocean_name(self):
-        """Get a name for the Droplet which is used on digital ocean
-
-        e.g
-            droplet.get_digital_ocean_name()  ->  "test-name"
-
-        Returns
-            str: name for the droplet which is used on digital ocean
-        """
-        return self.do_name
-
-    def deploy(
-        self,
-        sshkey=None,
-        region="Amsterdam 3",
-        image="ubuntu 18.04",
-        size_slug="s-1vcpu-2gb",
-        delete=True,
-        project_name=None,
-    ):
-        """
-        Deploy your Droplet to Digital Ocean
-
-        Args
-            sshkey (string): sshkey name used on digital ocean (if not set it will use the default one which already loaded)
-            region (string): region name to deploy to
-            image (string): Image name to be used
-            size_slug (string): size of the droplet  (s-1vcpu-2gb,s-6vcpu-16gb,gd-8vcpu-32gb)
-            delete (bool): delete the droplet if it is already deployed on digital ocean
-            project_name (string): project to add this droplet it. If not specified the default project will be used.
-
-        """
-        project = None
-        if project_name:
-            project = self.parent.projects.get_project_exist_remote(self.do_name)
-            if not project:
-                raise j.exceptions.Input("could not find project with name:%s" % project_name)
-
-        # Get ssh
-        if not sshkey:
-            sshkey_do = self.parent.get_default_sshkey()
-
-            if not sshkey_do:
-                # means we did not find the sshkey on digital ocean yet, need to create
-                sshkey = self.parent.sshkey
-                key = digitalocean.SSHKey(
-                    token=self.parent.projects.parent_instance.token_, name=sshkey.name, public_key=sshkey.public_key
-                )
-                key.create()
-            sshkey_do = self.parent.get_default_sshkey()
-            assert sshkey_do
-            sshkey = sshkey_do.name
-
-        if self.parent.droplets.check_droplet_exist_remote(self.do_name):
-            dr0 = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-            if delete:
-                dr0.destroy()
-            else:
-                sshcl = j.clients.sshclient.get(name="do_%s" % self.do_name, host=dr0.ip_address, sshkey=sshkey)
-                return dr0, sshcl
-
-        sshkey = self.parent.droplets.parent_instance.get_sshkey(sshkey)
-        region = self.parent.droplets.parent_instance.get_region(region)
-        imagedo = self.parent.droplets.parent_instance.get_image(image)
-
-        img_slug_or_id = imagedo.slug if imagedo.slug else imagedo.id
-
-        droplet = digitalocean.Droplet(
-            token=self.parent.droplets.parent_instance.token_,
-            name=self.do_name,
-            region=region.slug,
-            image=img_slug_or_id,
-            size_slug=size_slug,
-            ssh_keys=[sshkey],
-            backups=False,
-        )
-        droplet.create()
-
-        if project:
-            project.assign_resources(["do:droplet:%s" % droplet.id])
-
-    def delete_remote(self):
-        """Delete Droplet from digital ocean
-
-        e.g
-            droplet.delete_remote()
-
-        """
-        droplet = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-        droplet.destroy()
-
-

Ancestors

- -

Instance variables

-
-
var do_name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def delete_remote(self) -
-
-

Delete Droplet from digital ocean

-

e.g -droplet.delete_remote()

-
-Source code -
def delete_remote(self):
-    """Delete Droplet from digital ocean
-
-    e.g
-        droplet.delete_remote()
-
-    """
-    droplet = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-    droplet.destroy()
-
-
-
-def deploy(self, sshkey=None, region='Amsterdam 3', image='ubuntu 18.04', size_slug='s-1vcpu-2gb', delete=True, project_name=None) -
-
-

Deploy your Droplet to Digital Ocean

-

Args -sshkey (string): sshkey name used on digital ocean (if not set it will use the default one which already loaded) -region (string): region name to deploy to -image (string): Image name to be used -size_slug (string): size of the droplet -(s-1vcpu-2gb,s-6vcpu-16gb,gd-8vcpu-32gb) -delete (bool): delete the droplet if it is already deployed on digital ocean -project_name (string): project to add this droplet it. If not specified the default project will be used.

-
-Source code -
def deploy(
-    self,
-    sshkey=None,
-    region="Amsterdam 3",
-    image="ubuntu 18.04",
-    size_slug="s-1vcpu-2gb",
-    delete=True,
-    project_name=None,
-):
-    """
-    Deploy your Droplet to Digital Ocean
-
-    Args
-        sshkey (string): sshkey name used on digital ocean (if not set it will use the default one which already loaded)
-        region (string): region name to deploy to
-        image (string): Image name to be used
-        size_slug (string): size of the droplet  (s-1vcpu-2gb,s-6vcpu-16gb,gd-8vcpu-32gb)
-        delete (bool): delete the droplet if it is already deployed on digital ocean
-        project_name (string): project to add this droplet it. If not specified the default project will be used.
-
-    """
-    project = None
-    if project_name:
-        project = self.parent.projects.get_project_exist_remote(self.do_name)
-        if not project:
-            raise j.exceptions.Input("could not find project with name:%s" % project_name)
-
-    # Get ssh
-    if not sshkey:
-        sshkey_do = self.parent.get_default_sshkey()
-
-        if not sshkey_do:
-            # means we did not find the sshkey on digital ocean yet, need to create
-            sshkey = self.parent.sshkey
-            key = digitalocean.SSHKey(
-                token=self.parent.projects.parent_instance.token_, name=sshkey.name, public_key=sshkey.public_key
-            )
-            key.create()
-        sshkey_do = self.parent.get_default_sshkey()
-        assert sshkey_do
-        sshkey = sshkey_do.name
-
-    if self.parent.droplets.check_droplet_exist_remote(self.do_name):
-        dr0 = self.parent.droplets.get_droplet_exist_remote(self.do_name)
-        if delete:
-            dr0.destroy()
-        else:
-            sshcl = j.clients.sshclient.get(name="do_%s" % self.do_name, host=dr0.ip_address, sshkey=sshkey)
-            return dr0, sshcl
-
-    sshkey = self.parent.droplets.parent_instance.get_sshkey(sshkey)
-    region = self.parent.droplets.parent_instance.get_region(region)
-    imagedo = self.parent.droplets.parent_instance.get_image(image)
-
-    img_slug_or_id = imagedo.slug if imagedo.slug else imagedo.id
-
-    droplet = digitalocean.Droplet(
-        token=self.parent.droplets.parent_instance.token_,
-        name=self.do_name,
-        region=region.slug,
-        image=img_slug_or_id,
-        size_slug=size_slug,
-        ssh_keys=[sshkey],
-        backups=False,
-    )
-    droplet.create()
-
-    if project:
-        project.assign_resources(["do:droplet:%s" % droplet.id])
-
-
-
-def get_digital_ocean_name(self) -
-
-

Get a name for the Droplet which is used on digital ocean

-

e.g -droplet.get_digital_ocean_name() --> -"test-name"

-

Returns -str: name for the droplet which is used on digital ocean

-
-Source code -
def get_digital_ocean_name(self):
-    """Get a name for the Droplet which is used on digital ocean
-
-    e.g
-        droplet.get_digital_ocean_name()  ->  "test-name"
-
-    Returns
-        str: name for the droplet which is used on digital ocean
-    """
-    return self.do_name
-
-
-
-def set_digital_ocean_name(self, name) -
-
-

Set a name for your Droplet to be used on Digital Ocean

-

e.g -droplet.set_digital_ocean_name("test-name") -

-

Args

-
-
name : str
-
name to be used on digital ocean
-
-
-Source code -
def set_digital_ocean_name(self, name):
-    """Set a name for your Droplet to be used on Digital Ocean
-
-    e.g
-        droplet.set_digital_ocean_name("test-name")
-
-    Args:
-        name (str): name to be used on digital ocean
-    """
-    self.do_name = name
-
-
-
-

Inherited members

- -
-
-class DropletFactory -(*args, **kwargs) -
-
-

Stored factories are a custom type of Factory, which uses current configured store backend -to store all instance configurations.

-

get a new stored factory given the type to create and store instances for.

-

Any factory can have a name, parent Base instance and a parent factory.

-

Once a stored factory is created, it tries to lazy-load all current configuration for given type_.

-

Args

-
-
type_ : Base
-
Base class type
-
name_ : str, optional
-
factory name. Defaults to None.
-
parent_instance_ : Base, optional
-
a parent Base instance. Defaults to None.
-
parent_factory_ : Factory, optional
-
a parent Factory. Defaults to None.
-
-
-Source code -
class DropletFactory(StoredFactory):
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def list_remote(self, project_name=None):
-        """
-        List all remote droplet or list droplets for a project if it is specified
-
-        e.g
-            dg.droplets.list_remote()  -> list of droplets
-            dg.droplets.list_remote("codescalers")  -> list of droplets on codescalers project
-
-        Args:
-            project_name (str) : name of project on digital ocean (optional)
-
-        Returns
-            list (Droplet) : list of droplets on digital ocean
-
-
-        """
-        if project_name:
-            project = self.parent_instance.projects.get_project_exist_remote(project_name)
-            return project.list_droplets()
-
-        return self.parent_instance.client.get_all_droplets()
-
-    def check_droplet_exist_remote(self, name):
-        """
-        Check droplet exists on digital ocean
-
-        e.g
-            dg.droplets.check_droplet_exist_remote("3git")  -> True
-            dg.droplets.check_droplet_exist_remote("sdfgdfed")  -> False
-
-        Args:
-            name (str) : name of droplet
-
-        Returns
-            bool : True if the droplet exist or False if the droplet does not exist
-        """
-        for droplet in self.list_remote():
-            if droplet.name.lower() == name.lower():
-                return True
-        return False
-
-    def get_droplet_exist_remote(self, name):
-        """
-        Get Droplet exists from Digital Ocean
-
-        e.g
-            dg.droplets.get_droplet_exist_remote("3git")
-
-        Args:
-            name (str) : name of droplet
-
-        Returns
-            droplet : droplet with the name specified
-
-        """
-        for droplet in self.list_remote():
-            if droplet.name.lower() == name.lower():
-                return droplet
-        raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-    def shutdown_all(self, project_name=None):
-        """
-        Shutdown all the droplets or droplets in specific project
-
-        e.g
-            dg.droplets.shutdown_all("codescalers")
-            dg.droplets.shutdown_all()
-
-        Args:
-            name (str) : name of the project
-
-        """
-        for droplet in self.list_remote(project_name):
-            droplet.shutdown()
-
-    def delete_all(self, ignore=None, interactive=True, project_name=None):
-        """
-        Delete all the droplets or delete all the droplets in specific project
-
-        e.g
-            dg.droplets.delete_all(project_name = "codescalers")
-            dg.droplets.delete_all()
-
-        Args:
-            project_name (str) : name of the project
-            ignore (list): list of ignored droplets to prevent their deletion
-            interactive (bool): if True the deletion will be interactive and
-                                confirm if you want to delete but if False it
-                                will delete directly
-        """
-        if not ignore:
-            ignore = []
-
-        def test(ignore, name):
-            if name.startswith("TF-"):
-                return False
-            for item in ignore:
-                if name.lower().find(item.lower()) != -1:
-                    return False
-            return True
-
-        todo = []
-        for droplet in self.list_remote(project_name):
-            if test(ignore, droplet.name):
-                todo.append(droplet)
-        if todo != []:
-            todotxt = ",".join([i.name for i in todo])
-            if not interactive or j.tools.console.ask_yes_no("ok to delete:%s" % todotxt):
-                for droplet in todo:
-                    droplet.destroy()
-
-

Ancestors

- -

Methods

-
-
-def check_droplet_exist_remote(self, name) -
-
-

Check droplet exists on digital ocean

-

e.g -dg.droplets.check_droplet_exist_remote("3git") --> True -dg.droplets.check_droplet_exist_remote("sdfgdfed") --> False

-

Args

-
-
name (str) : name of droplet
-
Returns
-
bool : True if the droplet exist or False if the droplet does not exist
-
-
-Source code -
def check_droplet_exist_remote(self, name):
-    """
-    Check droplet exists on digital ocean
-
-    e.g
-        dg.droplets.check_droplet_exist_remote("3git")  -> True
-        dg.droplets.check_droplet_exist_remote("sdfgdfed")  -> False
-
-    Args:
-        name (str) : name of droplet
-
-    Returns
-        bool : True if the droplet exist or False if the droplet does not exist
-    """
-    for droplet in self.list_remote():
-        if droplet.name.lower() == name.lower():
-            return True
-    return False
-
-
-
-def delete_all(self, ignore=None, interactive=True, project_name=None) -
-
-

Delete all the droplets or delete all the droplets in specific project -

-

e.g -dg.droplets.delete_all(project_name = "codescalers") -dg.droplets.delete_all()

-

Args

-
-
project_name (str) : name of the project
-
ignore : list
-
list of ignored droplets to prevent their deletion
-
interactive : bool
-
if True the deletion will be interactive and -confirm if you want to delete but if False it -will delete directly
-
-
-Source code -
def delete_all(self, ignore=None, interactive=True, project_name=None):
-    """
-    Delete all the droplets or delete all the droplets in specific project
-
-    e.g
-        dg.droplets.delete_all(project_name = "codescalers")
-        dg.droplets.delete_all()
-
-    Args:
-        project_name (str) : name of the project
-        ignore (list): list of ignored droplets to prevent their deletion
-        interactive (bool): if True the deletion will be interactive and
-                            confirm if you want to delete but if False it
-                            will delete directly
-    """
-    if not ignore:
-        ignore = []
-
-    def test(ignore, name):
-        if name.startswith("TF-"):
-            return False
-        for item in ignore:
-            if name.lower().find(item.lower()) != -1:
-                return False
-        return True
-
-    todo = []
-    for droplet in self.list_remote(project_name):
-        if test(ignore, droplet.name):
-            todo.append(droplet)
-    if todo != []:
-        todotxt = ",".join([i.name for i in todo])
-        if not interactive or j.tools.console.ask_yes_no("ok to delete:%s" % todotxt):
-            for droplet in todo:
-                droplet.destroy()
-
-
-
-def get_droplet_exist_remote(self, name) -
-
-

Get Droplet exists from Digital Ocean

-

e.g -dg.droplets.get_droplet_exist_remote("3git")

-

Args

-
-
name (str) : name of droplet
-
Returns
-
droplet : droplet with the name specified
-
-
-Source code -
def get_droplet_exist_remote(self, name):
-    """
-    Get Droplet exists from Digital Ocean
-
-    e.g
-        dg.droplets.get_droplet_exist_remote("3git")
-
-    Args:
-        name (str) : name of droplet
-
-    Returns
-        droplet : droplet with the name specified
-
-    """
-    for droplet in self.list_remote():
-        if droplet.name.lower() == name.lower():
-            return droplet
-    raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-
-
-def list_remote(self, project_name=None) -
-
-

List all remote droplet or list droplets for a project if it is specified

-

e.g -dg.droplets.list_remote() --> list of droplets -dg.droplets.list_remote("codescalers") --> list of droplets on codescalers project

-

Args

-
-
project_name (str) : name of project on digital ocean (optional)
-
Returns
-
list (Droplet) : list of droplets on digital ocean
-
-
-Source code -
def list_remote(self, project_name=None):
-    """
-    List all remote droplet or list droplets for a project if it is specified
-
-    e.g
-        dg.droplets.list_remote()  -> list of droplets
-        dg.droplets.list_remote("codescalers")  -> list of droplets on codescalers project
-
-    Args:
-        project_name (str) : name of project on digital ocean (optional)
-
-    Returns
-        list (Droplet) : list of droplets on digital ocean
-
-
-    """
-    if project_name:
-        project = self.parent_instance.projects.get_project_exist_remote(project_name)
-        return project.list_droplets()
-
-    return self.parent_instance.client.get_all_droplets()
-
-
-
-def shutdown_all(self, project_name=None) -
-
-

Shutdown all the droplets or droplets in specific project -

-

e.g -dg.droplets.shutdown_all("codescalers") -dg.droplets.shutdown_all()

-

Args

-

name (str) : name of the project

-
-Source code -
def shutdown_all(self, project_name=None):
-    """
-    Shutdown all the droplets or droplets in specific project
-
-    e.g
-        dg.droplets.shutdown_all("codescalers")
-        dg.droplets.shutdown_all()
-
-    Args:
-        name (str) : name of the project
-
-    """
-    for droplet in self.list_remote(project_name):
-        droplet.shutdown()
-
-
-
-

Inherited members

- -
-
-class Project -(*args, **kwargs) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class Project(Client):
-    do_name = fields.String()
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def set_digital_ocean_name(self, name):
-        """Set a name for your project to be used on Digital Ocean
-        e.g
-            project.set_digital_ocean_name("test project DO client")
-
-        Args:
-            name (str): name to be used on digital ocean
-        """
-        self.do_name = name
-
-    def get_digital_ocean_name(self):
-        """Get a name for the project which is used on digital ocean
-        e.g
-            project.get_digital_ocean_name()  ->  "test project DO client"
-
-        Returns:
-            str: name for the project which is used on digital ocean
-        """
-        return self.do_name
-
-    def deploy(self, purpose, description="", environment="", is_default=False):
-        """Create a digital ocean project
-        e.g
-            project.deploy(purpose="testing digital ocean client")  -> project
-        Args:
-            purpose(str): purpose of the project (not optional)
-            description(str): description of the project, defaults to ""
-            environment(str): environment of project's resources, defaults to ""
-            is_default(bool): make this the default project for your user
-
-        Returns:
-            project: The project object that has been created
-        """
-
-        if self.parent.projects.check_project_exist_remote(self.do_name):
-            raise j.exceptions.Value("A project with the same name already exists")
-
-        project = ProjectManagement(
-            token=self.parent.projects.parent_instance.token_,
-            name=self.do_name,
-            purpose=purpose,
-            description=description,
-            environment=environment,
-            is_default=is_default,
-        )
-        project.create()
-
-        if is_default:
-            project.update(is_default=True)
-
-        return project
-
-    def delete_remote(self):
-        """Delete the project from Digital Ocean (A project can't be deleted unless it has no resources.)
-
-        e.g
-            project.delete_remote()
-        """
-        project = self.parent.projects.get_project_exist_remote(self.do_name)
-        project.delete()
-
-

Ancestors

- -

Instance variables

-
-
var do_name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def delete_remote(self) -
-
-

Delete the project from Digital Ocean (A project can't be deleted unless it has no resources.)

-

e.g -project.delete_remote()

-
-Source code -
def delete_remote(self):
-    """Delete the project from Digital Ocean (A project can't be deleted unless it has no resources.)
-
-    e.g
-        project.delete_remote()
-    """
-    project = self.parent.projects.get_project_exist_remote(self.do_name)
-    project.delete()
-
-
-
-def deploy(self, purpose, description='', environment='', is_default=False) -
-
-

Create a digital ocean project -e.g -project.deploy(purpose="testing digital ocean client") --> project

-

Args

-

purpose(str): purpose of the project (not optional) -description(str): description of the project, defaults to "" -environment(str): environment of project's resources, defaults to "" -is_default(bool): make this the default project for your user

-

Returns

-
-
project
-
The project object that has been created
-
-
-Source code -
def deploy(self, purpose, description="", environment="", is_default=False):
-    """Create a digital ocean project
-    e.g
-        project.deploy(purpose="testing digital ocean client")  -> project
-    Args:
-        purpose(str): purpose of the project (not optional)
-        description(str): description of the project, defaults to ""
-        environment(str): environment of project's resources, defaults to ""
-        is_default(bool): make this the default project for your user
-
-    Returns:
-        project: The project object that has been created
-    """
-
-    if self.parent.projects.check_project_exist_remote(self.do_name):
-        raise j.exceptions.Value("A project with the same name already exists")
-
-    project = ProjectManagement(
-        token=self.parent.projects.parent_instance.token_,
-        name=self.do_name,
-        purpose=purpose,
-        description=description,
-        environment=environment,
-        is_default=is_default,
-    )
-    project.create()
-
-    if is_default:
-        project.update(is_default=True)
-
-    return project
-
-
-
-def get_digital_ocean_name(self) -
-
-

Get a name for the project which is used on digital ocean -e.g -project.get_digital_ocean_name() --> -"test project DO client"

-

Returns

-
-
str
-
name for the project which is used on digital ocean
-
-
-Source code -
def get_digital_ocean_name(self):
-    """Get a name for the project which is used on digital ocean
-    e.g
-        project.get_digital_ocean_name()  ->  "test project DO client"
-
-    Returns:
-        str: name for the project which is used on digital ocean
-    """
-    return self.do_name
-
-
-
-def set_digital_ocean_name(self, name) -
-
-

Set a name for your project to be used on Digital Ocean -e.g -project.set_digital_ocean_name("test project DO client")

-

Args

-
-
name : str
-
name to be used on digital ocean
-
-
-Source code -
def set_digital_ocean_name(self, name):
-    """Set a name for your project to be used on Digital Ocean
-    e.g
-        project.set_digital_ocean_name("test project DO client")
-
-    Args:
-        name (str): name to be used on digital ocean
-    """
-    self.do_name = name
-
-
-
-

Inherited members

- -
-
-class ProjectFactory -(*args, **kwargs) -
-
-

Stored factories are a custom type of Factory, which uses current configured store backend -to store all instance configurations.

-

get a new stored factory given the type to create and store instances for.

-

Any factory can have a name, parent Base instance and a parent factory.

-

Once a stored factory is created, it tries to lazy-load all current configuration for given type_.

-

Args

-
-
type_ : Base
-
Base class type
-
name_ : str, optional
-
factory name. Defaults to None.
-
parent_instance_ : Base, optional
-
a parent Base instance. Defaults to None.
-
parent_factory_ : Factory, optional
-
a parent Factory. Defaults to None.
-
-
-Source code -
class ProjectFactory(StoredFactory):
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-
-    def list_remote(self):
-        """
-        Returns list of projects on Digital Ocean
-
-        e.g
-            dg.projects.list_remote()  -> list of projects
-
-        Returns
-            list(projects): list of projects on digital ocean
-
-        """
-        return ProjectManagement.list(self.parent_instance.client)
-
-    def check_project_exist_remote(self, name):
-        """
-        Check a project with specific name exits on Digital Ocean
-
-        e.g
-            dg.projects.check_project_exist_remote("codescalers")  -> True
-            dg.projects.check_project_exist_remote("dsrfjsdfjl")  -> False
-
-        Args
-            name (str): name of the project
-
-        Returns
-            bool : True if the project exits and False if the project does not exist on digital ocean
-        """
-        for project in self.list_remote():
-            if project.name == name:
-                return True
-        return False
-
-    def get_project_exist_remote(self, name):
-        """
-        Get a project with specifc name from  Digital Ocean.
-
-        e.g
-            dg.projects.get_project_exist_remote("codescalers")  -> project
-
-        Args
-            name (str): name of the project
-
-        Returns
-            Project : a project from digital ocean with the name specified
-        """
-        for project in self.list_remote():
-            if project.name == name:
-                return project
-        raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-

Ancestors

- -

Methods

-
-
-def check_project_exist_remote(self, name) -
-
-

Check a project with specific name exits on Digital Ocean

-

e.g -dg.projects.check_project_exist_remote("codescalers") --> True -dg.projects.check_project_exist_remote("dsrfjsdfjl") --> False

-

Args -name (str): name of the project

-

Returns -bool : True if the project exits and False if the project does not exist on digital ocean

-
-Source code -
def check_project_exist_remote(self, name):
-    """
-    Check a project with specific name exits on Digital Ocean
-
-    e.g
-        dg.projects.check_project_exist_remote("codescalers")  -> True
-        dg.projects.check_project_exist_remote("dsrfjsdfjl")  -> False
-
-    Args
-        name (str): name of the project
-
-    Returns
-        bool : True if the project exits and False if the project does not exist on digital ocean
-    """
-    for project in self.list_remote():
-        if project.name == name:
-            return True
-    return False
-
-
-
-def get_project_exist_remote(self, name) -
-
-

Get a project with specifc name from -Digital Ocean.

-

e.g -dg.projects.get_project_exist_remote("codescalers") --> project

-

Args -name (str): name of the project

-

Returns -Project : a project from digital ocean with the name specified

-
-Source code -
def get_project_exist_remote(self, name):
-    """
-    Get a project with specifc name from  Digital Ocean.
-
-    e.g
-        dg.projects.get_project_exist_remote("codescalers")  -> project
-
-    Args
-        name (str): name of the project
-
-    Returns
-        Project : a project from digital ocean with the name specified
-    """
-    for project in self.list_remote():
-        if project.name == name:
-            return project
-    raise j.exceptions.Input("could not find project with name:%s on you Digital Ocean account" % name)
-
-
-
-def list_remote(self) -
-
-

Returns list of projects on Digital Ocean

-

e.g -dg.projects.list_remote() --> list of projects

-

Returns -list(projects): list of projects on digital ocean

-
-Source code -
def list_remote(self):
-    """
-    Returns list of projects on Digital Ocean
-
-    e.g
-        dg.projects.list_remote()  -> list of projects
-
-    Returns
-        list(projects): list of projects on digital ocean
-
-    """
-    return ProjectManagement.list(self.parent_instance.client)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/digitalocean/index.html b/docs/api/jumpscale/clients/digitalocean/index.html deleted file mode 100644 index a01704759..000000000 --- a/docs/api/jumpscale/clients/digitalocean/index.html +++ /dev/null @@ -1,104 +0,0 @@ - - - - - - -jumpscale.clients.digitalocean API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.digitalocean

-
-
-
-Source code -
def export_module_as():
-
-    from jumpscale.core.base import StoredFactory
-
-    from .digitalocean import DigitalOcean
-
-    return StoredFactory(DigitalOcean)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.digitalocean.digitalocean
-
-

This module is used to manage your digital ocean account, create droplet,list all the droplets, destroy droplets, create project, list all the …

-
-
jumpscale.clients.digitalocean.project
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-
-    from jumpscale.core.base import StoredFactory
-
-    from .digitalocean import DigitalOcean
-
-    return StoredFactory(DigitalOcean)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/digitalocean/project.html b/docs/api/jumpscale/clients/digitalocean/project.html deleted file mode 100644 index 7c3090bdb..000000000 --- a/docs/api/jumpscale/clients/digitalocean/project.html +++ /dev/null @@ -1,665 +0,0 @@ - - - - - - -jumpscale.clients.digitalocean.project API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.digitalocean.project

-
-
-
-Source code -
from digitalocean import Droplet
-from digitalocean.baseapi import BaseAPI, Error, GET, POST, DELETE, PUT
-
-
-class ProjectManagement(BaseAPI):
-    """Project management
-
-    Attributes accepted at creation time:
-
-    Args:
-        name (str): project name
-        description (str): project size
-        purpose (str): purpose of the project
-        environemnt (str): environment of the project's resources
-
-    Attributes returned by API:
-        * id (int): project id
-        * owner_uuid (str): uuid of the project owner
-        * owner_id (str): id of the project owner
-        * name (str): project name
-        * description (str): project description
-        * purpose (str): project purpose
-        * environment (str): environment of the project's resources
-        * is_default (bool): If true, all resources will be added to this project if no project is specified.
-        * created_at (str): creation date in format u'2014-11-06T10:42:09Z'
-        * updated_at (str): update date in format u'2014-11-06T10:42:09Z'
-
-    """
-
-    def __init__(self, *args, **kwargs):
-        # Defining default values
-        self.id = None
-        self.name = None
-        self.owner_uuid = None
-        self.owner_id = None
-        self.description = None
-        self.purpose = None
-        self.environment = None
-        self.is_default = False
-        self.updated_at = None
-        self.created_at = None
-
-        # This will load also the values passed
-        super(ProjectManagement, self).__init__(*args, **kwargs)
-
-    @classmethod
-    def get_object(cls, api_token, project_id):
-        """Class method that will return a Project object by ID.
-
-        Args:
-            api_token (str): token
-            project_id (int): project id
-        """
-        project = cls(token=api_token, id=project_id)
-        project.load()
-        return project
-
-    @classmethod
-    def list(cls, client):
-
-        data = client.get_data("projects")
-
-        projects = list()
-        for jsoned in data["projects"]:
-            project = cls(**jsoned)
-            project.token = client.token
-
-            projects.append(project)
-
-        return projects
-
-    def load(self):
-        """
-        Fetch data about project - use this instead of get_data()
-        """
-        projects = self.get_data("projects/%s" % self.id)
-        project = projects["project"]
-
-        for attr in project.keys():
-            setattr(self, attr, project[attr])
-
-        return self
-
-    def _update_data(self, project):
-        self.id = project["id"]
-        self.owner_uuid = project["owner_uuid"]
-        self.owner_id = project["owner_id"]
-        self.name = project["name"]
-        self.description = project["description"]
-        self.purpose = project["purpose"]
-        self.environment = project["environment"]
-        self.is_default = project["is_default"]
-        self.created_at = project["created_at"]
-        self.updated_at = project["updated_at"]
-
-    def create(self, *args, **kwargs):
-        """
-        Create the project with object properties.
-
-        Note: Every argument and parameter given to this method will be
-        assigned to the object.
-        """
-        for attr in kwargs.keys():
-            setattr(self, attr, kwargs[attr])
-
-        data = {
-            "name": self.name,
-            "description": self.description,
-            "purpose": self.purpose,
-            "environment": self.environment,
-        }
-
-        data = self.get_data("projects", type=POST, params=data)
-        self._update_data(data["project"])
-
-    def update(self, *args, **kwargs):
-        """
-        Update the project with object properties.
-
-        Note: Every argument and parameter given to this method will be
-        assigned to the object.
-        """
-        for attr in kwargs.keys():
-            setattr(self, attr, kwargs[attr])
-
-        data = {
-            "name": self.name,
-            "description": self.description,
-            "purpose": self.purpose,
-            "environment": self.environment,
-            "is_default": self.is_default,
-        }
-
-        data = self.get_data("projects/%s" % self.id, type=PUT, params=data)
-        self._update_data(data["project"])
-
-    def delete(self):
-        """
-        Delete the project.
-        To be deleted, a project must not have any resources assigned to it. Any existing resources must first be reassigned or destroyed.
-        """
-        self.get_data("projects/%s" % self.id, type=DELETE)
-
-    def list_resources(self):
-        """
-        List all resources in the project
-        """
-        return self.get_data("projects/%s/resources" % self.id)["resources"]
-
-    def list_droplets(self):
-        """
-        List all droplets in the project
-        """
-        resources = self.list_resources()
-        droplets = []
-        for resource in resources:
-            if not resource["urn"].startswith("do:droplet:"):
-                continue
-            droplet_id = resource["urn"].replace("do:droplet:", "")
-            droplet = Droplet.get_object(api_token=self.token, droplet_id=droplet_id)
-            droplets.append(droplet)
-
-        return droplets
-
-    def assign_resources(self, resources):
-        """Assign resources to the project.
-
-        :param resources: A list of uniform resource names (URNs) to be added to a project.
-        :type resources: [str]
-        """
-        self.get_data("projects/%s/resources" % self.id, type=POST, params={"resources": resources})
-
-    def __str__(self):
-        return "<Project: %s %s>" % (self.id, self.name)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class ProjectManagement -(*args, **kwargs) -
-
-

Project management

-

Attributes accepted at creation time:

-

Args

-
-
name : str
-
project name
-
description : str
-
project size
-
purpose : str
-
purpose of the project
-
environemnt : str
-
environment of the project's resources
-
-

Attributes returned by API: -* id (int): project id -* owner_uuid (str): uuid of the project owner -* owner_id (str): id of the project owner -* name (str): project name -* description (str): project description -* purpose (str): project purpose -* environment (str): environment of the project's resources -* is_default (bool): If true, all resources will be added to this project if no project is specified. -* created_at (str): creation date in format u'2014-11-06T10:42:09Z' -* updated_at (str): update date in format u'2014-11-06T10:42:09Z'

-
-Source code -
class ProjectManagement(BaseAPI):
-    """Project management
-
-    Attributes accepted at creation time:
-
-    Args:
-        name (str): project name
-        description (str): project size
-        purpose (str): purpose of the project
-        environemnt (str): environment of the project's resources
-
-    Attributes returned by API:
-        * id (int): project id
-        * owner_uuid (str): uuid of the project owner
-        * owner_id (str): id of the project owner
-        * name (str): project name
-        * description (str): project description
-        * purpose (str): project purpose
-        * environment (str): environment of the project's resources
-        * is_default (bool): If true, all resources will be added to this project if no project is specified.
-        * created_at (str): creation date in format u'2014-11-06T10:42:09Z'
-        * updated_at (str): update date in format u'2014-11-06T10:42:09Z'
-
-    """
-
-    def __init__(self, *args, **kwargs):
-        # Defining default values
-        self.id = None
-        self.name = None
-        self.owner_uuid = None
-        self.owner_id = None
-        self.description = None
-        self.purpose = None
-        self.environment = None
-        self.is_default = False
-        self.updated_at = None
-        self.created_at = None
-
-        # This will load also the values passed
-        super(ProjectManagement, self).__init__(*args, **kwargs)
-
-    @classmethod
-    def get_object(cls, api_token, project_id):
-        """Class method that will return a Project object by ID.
-
-        Args:
-            api_token (str): token
-            project_id (int): project id
-        """
-        project = cls(token=api_token, id=project_id)
-        project.load()
-        return project
-
-    @classmethod
-    def list(cls, client):
-
-        data = client.get_data("projects")
-
-        projects = list()
-        for jsoned in data["projects"]:
-            project = cls(**jsoned)
-            project.token = client.token
-
-            projects.append(project)
-
-        return projects
-
-    def load(self):
-        """
-        Fetch data about project - use this instead of get_data()
-        """
-        projects = self.get_data("projects/%s" % self.id)
-        project = projects["project"]
-
-        for attr in project.keys():
-            setattr(self, attr, project[attr])
-
-        return self
-
-    def _update_data(self, project):
-        self.id = project["id"]
-        self.owner_uuid = project["owner_uuid"]
-        self.owner_id = project["owner_id"]
-        self.name = project["name"]
-        self.description = project["description"]
-        self.purpose = project["purpose"]
-        self.environment = project["environment"]
-        self.is_default = project["is_default"]
-        self.created_at = project["created_at"]
-        self.updated_at = project["updated_at"]
-
-    def create(self, *args, **kwargs):
-        """
-        Create the project with object properties.
-
-        Note: Every argument and parameter given to this method will be
-        assigned to the object.
-        """
-        for attr in kwargs.keys():
-            setattr(self, attr, kwargs[attr])
-
-        data = {
-            "name": self.name,
-            "description": self.description,
-            "purpose": self.purpose,
-            "environment": self.environment,
-        }
-
-        data = self.get_data("projects", type=POST, params=data)
-        self._update_data(data["project"])
-
-    def update(self, *args, **kwargs):
-        """
-        Update the project with object properties.
-
-        Note: Every argument and parameter given to this method will be
-        assigned to the object.
-        """
-        for attr in kwargs.keys():
-            setattr(self, attr, kwargs[attr])
-
-        data = {
-            "name": self.name,
-            "description": self.description,
-            "purpose": self.purpose,
-            "environment": self.environment,
-            "is_default": self.is_default,
-        }
-
-        data = self.get_data("projects/%s" % self.id, type=PUT, params=data)
-        self._update_data(data["project"])
-
-    def delete(self):
-        """
-        Delete the project.
-        To be deleted, a project must not have any resources assigned to it. Any existing resources must first be reassigned or destroyed.
-        """
-        self.get_data("projects/%s" % self.id, type=DELETE)
-
-    def list_resources(self):
-        """
-        List all resources in the project
-        """
-        return self.get_data("projects/%s/resources" % self.id)["resources"]
-
-    def list_droplets(self):
-        """
-        List all droplets in the project
-        """
-        resources = self.list_resources()
-        droplets = []
-        for resource in resources:
-            if not resource["urn"].startswith("do:droplet:"):
-                continue
-            droplet_id = resource["urn"].replace("do:droplet:", "")
-            droplet = Droplet.get_object(api_token=self.token, droplet_id=droplet_id)
-            droplets.append(droplet)
-
-        return droplets
-
-    def assign_resources(self, resources):
-        """Assign resources to the project.
-
-        :param resources: A list of uniform resource names (URNs) to be added to a project.
-        :type resources: [str]
-        """
-        self.get_data("projects/%s/resources" % self.id, type=POST, params={"resources": resources})
-
-    def __str__(self):
-        return "<Project: %s %s>" % (self.id, self.name)
-
-

Ancestors

-
    -
  • digitalocean.BaseAPI
  • -
-

Static methods

-
-
-def get_object(api_token, project_id) -
-
-

Class method that will return a Project object by ID.

-

Args

-
-
api_token : str
-
token
-
project_id : int
-
project id
-
-
-Source code -
@classmethod
-def get_object(cls, api_token, project_id):
-    """Class method that will return a Project object by ID.
-
-    Args:
-        api_token (str): token
-        project_id (int): project id
-    """
-    project = cls(token=api_token, id=project_id)
-    project.load()
-    return project
-
-
-
-def list(client) -
-
-
-
-Source code -
@classmethod
-def list(cls, client):
-
-    data = client.get_data("projects")
-
-    projects = list()
-    for jsoned in data["projects"]:
-        project = cls(**jsoned)
-        project.token = client.token
-
-        projects.append(project)
-
-    return projects
-
-
-
-

Methods

-
-
-def assign_resources(self, resources) -
-
-

Assign resources to the project.

-

:param resources: A list of uniform resource names (URNs) to be added to a project. -:type resources: [str]

-
-Source code -
def assign_resources(self, resources):
-    """Assign resources to the project.
-
-    :param resources: A list of uniform resource names (URNs) to be added to a project.
-    :type resources: [str]
-    """
-    self.get_data("projects/%s/resources" % self.id, type=POST, params={"resources": resources})
-
-
-
-def create(self, *args, **kwargs) -
-
-

Create the project with object properties.

-

Note: Every argument and parameter given to this method will be -assigned to the object.

-
-Source code -
def create(self, *args, **kwargs):
-    """
-    Create the project with object properties.
-
-    Note: Every argument and parameter given to this method will be
-    assigned to the object.
-    """
-    for attr in kwargs.keys():
-        setattr(self, attr, kwargs[attr])
-
-    data = {
-        "name": self.name,
-        "description": self.description,
-        "purpose": self.purpose,
-        "environment": self.environment,
-    }
-
-    data = self.get_data("projects", type=POST, params=data)
-    self._update_data(data["project"])
-
-
-
-def delete(self) -
-
-

Delete the project. -To be deleted, a project must not have any resources assigned to it. Any existing resources must first be reassigned or destroyed.

-
-Source code -
def delete(self):
-    """
-    Delete the project.
-    To be deleted, a project must not have any resources assigned to it. Any existing resources must first be reassigned or destroyed.
-    """
-    self.get_data("projects/%s" % self.id, type=DELETE)
-
-
-
-def list_droplets(self) -
-
-

List all droplets in the project

-
-Source code -
def list_droplets(self):
-    """
-    List all droplets in the project
-    """
-    resources = self.list_resources()
-    droplets = []
-    for resource in resources:
-        if not resource["urn"].startswith("do:droplet:"):
-            continue
-        droplet_id = resource["urn"].replace("do:droplet:", "")
-        droplet = Droplet.get_object(api_token=self.token, droplet_id=droplet_id)
-        droplets.append(droplet)
-
-    return droplets
-
-
-
-def list_resources(self) -
-
-

List all resources in the project

-
-Source code -
def list_resources(self):
-    """
-    List all resources in the project
-    """
-    return self.get_data("projects/%s/resources" % self.id)["resources"]
-
-
-
-def load(self) -
-
-

Fetch data about project - use this instead of get_data()

-
-Source code -
def load(self):
-    """
-    Fetch data about project - use this instead of get_data()
-    """
-    projects = self.get_data("projects/%s" % self.id)
-    project = projects["project"]
-
-    for attr in project.keys():
-        setattr(self, attr, project[attr])
-
-    return self
-
-
-
-def update(self, *args, **kwargs) -
-
-

Update the project with object properties.

-

Note: Every argument and parameter given to this method will be -assigned to the object.

-
-Source code -
def update(self, *args, **kwargs):
-    """
-    Update the project with object properties.
-
-    Note: Every argument and parameter given to this method will be
-    assigned to the object.
-    """
-    for attr in kwargs.keys():
-        setattr(self, attr, kwargs[attr])
-
-    data = {
-        "name": self.name,
-        "description": self.description,
-        "purpose": self.purpose,
-        "environment": self.environment,
-        "is_default": self.is_default,
-    }
-
-    data = self.get_data("projects/%s" % self.id, type=PUT, params=data)
-    self._update_data(data["project"])
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/clients/gdrive/gdrive.html b/docs/api/jumpscale/clients/gdrive/gdrive.html deleted file mode 100644 index d5f84cac2..000000000 --- a/docs/api/jumpscale/clients/gdrive/gdrive.html +++ /dev/null @@ -1,308 +0,0 @@ - - - - - - -jumpscale.clients.gdrive.gdrive API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gdrive.gdrive

-
-
-
-Source code -
from google.oauth2 import service_account
-from googleapiclient.discovery import build
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-
-
-"""
-JS-NG> cl = j.clients.gdrive.new("name")
-JS-NG> cl.credfile = "/Downloads/pelagic-core-251306-8b2323198535.json"
-JS-NG> cl.get_file('1kUHHSjtPNUN2dAJQSAeCWMvrZzUO2YNW')
-{'kind': 'drive#file', 'id': '1kUHHSjtPNUN2dAJQSAeCWMvrZzUO2YNW', 'name': 'my.txt', 'mimeType': 'text/plain'}
-
-cl.files.get_media(fileId='1kUHHSjtPNUN2dAJQSAeCWMvrZzUO2YNW')
-
-JS-NG> cl.get_service('drive', 'v3')
-<googleapiclient.discovery.Resource object at 0x7f3fa8982240>
-"""
-
-
-SCOPES = [
-    "https://www.googleapis.com/auth/drive",
-    "https://www.googleapis.com/auth/drive.file",
-    "https://www.googleapis.com/auth/drive.appdata",
-    "https://www.googleapis.com/auth/drive.scripts",
-    "https://www.googleapis.com/auth/drive.metadata",
-]
-
-DRIVE_BUILD_VERSION = "v3"
-
-
-class GdriveClient(Client):
-    credfile = fields.String()
-
-    def __init__(self):
-        self.__credentials = None
-        self.__files = None
-        super().__init__()
-
-    @property
-    def credentials(self):
-        if not self.__credentials:
-            self.__credentials = service_account.Credentials.from_service_account_file(
-                self.credfile, scopes=SCOPES
-            )
-        return self.__credentials
-
-    @property
-    def files(self):
-        if not self.__files:
-            drive = self.get_service("drive", DRIVE_BUILD_VERSION)
-            self.__files = drive.files()
-        return self.__files
-
-    def get_service(self, name, version):
-        return build(name, version, credentials=self.credentials)
-
-    def get_file(self, file_id):
-        return self.files.get(fileId=file_id).execute()
-
-    def export_pdf(self, file_id, export_path):
-        response = self.files.export_media(fileId=file_id, mimeType="application/pdf").execute()
-        with open(export_path, "wb") as expr:
-            expr.write(response)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class GdriveClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class GdriveClient(Client):
-    credfile = fields.String()
-
-    def __init__(self):
-        self.__credentials = None
-        self.__files = None
-        super().__init__()
-
-    @property
-    def credentials(self):
-        if not self.__credentials:
-            self.__credentials = service_account.Credentials.from_service_account_file(
-                self.credfile, scopes=SCOPES
-            )
-        return self.__credentials
-
-    @property
-    def files(self):
-        if not self.__files:
-            drive = self.get_service("drive", DRIVE_BUILD_VERSION)
-            self.__files = drive.files()
-        return self.__files
-
-    def get_service(self, name, version):
-        return build(name, version, credentials=self.credentials)
-
-    def get_file(self, file_id):
-        return self.files.get(fileId=file_id).execute()
-
-    def export_pdf(self, file_id, export_path):
-        response = self.files.export_media(fileId=file_id, mimeType="application/pdf").execute()
-        with open(export_path, "wb") as expr:
-            expr.write(response)
-
-

Ancestors

- -

Instance variables

-
-
var credentials
-
-
-
-Source code -
@property
-def credentials(self):
-    if not self.__credentials:
-        self.__credentials = service_account.Credentials.from_service_account_file(
-            self.credfile, scopes=SCOPES
-        )
-    return self.__credentials
-
-
-
var credfile
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var files
-
-
-
-Source code -
@property
-def files(self):
-    if not self.__files:
-        drive = self.get_service("drive", DRIVE_BUILD_VERSION)
-        self.__files = drive.files()
-    return self.__files
-
-
-
-

Methods

-
-
-def export_pdf(self, file_id, export_path) -
-
-
-
-Source code -
def export_pdf(self, file_id, export_path):
-    response = self.files.export_media(fileId=file_id, mimeType="application/pdf").execute()
-    with open(export_path, "wb") as expr:
-        expr.write(response)
-
-
-
-def get_file(self, file_id) -
-
-
-
-Source code -
def get_file(self, file_id):
-    return self.files.get(fileId=file_id).execute()
-
-
-
-def get_service(self, name, version) -
-
-
-
-Source code -
def get_service(self, name, version):
-    return build(name, version, credentials=self.credentials)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/gdrive/index.html b/docs/api/jumpscale/clients/gdrive/index.html deleted file mode 100644 index 79e86bfac..000000000 --- a/docs/api/jumpscale/clients/gdrive/index.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.clients.gdrive API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gdrive

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .gdrive import GdriveClient
-
-    return StoredFactory(GdriveClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.gdrive.gdrive
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .gdrive import GdriveClient
-
-    return StoredFactory(GdriveClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/gedis/gedis.html b/docs/api/jumpscale/clients/gedis/gedis.html deleted file mode 100644 index bbb47cac6..000000000 --- a/docs/api/jumpscale/clients/gedis/gedis.html +++ /dev/null @@ -1,721 +0,0 @@ - - - - - - -jumpscale.clients.gedis.gedis API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gedis.gedis

-
-
-
-Source code -
import inspect
-import json
-import os
-import sys
-from functools import partial
-
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-from jumpscale.loader import j
-from jumpscale.servers.gedis.server import GedisErrorTypes, deserialize, serialize
-from jumpscale.tools.codeloader import load_python_module
-
-
-class ActorResult:
-    def __init__(self, **kwargs):
-        self.success = kwargs.get("success", True)
-        self.result = kwargs.get("result", None)
-        self.error = kwargs.get("error", None)
-        self.error_type = kwargs.get("error_type", None)
-        self.is_async = kwargs.get("is_async", False)
-        self.task_id = kwargs.get("task_id", None)
-
-    def __dir__(self):
-        return list(self.__dict__.keys())
-
-    def __repr__(self):
-        return str(self.__dict__)
-
-
-class ActorProxy:
-    def __init__(self, actor_name, actor_info, client):
-        """ActorProxy to remote actor on the server side
-
-        Arguments:
-            actor_name {str} -- [description]
-            actor_info {dict} -- actor information dict e.g { method_name: { args: [], 'doc':...} }
-            gedis_client {GedisClient} -- gedis client reference
-        """
-        self.actor_name = actor_name
-        self.actor_info = actor_info
-        self.client = client
-
-    def __dir__(self):
-        """Delegate the available functions on the ActorProxy to `actor_info` keys
-
-        Returns:
-            list -- methods available on the ActorProxy
-        """
-        return list(self.actor_info["methods"].keys())
-
-    def __getattr__(self, method):
-        """Return a function representing the remote function on the actual actor
-
-        Arguments:
-            attr {str} -- method name
-
-        Returns:
-            function -- function waiting on the arguments
-        """
-
-        def function(*args, **kwargs):
-            return self.client.execute(self.actor_name, method, *args, **kwargs)
-
-        func = partial(function)
-        func.__doc__ = self.actor_info["methods"][method]["doc"]
-        return func
-
-
-class ActorsCollection:
-    def __init__(self, actors):
-        self._actors = actors
-
-    def __dir__(self):
-        return list(self._actors.keys())
-
-    def __getattr__(self, actor_name):
-        if actor_name in self._actors:
-            return self._actors[actor_name]
-
-
-class GedisClient(Client):
-    name = fields.String(default="local")
-    hostname = fields.String(default="localhost")
-    port = fields.Integer(default=16000)
-    raise_on_error = fields.Boolean(default=False)
-    disable_deserialization = fields.Boolean(default=False)
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-        self._redisclient = None
-        self._loaded_actors = {}
-        self._loaded_modules = []
-        self.actors = None
-        self._load_actors()
-
-    @property
-    def redis_client(self):
-        if self._redisclient is None:
-            self._redisclient = j.clients.redis.get(name=f"gedis_{self.name}", hostname=self.hostname, port=self.port)
-        return self._redisclient
-
-    def _load_module(self, path, force_reload=False):
-        load_python_module(path, force_reload=force_reload)
-        if path not in self._loaded_modules:
-            self._loaded_modules.append(path)
-
-    def _load_actors(self, force_reload=False):
-        self._loaded_actors = {}
-        for actor_name in self.list_actors():
-            actor_info = self._get_actor_info(actor_name)
-            self._load_module(actor_info["path"], force_reload=force_reload)
-            self._loaded_actors[actor_name] = ActorProxy(actor_name, actor_info, self)
-
-        self.actors = ActorsCollection(self._loaded_actors)
-
-    def _get_actor_info(self, actor_name):
-        return self.execute(actor_name, "info", die=True).result
-
-    def list_actors(self) -> list:
-        """List actors
-
-        Returns:
-            list -- List of loaded actors
-        """
-        return self.execute("core", "list_actors", die=True).result
-
-    def reload(self):
-        """Reload actors
-        """
-        self._load_actors(force_reload=True)
-
-    def execute(self, actor_name: str, actor_method: str, *args, die: bool = False, **kwargs) -> ActorResult:
-        """Execute actor's method
-
-        Arguments:
-            actor_name {str} -- actor name
-            actor_method {str} -- actor method
-
-        Keyword Arguments:
-            die {bool} --  flag to raise an error when request fails (default: {False})
-
-        Raises:
-            RemoteException: Raises if the request failed and raise_on_error flag is set
-
-        Returns:
-            ActorResult -- request result
-        """
-        payload = json.dumps((args, kwargs), default=serialize)
-        response = self.redis_client.execute_command(actor_name, actor_method, payload)
-
-        deserializer = deserialize if not self.disable_deserialization else None
-        response = json.loads(response, object_hook=deserializer)
-
-        if not response["success"]:
-            if die or self.raise_on_error:
-                raise RemoteException(response["error"])
-
-            response["error_type"] = GedisErrorTypes(response["error_type"])
-
-        return ActorResult(**response)
-
-
-class RemoteException(Exception):
-    pass
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class ActorProxy -(actor_name, actor_info, client) -
-
-

ActorProxy to remote actor on the server side

-

Arguments

-

actor_name {str} – [description] -actor_info {dict} – actor information dict e.g { method_name: { args: [], 'doc':…} } -gedis_client {GedisClient} – gedis client reference

-
-Source code -
class ActorProxy:
-    def __init__(self, actor_name, actor_info, client):
-        """ActorProxy to remote actor on the server side
-
-        Arguments:
-            actor_name {str} -- [description]
-            actor_info {dict} -- actor information dict e.g { method_name: { args: [], 'doc':...} }
-            gedis_client {GedisClient} -- gedis client reference
-        """
-        self.actor_name = actor_name
-        self.actor_info = actor_info
-        self.client = client
-
-    def __dir__(self):
-        """Delegate the available functions on the ActorProxy to `actor_info` keys
-
-        Returns:
-            list -- methods available on the ActorProxy
-        """
-        return list(self.actor_info["methods"].keys())
-
-    def __getattr__(self, method):
-        """Return a function representing the remote function on the actual actor
-
-        Arguments:
-            attr {str} -- method name
-
-        Returns:
-            function -- function waiting on the arguments
-        """
-
-        def function(*args, **kwargs):
-            return self.client.execute(self.actor_name, method, *args, **kwargs)
-
-        func = partial(function)
-        func.__doc__ = self.actor_info["methods"][method]["doc"]
-        return func
-
-
-
-class ActorResult -(**kwargs) -
-
-
-
-Source code -
class ActorResult:
-    def __init__(self, **kwargs):
-        self.success = kwargs.get("success", True)
-        self.result = kwargs.get("result", None)
-        self.error = kwargs.get("error", None)
-        self.error_type = kwargs.get("error_type", None)
-        self.is_async = kwargs.get("is_async", False)
-        self.task_id = kwargs.get("task_id", None)
-
-    def __dir__(self):
-        return list(self.__dict__.keys())
-
-    def __repr__(self):
-        return str(self.__dict__)
-
-
-
-class ActorsCollection -(actors) -
-
-
-
-Source code -
class ActorsCollection:
-    def __init__(self, actors):
-        self._actors = actors
-
-    def __dir__(self):
-        return list(self._actors.keys())
-
-    def __getattr__(self, actor_name):
-        if actor_name in self._actors:
-            return self._actors[actor_name]
-
-
-
-class GedisClient -(*args, **kwargs) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class GedisClient(Client):
-    name = fields.String(default="local")
-    hostname = fields.String(default="localhost")
-    port = fields.Integer(default=16000)
-    raise_on_error = fields.Boolean(default=False)
-    disable_deserialization = fields.Boolean(default=False)
-
-    def __init__(self, *args, **kwargs):
-        super().__init__(*args, **kwargs)
-        self._redisclient = None
-        self._loaded_actors = {}
-        self._loaded_modules = []
-        self.actors = None
-        self._load_actors()
-
-    @property
-    def redis_client(self):
-        if self._redisclient is None:
-            self._redisclient = j.clients.redis.get(name=f"gedis_{self.name}", hostname=self.hostname, port=self.port)
-        return self._redisclient
-
-    def _load_module(self, path, force_reload=False):
-        load_python_module(path, force_reload=force_reload)
-        if path not in self._loaded_modules:
-            self._loaded_modules.append(path)
-
-    def _load_actors(self, force_reload=False):
-        self._loaded_actors = {}
-        for actor_name in self.list_actors():
-            actor_info = self._get_actor_info(actor_name)
-            self._load_module(actor_info["path"], force_reload=force_reload)
-            self._loaded_actors[actor_name] = ActorProxy(actor_name, actor_info, self)
-
-        self.actors = ActorsCollection(self._loaded_actors)
-
-    def _get_actor_info(self, actor_name):
-        return self.execute(actor_name, "info", die=True).result
-
-    def list_actors(self) -> list:
-        """List actors
-
-        Returns:
-            list -- List of loaded actors
-        """
-        return self.execute("core", "list_actors", die=True).result
-
-    def reload(self):
-        """Reload actors
-        """
-        self._load_actors(force_reload=True)
-
-    def execute(self, actor_name: str, actor_method: str, *args, die: bool = False, **kwargs) -> ActorResult:
-        """Execute actor's method
-
-        Arguments:
-            actor_name {str} -- actor name
-            actor_method {str} -- actor method
-
-        Keyword Arguments:
-            die {bool} --  flag to raise an error when request fails (default: {False})
-
-        Raises:
-            RemoteException: Raises if the request failed and raise_on_error flag is set
-
-        Returns:
-            ActorResult -- request result
-        """
-        payload = json.dumps((args, kwargs), default=serialize)
-        response = self.redis_client.execute_command(actor_name, actor_method, payload)
-
-        deserializer = deserialize if not self.disable_deserialization else None
-        response = json.loads(response, object_hook=deserializer)
-
-        if not response["success"]:
-            if die or self.raise_on_error:
-                raise RemoteException(response["error"])
-
-            response["error_type"] = GedisErrorTypes(response["error_type"])
-
-        return ActorResult(**response)
-
-

Ancestors

- -

Instance variables

-
-
var disable_deserialization
-
-

getter method this property

-

will call _get_value, which would if the value is already defined -and will get the default value if not

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    will call `_get_value`, which would if the value is already defined
-    and will get the default value if not
-
-    Returns:
-        any: the field value
-    """
-    return self._get_value(name, field)
-
-
-
var hostname
-
-

getter method this property

-

will call _get_value, which would if the value is already defined -and will get the default value if not

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    will call `_get_value`, which would if the value is already defined
-    and will get the default value if not
-
-    Returns:
-        any: the field value
-    """
-    return self._get_value(name, field)
-
-
-
var name
-
-

getter method this property

-

will call _get_value, which would if the value is already defined -and will get the default value if not

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    will call `_get_value`, which would if the value is already defined
-    and will get the default value if not
-
-    Returns:
-        any: the field value
-    """
-    return self._get_value(name, field)
-
-
-
var port
-
-

getter method this property

-

will call _get_value, which would if the value is already defined -and will get the default value if not

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    will call `_get_value`, which would if the value is already defined
-    and will get the default value if not
-
-    Returns:
-        any: the field value
-    """
-    return self._get_value(name, field)
-
-
-
var raise_on_error
-
-

getter method this property

-

will call _get_value, which would if the value is already defined -and will get the default value if not

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    will call `_get_value`, which would if the value is already defined
-    and will get the default value if not
-
-    Returns:
-        any: the field value
-    """
-    return self._get_value(name, field)
-
-
-
var redis_client
-
-
-
-Source code -
@property
-def redis_client(self):
-    if self._redisclient is None:
-        self._redisclient = j.clients.redis.get(name=f"gedis_{self.name}", hostname=self.hostname, port=self.port)
-    return self._redisclient
-
-
-
-

Methods

-
-
-def execute(self, actor_name, actor_method, *args, die=False, **kwargs) -
-
-

Execute actor's method

-

Arguments

-

actor_name {str} – actor name -actor_method {str} – actor method -Keyword Arguments: -die {bool} – -flag to raise an error when request fails (default: {False})

-

Raises

-
-
RemoteException
-
Raises if the request failed and raise_on_error flag is set
-
-

Returns

-
-
ActorResultrequest result
-
 
-
-
-Source code -
def execute(self, actor_name: str, actor_method: str, *args, die: bool = False, **kwargs) -> ActorResult:
-    """Execute actor's method
-
-    Arguments:
-        actor_name {str} -- actor name
-        actor_method {str} -- actor method
-
-    Keyword Arguments:
-        die {bool} --  flag to raise an error when request fails (default: {False})
-
-    Raises:
-        RemoteException: Raises if the request failed and raise_on_error flag is set
-
-    Returns:
-        ActorResult -- request result
-    """
-    payload = json.dumps((args, kwargs), default=serialize)
-    response = self.redis_client.execute_command(actor_name, actor_method, payload)
-
-    deserializer = deserialize if not self.disable_deserialization else None
-    response = json.loads(response, object_hook=deserializer)
-
-    if not response["success"]:
-        if die or self.raise_on_error:
-            raise RemoteException(response["error"])
-
-        response["error_type"] = GedisErrorTypes(response["error_type"])
-
-    return ActorResult(**response)
-
-
-
-def list_actors(self) -
-
-

List actors

-

Returns

-
-
listList of loaded actors
-
 
-
-
-Source code -
def list_actors(self) -> list:
-    """List actors
-
-    Returns:
-        list -- List of loaded actors
-    """
-    return self.execute("core", "list_actors", die=True).result
-
-
-
-def reload(self) -
-
-

Reload actors

-
-Source code -
def reload(self):
-    """Reload actors
-    """
-    self._load_actors(force_reload=True)
-
-
-
-

Inherited members

- -
-
-class RemoteException -(*args, **kwargs) -
-
-

Common base class for all non-exit exceptions.

-
-Source code -
class RemoteException(Exception):
-    pass
-
-

Ancestors

-
    -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/clients/gedis/index.html b/docs/api/jumpscale/clients/gedis/index.html deleted file mode 100644 index 4dc00a8e5..000000000 --- a/docs/api/jumpscale/clients/gedis/index.html +++ /dev/null @@ -1,238 +0,0 @@ - - - - - - -jumpscale.clients.gedis API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gedis

-
-
-

This module gives you all the facilities to communicate with gedis server

-

Connecting to a gedis server

-
JS-NG> gedis = j.clients.gedis.get("local")
-JS-NG> gedis.list_actors()
-['system']
-
-

Registering actor

-
JS-NG> gedis.actors.system.register_actor("greeter", "/home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py")
-1
-
-

Listing actors

-
JS-NG> gedis.list_actors()
-['system', 'greeter']
-
-

Documentation of an actor

-
JS-NG> gedis.ppdoc("greeter")
-{
-  "add2": {
-    "args": [
-      "a",
-      "b"
-    ],
-    "doc": "Add two args
-
-        "
-  },
-  "hi": {
-    "args": [],
-    "doc": "returns hello world
-        "
-  },
-  "info": {
-    "args": [
-      "result",
-      "members",
-      "name",
-      "attr"
-    ],
-    "doc": ""
-  },
-  "ping": {
-    "args": [],
-    "doc": "
-
-        "
-  }
-}
-
-

Invoking an actor method

-
JS-NG> gedis.execute("greeter", "hi")
-b'hello world'
-
-JS-NG> gedis.execute("greeter", "ping")
-b'pong no?'
-
-JS-NG> gedis.execute("greeter", "add2", "first", "second")
-b'firstsecond'
-
-

Invoking actor method with attribute access

-
JS-NG> gedis.actors.greeter.hi()
-b'hello world'
-
-JS-NG> gedis.actors.greeter.add2("a", "b")
-b'ab'
-
-
-Source code -
"""This module gives you all the facilities to communicate with gedis server
-
-Connecting to a gedis server
-```
-JS-NG> gedis = j.clients.gedis.get("local")
-JS-NG> gedis.list_actors()
-['system']
-```
-
-Registering actor
-```
-JS-NG> gedis.actors.system.register_actor("greeter", "/home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py")
-1
-```
-
-Listing actors
-```
-JS-NG> gedis.list_actors()
-['system', 'greeter']
-```
-
-Documentation of an actor
-
-```
-JS-NG> gedis.ppdoc("greeter")
-{
-  "add2": {
-    "args": [
-      "a",
-      "b"
-    ],
-    "doc": "Add two args\n        \n        "
-  },
-  "hi": {
-    "args": [],
-    "doc": "returns hello world\n        "
-  },
-  "info": {
-    "args": [
-      "result",
-      "members",
-      "name",
-      "attr"
-    ],
-    "doc": ""
-  },
-  "ping": {
-    "args": [],
-    "doc": "\n        \n        "
-  }
-}
-```
-Invoking an actor method
-```
-JS-NG> gedis.execute("greeter", "hi")
-b'hello world'
-
-JS-NG> gedis.execute("greeter", "ping")
-b'pong no?'
-
-JS-NG> gedis.execute("greeter", "add2", "first", "second")
-b'firstsecond'
-```
-Invoking actor method with attribute access
-```
-JS-NG> gedis.actors.greeter.hi()
-b'hello world'
-
-JS-NG> gedis.actors.greeter.add2("a", "b")
-b'ab'
-```
-"""
-
-
-def export_module_as():
-
-    from jumpscale.core.base import StoredFactory
-
-    from .gedis import GedisClient
-
-    return StoredFactory(GedisClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.gedis.gedis
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-
-    from jumpscale.core.base import StoredFactory
-
-    from .gedis import GedisClient
-
-    return StoredFactory(GedisClient)
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/clients/github/base.html b/docs/api/jumpscale/clients/github/base.html deleted file mode 100644 index a26cafd8e..000000000 --- a/docs/api/jumpscale/clients/github/base.html +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - -jumpscale.clients.github.base API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github.base

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import Base, fields
-from jumpscale.loader import j
-
-replacelabels = {
-    "bug": "type_bug",
-    "duplicate": "process_duplicate",
-    "enhancement": "type_feature",
-    "help wanted": "state_question",
-    "invalid": "state_question",
-    "question": "state_question",
-    "wontfix": "process_wontfix",
-    "completed": "state_verification",
-    "in progress": "state_inprogress",
-    "ready": "state_verification",
-    "story": "type_story",
-    "urgent": "priority_urgent",
-    "type_bug": "type_unknown",
-    "type_story": "type_unknown",
-}
-
-
-class base(Base):
-    def __init__(self):
-        super().__init__()
-
-    @property
-    def body_without_tags(self):
-        # remove the tag lines from the body
-        out = ""
-        if self.body is None:
-            return ""
-        for line in self.body.split("\n"):
-            if line.startswith("##") and not line.startswith("###"):
-                continue
-            out += "%s\n" % line
-
-        out = out.rstrip() + "\n"
-        return out
-
-    # @tags.setter
-    # def tags(self, ddict):
-    #     if isinstance(ddict,dict) is False:
-    #         raise Exception("Tags need to be dict as input for setter, now:%s" % ddict)
-
-    #     keys = sorted(ddict.keys())
-
-    #     out = self.body_without_tags + "\n"
-    #     for key, val in ddict.items():
-    #         out += ".. %s:%s\n" % (key, val)
-
-    #     self.body = out
-    #     return self.tags
-
-    def __str__(self):
-        return str(self._ddict)
-
-    __repr__ = __str__
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class base -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class base(Base):
-    def __init__(self):
-        super().__init__()
-
-    @property
-    def body_without_tags(self):
-        # remove the tag lines from the body
-        out = ""
-        if self.body is None:
-            return ""
-        for line in self.body.split("\n"):
-            if line.startswith("##") and not line.startswith("###"):
-                continue
-            out += "%s\n" % line
-
-        out = out.rstrip() + "\n"
-        return out
-
-    # @tags.setter
-    # def tags(self, ddict):
-    #     if isinstance(ddict,dict) is False:
-    #         raise Exception("Tags need to be dict as input for setter, now:%s" % ddict)
-
-    #     keys = sorted(ddict.keys())
-
-    #     out = self.body_without_tags + "\n"
-    #     for key, val in ddict.items():
-    #         out += ".. %s:%s\n" % (key, val)
-
-    #     self.body = out
-    #     return self.tags
-
-    def __str__(self):
-        return str(self._ddict)
-
-    __repr__ = __str__
-
-

Ancestors

-
    -
  • Base
  • -
  • types.SimpleNamespace
  • -
-

Subclasses

- -

Instance variables

-
-
var body_without_tags
-
-
-
-Source code -
@property
-def body_without_tags(self):
-    # remove the tag lines from the body
-    out = ""
-    if self.body is None:
-        return ""
-    for line in self.body.split("\n"):
-        if line.startswith("##") and not line.startswith("###"):
-            continue
-        out += "%s\n" % line
-
-    out = out.rstrip() + "\n"
-    return out
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/github/github.html b/docs/api/jumpscale/clients/github/github.html deleted file mode 100644 index e66e0fff9..000000000 --- a/docs/api/jumpscale/clients/github/github.html +++ /dev/null @@ -1,462 +0,0 @@ - - - - - - -jumpscale.clients.github.github API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github.github

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import Base, fields
-from jumpscale.loader import j
-from .repo import GithubRepo
-from github import Github, GithubObject
-
-NotSet = GithubObject.NotSet
-
-
-class GithubClient(Client):
-    username = fields.String()
-    password = fields.String()
-    accesstoken = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def github_client(self):
-        if not self.__client:
-            if self.accesstoken:
-                self.__client = Github(self.accesstoken)
-            else:
-                self.__client = Github(login_or_token=self.username, password=self.password)
-        return self.__client
-
-    def get_repo(self, repo_full_name):
-        return GithubRepo(self.__client,repo_full_name)
-
-    def get_repos(self):
-        l = []
-        for r in self.github_client.get_user().get_repos():
-            l.append(GithubRepo(self.__client,r.full_name))
-        return l
-
-    def get_orgs(self):
-        l = []
-        for o in self.github_client.get_user().get_orgs():
-            l.append(o.login)
-        return l
-
-    def get_userdata(self):
-        u = self.github_client.get_user()
-        el = []
-        for e in u.get_emails():
-            el.append(e)
-        return {"name": u.name, "emails": el, "id": u.id, "avatar_url": u.avatar_url}
-
-    def create_repo(
-        self,
-        name,
-        description=NotSet,
-        homepage=NotSet,
-        private=NotSet,
-        has_issues=NotSet,
-        has_wiki=NotSet,
-        has_downloads=NotSet,
-        auto_init=NotSet,
-        gitignore_template=NotSet,
-    ):
-
-        return self.github_client.get_user().create_repo(
-            name,
-            description=description,
-            homepage=homepage,
-            private=private,
-            has_issues=has_issues,
-            has_wiki=has_wiki,
-            has_downloads=has_downloads,
-            auto_init=auto_init,
-            gitignore_template=gitignore_template,
-        )
-
-    def delete_repo(self, repo_name):
-        return self.__client.get_user().get_repo(repo_name).delete()
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class GithubClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class GithubClient(Client):
-    username = fields.String()
-    password = fields.String()
-    accesstoken = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def github_client(self):
-        if not self.__client:
-            if self.accesstoken:
-                self.__client = Github(self.accesstoken)
-            else:
-                self.__client = Github(login_or_token=self.username, password=self.password)
-        return self.__client
-
-    def get_repo(self, repo_full_name):
-        return GithubRepo(self.__client,repo_full_name)
-
-    def get_repos(self):
-        l = []
-        for r in self.github_client.get_user().get_repos():
-            l.append(GithubRepo(self.__client,r.full_name))
-        return l
-
-    def get_orgs(self):
-        l = []
-        for o in self.github_client.get_user().get_orgs():
-            l.append(o.login)
-        return l
-
-    def get_userdata(self):
-        u = self.github_client.get_user()
-        el = []
-        for e in u.get_emails():
-            el.append(e)
-        return {"name": u.name, "emails": el, "id": u.id, "avatar_url": u.avatar_url}
-
-    def create_repo(
-        self,
-        name,
-        description=NotSet,
-        homepage=NotSet,
-        private=NotSet,
-        has_issues=NotSet,
-        has_wiki=NotSet,
-        has_downloads=NotSet,
-        auto_init=NotSet,
-        gitignore_template=NotSet,
-    ):
-
-        return self.github_client.get_user().create_repo(
-            name,
-            description=description,
-            homepage=homepage,
-            private=private,
-            has_issues=has_issues,
-            has_wiki=has_wiki,
-            has_downloads=has_downloads,
-            auto_init=auto_init,
-            gitignore_template=gitignore_template,
-        )
-
-    def delete_repo(self, repo_name):
-        return self.__client.get_user().get_repo(repo_name).delete()
-
-

Ancestors

- -

Instance variables

-
-
var accesstoken
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var github_client
-
-
-
-Source code -
@property
-def github_client(self):
-    if not self.__client:
-        if self.accesstoken:
-            self.__client = Github(self.accesstoken)
-        else:
-            self.__client = Github(login_or_token=self.username, password=self.password)
-    return self.__client
-
-
-
var password
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var username
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def create_repo(self, name, description=NotSet, homepage=NotSet, private=NotSet, has_issues=NotSet, has_wiki=NotSet, has_downloads=NotSet, auto_init=NotSet, gitignore_template=NotSet) -
-
-
-
-Source code -
def create_repo(
-    self,
-    name,
-    description=NotSet,
-    homepage=NotSet,
-    private=NotSet,
-    has_issues=NotSet,
-    has_wiki=NotSet,
-    has_downloads=NotSet,
-    auto_init=NotSet,
-    gitignore_template=NotSet,
-):
-
-    return self.github_client.get_user().create_repo(
-        name,
-        description=description,
-        homepage=homepage,
-        private=private,
-        has_issues=has_issues,
-        has_wiki=has_wiki,
-        has_downloads=has_downloads,
-        auto_init=auto_init,
-        gitignore_template=gitignore_template,
-    )
-
-
-
-def delete_repo(self, repo_name) -
-
-
-
-Source code -
def delete_repo(self, repo_name):
-    return self.__client.get_user().get_repo(repo_name).delete()
-
-
-
-def get_orgs(self) -
-
-
-
-Source code -
def get_orgs(self):
-    l = []
-    for o in self.github_client.get_user().get_orgs():
-        l.append(o.login)
-    return l
-
-
-
-def get_repo(self, repo_full_name) -
-
-
-
-Source code -
def get_repo(self, repo_full_name):
-    return GithubRepo(self.__client,repo_full_name)
-
-
-
-def get_repos(self) -
-
-
-
-Source code -
def get_repos(self):
-    l = []
-    for r in self.github_client.get_user().get_repos():
-        l.append(GithubRepo(self.__client,r.full_name))
-    return l
-
-
-
-def get_userdata(self) -
-
-
-
-Source code -
def get_userdata(self):
-    u = self.github_client.get_user()
-    el = []
-    for e in u.get_emails():
-        el.append(e)
-    return {"name": u.name, "emails": el, "id": u.id, "avatar_url": u.avatar_url}
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/github/index.html b/docs/api/jumpscale/clients/github/index.html deleted file mode 100644 index df2c483d0..000000000 --- a/docs/api/jumpscale/clients/github/index.html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - -jumpscale.clients.github API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .github import GithubClient
-
-    return StoredFactory(GithubClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.github.base
-
-
-
-
jumpscale.clients.github.github
-
-
-
-
jumpscale.clients.github.issue
-
-
-
-
jumpscale.clients.github.milestone
-
-
-
-
jumpscale.clients.github.repo
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .github import GithubClient
-
-    return StoredFactory(GithubClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/github/issue.html b/docs/api/jumpscale/clients/github/issue.html deleted file mode 100644 index 67e1d1277..000000000 --- a/docs/api/jumpscale/clients/github/issue.html +++ /dev/null @@ -1,1090 +0,0 @@ - - - - - - -jumpscale.clients.github.issue API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github.issue

-
-
-
-Source code -
from jumpscale.loader import j
-from .base import base
-from .base import replacelabels
-from .milestone import RepoMilestone
-
-
-class Issue(base):
-    def __init__(self, repo, ddict={}, githubObj=None):
-        base.__init__(self)
-        self.repo = repo
-        self._ddict = ddict
-        self._githubObj = githubObj
-        self._comments = ddict.get("comments", None)
-        if githubObj is not None:
-            self.load()
-
-        self._lock = threading.RLock()
-        # self.todo
-
-    @property
-    def api(self):
-        if self._githubObj is None:
-            self._githubObj = self.repo.api.get_issue(self.number)
-        return self._githubObj
-
-    @property
-    def ddict(self):
-        if self._ddict == {}:
-            # no dict yet, fetch from github
-            self.load()
-        # we lazy load the comments. so it's only loaded when accesses
-        self._ddict["comments"] = self.comments
-        return self._ddict
-
-    @property
-    def comments(self):
-        if self._comments is not None:
-            return self._comments
-
-        with self._lock:
-            if self._comments is None:
-                self._log_debug("Loading comments for issue: %s" % self.number)
-                self._comments = []
-                for comment in self.api.get_comments():
-                    obj = {}
-                    user = self.repo.client.getUserLogin(githubObj=comment.user)
-                    obj["user"] = user
-                    obj["url"] = comment.url
-                    obj["id"] = comment.id
-                    obj["body"] = comment.body
-                    obj["user_id"] = comment.user.id
-                    # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-                    self._comments.append(obj)
-        return self._comments
-
-    def reload_comments(self):
-        with self._lock:
-            self._comments = []
-            for comment in self.api.get_comments():
-                obj = {}
-                user = self.repo.client.getUserLogin(githubObj=comment.user)
-                obj["user"] = user
-                obj["url"] = comment.url
-                obj["id"] = comment.id
-                obj["body"] = comment.body
-                # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-                self._comments.append(obj)
-        return self._comments
-
-    @property
-    def guid(self):
-        return self.repo.fullname + "_" + str(self._ddict["number"])
-
-    @property
-    def number(self):
-        return int(self._ddict["number"])
-
-    @property
-    def title(self):
-        return self._ddict["title"]
-
-    @property
-    def body(self):
-        return self._ddict["body"]
-
-    @body.setter
-    def body(self, val):
-        self._ddict["body"] = val
-        try:
-            self.api.edit(body=self._ddict["body"])
-        except Exception as e:
-            self._log_error("Failed to update the issue body: %s" % e)
-
-    @property
-    def time(self):
-        return self._ddict["time"]
-
-    @property
-    def url(self):
-        return self._ddict["url"]
-
-    @property
-    def assignee(self):
-        return self._ddict["assignee"]
-
-    @property
-    def labels(self):
-        # we return a copy so changing the list doesn't actually change the
-        # ddict value
-        return self._ddict["labels"][:]
-
-    @property
-    def id(self):
-        return self._ddict["id"]
-
-    @labels.setter
-    def labels(self, val):
-        # check if all are already in labels, if yes nothing to do
-        if len(val) == len(self._ddict["labels"]):
-            self._ddict["labels"].sort()
-            val.sort()
-            if val == self._ddict["labels"]:
-                return
-        self._ddict["labels"] = val
-        toset = [self.repo.getLabel(item) for item in self._ddict["labels"]]
-        self.api.set_labels(*toset)
-
-    @property
-    def milestone(self):
-        return self._ddict["milestone"]
-
-    @property
-    def state(self):
-        states = []
-        if not self.is_open:
-            return "closed"
-
-        for label in self.labels:
-            if label.startswith("state"):
-                states.append(label)
-        if len(states) == 1:
-            return states[0][len("state") :].strip("_")
-        elif len(states) > 1:
-            self.state = "question"
-        else:
-            return ""
-
-    @state.setter
-    def state(self, val):
-        return self._setLabels(val, "state")
-
-    @property
-    def is_open(self):
-        return self._ddict["open"]
-
-    @property
-    def type(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("type"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0].partition("_")[-1]
-
-        return ""
-
-    @type.setter
-    def type(self, val):
-        return self._setLabels(val, "type")
-
-    @property
-    def priority(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("priority"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0].partition("_")[-1]
-        else:
-            self.priority = "normal"
-            return self.priority
-
-    @priority.setter
-    def priority(self, val):
-        return self._setLabels(val, "priority")
-
-    @property
-    def process(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("process"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0][len("process") :].strip("_")
-        else:
-            return ""
-
-    @process.setter
-    def process(self, val):
-        return self._setLabels(val, "process")
-
-    def _setLabels(self, val, category):
-        if val is None or val == "":
-            return
-
-        if val.startswith(category):
-            _, _, val = val.partition("_")
-
-        val = val.strip("_")
-        val = val.lower()
-
-        val = "%s_%s" % (category, val)
-
-        if val not in self.repo.labelnames:
-            self.repo.labelnames.sort()
-            llist = ",".join(self.repo.labelnames)
-            raise Exception(
-                "Label needs to be in list:%s (is understood labels in this repo on github), now is: '%s'"
-                % (llist, val)
-            )
-
-        # make sure there is only 1
-        labels2set = self.labels
-        items = []
-        for label in self.labels:
-            if label.startswith(category):
-                items.append(label)
-        if len(items) == 1 and val in items:
-            return
-        for item in items:
-            labels2set.pop(labels2set.index(item))
-        if val is not None or val != "":
-            labels2set.append(val)
-        self.labels = labels2set
-
-    def load(self):
-
-        self._ddict = {}
-
-        # check labels
-        labels = [item.name for item in self.api.labels]  # are the names
-        newlabels = []
-        for label in labels:
-            if label not in self.repo.labelnames:
-                if label in replacelabels:
-                    if replacelabels[label] not in newlabels:
-                        newlabels.append(replacelabels[label])
-            else:
-                if label not in newlabels:
-                    newlabels.append(label)
-
-        if labels != newlabels:
-            self._log_info("change label:%s for %s" % (labels, self.api.title))
-            labels2set = [self.repo.getLabel(item) for item in newlabels]
-            self.api.set_labels(*labels2set)
-            labels = newlabels
-
-        self._ddict["labels"] = labels
-        self._ddict["id"] = self.api.id
-        self._ddict["url"] = self.api.html_url
-        self._ddict["number"] = self.api.number
-        self._ddict["open"] = self.api.state == "open"
-
-        self._ddict["assignee"] = self.repo.client.getUserLogin(githubObj=self.api.assignee)
-        self._ddict["state"] = self.api.state
-        self._ddict["title"] = self.api.title
-
-        self._ddict["body"] = self.api.body
-
-        # self._ddict["time"] = j.data.time.any2HRDateTime([self.api.last_modified, self.api.created_at])
-
-        self._log_debug("LOAD:%s %s" % (self.repo.fullname, self._ddict["title"]))
-
-        if self.api.milestone is None:
-            self._ddict["milestone"] = ""
-        else:
-            ms = RepoMilestone(repo=self.repo, githubObj=self.api.milestone)
-            self._ddict["milestone"] = "%s:%s" % (ms.number, ms.title)
-
-    @property
-    def todo(self):
-        if "_todo" not in self.__dict__:
-            todo = []
-            if self.body is not None:
-                for line in self.body.split("\n"):
-                    if line.startswith("!! "):
-                        todo.append(line.strip().strip("!! "))
-            for comment in self.comments:
-                for line in comment["body"].split("\n"):
-                    if line.startswith("!! "):
-                        todo.append(line.strip().strip("!! "))
-            self._todo = todo
-        return self._todo
-
-    @property
-    def istask(self):
-        if self.type == "task" or self.title.lower().endswith("task"):
-            return True
-        return False
-
-    def __str__(self):
-        return "issue:%s" % self.title
-
-    __repr__ = __str__
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class Issue -(repo, ddict={}, githubObj=None) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class Issue(base):
-    def __init__(self, repo, ddict={}, githubObj=None):
-        base.__init__(self)
-        self.repo = repo
-        self._ddict = ddict
-        self._githubObj = githubObj
-        self._comments = ddict.get("comments", None)
-        if githubObj is not None:
-            self.load()
-
-        self._lock = threading.RLock()
-        # self.todo
-
-    @property
-    def api(self):
-        if self._githubObj is None:
-            self._githubObj = self.repo.api.get_issue(self.number)
-        return self._githubObj
-
-    @property
-    def ddict(self):
-        if self._ddict == {}:
-            # no dict yet, fetch from github
-            self.load()
-        # we lazy load the comments. so it's only loaded when accesses
-        self._ddict["comments"] = self.comments
-        return self._ddict
-
-    @property
-    def comments(self):
-        if self._comments is not None:
-            return self._comments
-
-        with self._lock:
-            if self._comments is None:
-                self._log_debug("Loading comments for issue: %s" % self.number)
-                self._comments = []
-                for comment in self.api.get_comments():
-                    obj = {}
-                    user = self.repo.client.getUserLogin(githubObj=comment.user)
-                    obj["user"] = user
-                    obj["url"] = comment.url
-                    obj["id"] = comment.id
-                    obj["body"] = comment.body
-                    obj["user_id"] = comment.user.id
-                    # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-                    self._comments.append(obj)
-        return self._comments
-
-    def reload_comments(self):
-        with self._lock:
-            self._comments = []
-            for comment in self.api.get_comments():
-                obj = {}
-                user = self.repo.client.getUserLogin(githubObj=comment.user)
-                obj["user"] = user
-                obj["url"] = comment.url
-                obj["id"] = comment.id
-                obj["body"] = comment.body
-                # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-                self._comments.append(obj)
-        return self._comments
-
-    @property
-    def guid(self):
-        return self.repo.fullname + "_" + str(self._ddict["number"])
-
-    @property
-    def number(self):
-        return int(self._ddict["number"])
-
-    @property
-    def title(self):
-        return self._ddict["title"]
-
-    @property
-    def body(self):
-        return self._ddict["body"]
-
-    @body.setter
-    def body(self, val):
-        self._ddict["body"] = val
-        try:
-            self.api.edit(body=self._ddict["body"])
-        except Exception as e:
-            self._log_error("Failed to update the issue body: %s" % e)
-
-    @property
-    def time(self):
-        return self._ddict["time"]
-
-    @property
-    def url(self):
-        return self._ddict["url"]
-
-    @property
-    def assignee(self):
-        return self._ddict["assignee"]
-
-    @property
-    def labels(self):
-        # we return a copy so changing the list doesn't actually change the
-        # ddict value
-        return self._ddict["labels"][:]
-
-    @property
-    def id(self):
-        return self._ddict["id"]
-
-    @labels.setter
-    def labels(self, val):
-        # check if all are already in labels, if yes nothing to do
-        if len(val) == len(self._ddict["labels"]):
-            self._ddict["labels"].sort()
-            val.sort()
-            if val == self._ddict["labels"]:
-                return
-        self._ddict["labels"] = val
-        toset = [self.repo.getLabel(item) for item in self._ddict["labels"]]
-        self.api.set_labels(*toset)
-
-    @property
-    def milestone(self):
-        return self._ddict["milestone"]
-
-    @property
-    def state(self):
-        states = []
-        if not self.is_open:
-            return "closed"
-
-        for label in self.labels:
-            if label.startswith("state"):
-                states.append(label)
-        if len(states) == 1:
-            return states[0][len("state") :].strip("_")
-        elif len(states) > 1:
-            self.state = "question"
-        else:
-            return ""
-
-    @state.setter
-    def state(self, val):
-        return self._setLabels(val, "state")
-
-    @property
-    def is_open(self):
-        return self._ddict["open"]
-
-    @property
-    def type(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("type"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0].partition("_")[-1]
-
-        return ""
-
-    @type.setter
-    def type(self, val):
-        return self._setLabels(val, "type")
-
-    @property
-    def priority(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("priority"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0].partition("_")[-1]
-        else:
-            self.priority = "normal"
-            return self.priority
-
-    @priority.setter
-    def priority(self, val):
-        return self._setLabels(val, "priority")
-
-    @property
-    def process(self):
-        items = []
-        for label in self.labels:
-            if label.startswith("process"):
-                items.append(label)
-        if len(items) == 1:
-            return items[0][len("process") :].strip("_")
-        else:
-            return ""
-
-    @process.setter
-    def process(self, val):
-        return self._setLabels(val, "process")
-
-    def _setLabels(self, val, category):
-        if val is None or val == "":
-            return
-
-        if val.startswith(category):
-            _, _, val = val.partition("_")
-
-        val = val.strip("_")
-        val = val.lower()
-
-        val = "%s_%s" % (category, val)
-
-        if val not in self.repo.labelnames:
-            self.repo.labelnames.sort()
-            llist = ",".join(self.repo.labelnames)
-            raise Exception(
-                "Label needs to be in list:%s (is understood labels in this repo on github), now is: '%s'"
-                % (llist, val)
-            )
-
-        # make sure there is only 1
-        labels2set = self.labels
-        items = []
-        for label in self.labels:
-            if label.startswith(category):
-                items.append(label)
-        if len(items) == 1 and val in items:
-            return
-        for item in items:
-            labels2set.pop(labels2set.index(item))
-        if val is not None or val != "":
-            labels2set.append(val)
-        self.labels = labels2set
-
-    def load(self):
-
-        self._ddict = {}
-
-        # check labels
-        labels = [item.name for item in self.api.labels]  # are the names
-        newlabels = []
-        for label in labels:
-            if label not in self.repo.labelnames:
-                if label in replacelabels:
-                    if replacelabels[label] not in newlabels:
-                        newlabels.append(replacelabels[label])
-            else:
-                if label not in newlabels:
-                    newlabels.append(label)
-
-        if labels != newlabels:
-            self._log_info("change label:%s for %s" % (labels, self.api.title))
-            labels2set = [self.repo.getLabel(item) for item in newlabels]
-            self.api.set_labels(*labels2set)
-            labels = newlabels
-
-        self._ddict["labels"] = labels
-        self._ddict["id"] = self.api.id
-        self._ddict["url"] = self.api.html_url
-        self._ddict["number"] = self.api.number
-        self._ddict["open"] = self.api.state == "open"
-
-        self._ddict["assignee"] = self.repo.client.getUserLogin(githubObj=self.api.assignee)
-        self._ddict["state"] = self.api.state
-        self._ddict["title"] = self.api.title
-
-        self._ddict["body"] = self.api.body
-
-        # self._ddict["time"] = j.data.time.any2HRDateTime([self.api.last_modified, self.api.created_at])
-
-        self._log_debug("LOAD:%s %s" % (self.repo.fullname, self._ddict["title"]))
-
-        if self.api.milestone is None:
-            self._ddict["milestone"] = ""
-        else:
-            ms = RepoMilestone(repo=self.repo, githubObj=self.api.milestone)
-            self._ddict["milestone"] = "%s:%s" % (ms.number, ms.title)
-
-    @property
-    def todo(self):
-        if "_todo" not in self.__dict__:
-            todo = []
-            if self.body is not None:
-                for line in self.body.split("\n"):
-                    if line.startswith("!! "):
-                        todo.append(line.strip().strip("!! "))
-            for comment in self.comments:
-                for line in comment["body"].split("\n"):
-                    if line.startswith("!! "):
-                        todo.append(line.strip().strip("!! "))
-            self._todo = todo
-        return self._todo
-
-    @property
-    def istask(self):
-        if self.type == "task" or self.title.lower().endswith("task"):
-            return True
-        return False
-
-    def __str__(self):
-        return "issue:%s" % self.title
-
-    __repr__ = __str__
-
-

Ancestors

- -

Instance variables

-
-
var api
-
-
-
-Source code -
@property
-def api(self):
-    if self._githubObj is None:
-        self._githubObj = self.repo.api.get_issue(self.number)
-    return self._githubObj
-
-
-
var assignee
-
-
-
-Source code -
@property
-def assignee(self):
-    return self._ddict["assignee"]
-
-
-
var body
-
-
-
-Source code -
@property
-def body(self):
-    return self._ddict["body"]
-
-
-
var comments
-
-
-
-Source code -
@property
-def comments(self):
-    if self._comments is not None:
-        return self._comments
-
-    with self._lock:
-        if self._comments is None:
-            self._log_debug("Loading comments for issue: %s" % self.number)
-            self._comments = []
-            for comment in self.api.get_comments():
-                obj = {}
-                user = self.repo.client.getUserLogin(githubObj=comment.user)
-                obj["user"] = user
-                obj["url"] = comment.url
-                obj["id"] = comment.id
-                obj["body"] = comment.body
-                obj["user_id"] = comment.user.id
-                # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-                self._comments.append(obj)
-    return self._comments
-
-
-
var ddict
-
-
-
-Source code -
@property
-def ddict(self):
-    if self._ddict == {}:
-        # no dict yet, fetch from github
-        self.load()
-    # we lazy load the comments. so it's only loaded when accesses
-    self._ddict["comments"] = self.comments
-    return self._ddict
-
-
-
var guid
-
-
-
-Source code -
@property
-def guid(self):
-    return self.repo.fullname + "_" + str(self._ddict["number"])
-
-
-
var id
-
-
-
-Source code -
@property
-def id(self):
-    return self._ddict["id"]
-
-
-
var is_open
-
-
-
-Source code -
@property
-def is_open(self):
-    return self._ddict["open"]
-
-
-
var istask
-
-
-
-Source code -
@property
-def istask(self):
-    if self.type == "task" or self.title.lower().endswith("task"):
-        return True
-    return False
-
-
-
var labels
-
-
-
-Source code -
@property
-def labels(self):
-    # we return a copy so changing the list doesn't actually change the
-    # ddict value
-    return self._ddict["labels"][:]
-
-
-
var milestone
-
-
-
-Source code -
@property
-def milestone(self):
-    return self._ddict["milestone"]
-
-
-
var number
-
-
-
-Source code -
@property
-def number(self):
-    return int(self._ddict["number"])
-
-
-
var priority
-
-
-
-Source code -
@property
-def priority(self):
-    items = []
-    for label in self.labels:
-        if label.startswith("priority"):
-            items.append(label)
-    if len(items) == 1:
-        return items[0].partition("_")[-1]
-    else:
-        self.priority = "normal"
-        return self.priority
-
-
-
var process
-
-
-
-Source code -
@property
-def process(self):
-    items = []
-    for label in self.labels:
-        if label.startswith("process"):
-            items.append(label)
-    if len(items) == 1:
-        return items[0][len("process") :].strip("_")
-    else:
-        return ""
-
-
-
var state
-
-
-
-Source code -
@property
-def state(self):
-    states = []
-    if not self.is_open:
-        return "closed"
-
-    for label in self.labels:
-        if label.startswith("state"):
-            states.append(label)
-    if len(states) == 1:
-        return states[0][len("state") :].strip("_")
-    elif len(states) > 1:
-        self.state = "question"
-    else:
-        return ""
-
-
-
var time
-
-
-
-Source code -
@property
-def time(self):
-    return self._ddict["time"]
-
-
-
var title
-
-
-
-Source code -
@property
-def title(self):
-    return self._ddict["title"]
-
-
-
var todo
-
-
-
-Source code -
@property
-def todo(self):
-    if "_todo" not in self.__dict__:
-        todo = []
-        if self.body is not None:
-            for line in self.body.split("\n"):
-                if line.startswith("!! "):
-                    todo.append(line.strip().strip("!! "))
-        for comment in self.comments:
-            for line in comment["body"].split("\n"):
-                if line.startswith("!! "):
-                    todo.append(line.strip().strip("!! "))
-        self._todo = todo
-    return self._todo
-
-
-
var type
-
-
-
-Source code -
@property
-def type(self):
-    items = []
-    for label in self.labels:
-        if label.startswith("type"):
-            items.append(label)
-    if len(items) == 1:
-        return items[0].partition("_")[-1]
-
-    return ""
-
-
-
var url
-
-
-
-Source code -
@property
-def url(self):
-    return self._ddict["url"]
-
-
-
-

Methods

-
-
-def load(self) -
-
-
-
-Source code -
def load(self):
-
-    self._ddict = {}
-
-    # check labels
-    labels = [item.name for item in self.api.labels]  # are the names
-    newlabels = []
-    for label in labels:
-        if label not in self.repo.labelnames:
-            if label in replacelabels:
-                if replacelabels[label] not in newlabels:
-                    newlabels.append(replacelabels[label])
-        else:
-            if label not in newlabels:
-                newlabels.append(label)
-
-    if labels != newlabels:
-        self._log_info("change label:%s for %s" % (labels, self.api.title))
-        labels2set = [self.repo.getLabel(item) for item in newlabels]
-        self.api.set_labels(*labels2set)
-        labels = newlabels
-
-    self._ddict["labels"] = labels
-    self._ddict["id"] = self.api.id
-    self._ddict["url"] = self.api.html_url
-    self._ddict["number"] = self.api.number
-    self._ddict["open"] = self.api.state == "open"
-
-    self._ddict["assignee"] = self.repo.client.getUserLogin(githubObj=self.api.assignee)
-    self._ddict["state"] = self.api.state
-    self._ddict["title"] = self.api.title
-
-    self._ddict["body"] = self.api.body
-
-    # self._ddict["time"] = j.data.time.any2HRDateTime([self.api.last_modified, self.api.created_at])
-
-    self._log_debug("LOAD:%s %s" % (self.repo.fullname, self._ddict["title"]))
-
-    if self.api.milestone is None:
-        self._ddict["milestone"] = ""
-    else:
-        ms = RepoMilestone(repo=self.repo, githubObj=self.api.milestone)
-        self._ddict["milestone"] = "%s:%s" % (ms.number, ms.title)
-
-
-
-def reload_comments(self) -
-
-
-
-Source code -
def reload_comments(self):
-    with self._lock:
-        self._comments = []
-        for comment in self.api.get_comments():
-            obj = {}
-            user = self.repo.client.getUserLogin(githubObj=comment.user)
-            obj["user"] = user
-            obj["url"] = comment.url
-            obj["id"] = comment.id
-            obj["body"] = comment.body
-            # obj["time"] = j.data.time.any2HRDateTime([comment.last_modified, comment.created_at])
-            self._comments.append(obj)
-    return self._comments
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/github/milestone.html b/docs/api/jumpscale/clients/github/milestone.html deleted file mode 100644 index fefdaf0a0..000000000 --- a/docs/api/jumpscale/clients/github/milestone.html +++ /dev/null @@ -1,368 +0,0 @@ - - - - - - -jumpscale.clients.github.milestone API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github.milestone

-
-
-
-Source code -
from jumpscale.loader import j
-from .base import base
-
-
-class RepoMilestone(base):
-    """
-    milestone as defined on 1 specific repo
-    """
-
-    def __init__(self, repo, githubObj=None):
-        base.__init__(self)
-        self._ddict = {}
-        self._githubObj = githubObj
-        if githubObj is not None:
-            self.load()
-        self.repo = repo
-
-    # @property
-    # def api(self):
-    #     if self._githubObj is None:
-    #         j.application.break_into_jshell("DEBUG NOW get api for milestone")
-    #     return self._githubObj
-
-    def load(self):
-        self._ddict = {}
-        #self._ddict["deadline"] = j.data.time.any2HRDateTime(self.api.due_on)
-        self._ddict["id"] = self.api.id
-        self._ddict["url"] = self.api.url
-        self._ddict["title"] = self.api.title
-        self._ddict["body"] = self.api.description
-        self._ddict["number"] = self.api.number
-
-    @property
-    def title(self):
-        return self._ddict["title"]
-
-    @title.setter
-    def title(self, val):
-        self._ddict["title"] = val
-        self.api.edit(title=val)
-
-    @property
-    def ddict(self):
-        if not self._ddict:
-            # no dict yet, fetch from github
-            self.load()
-        return self._ddict
-
-
-
-    # synonym to let the tags of super class work
-    @property
-    def body(self):
-        return self._ddict["body"]
-
-    @body.setter
-    def body(self, val):
-        if self._ddict["body"] != val:
-            self._ddict["body"] = val
-            self.api.edit(self.title, description=val)
-
-    # @property
-    # def deadline(self):
-    #     return self._ddict["deadline"]
-
-    # @deadline.setter
-    # def deadline(self, val):
-    #     #due = j.data.time.epoch2pythonDateTime(int(j.data.time.getEpochFuture(val)))
-
-    #     self._ddict["deadline"] = val
-    #     self.api.edit(title=self.title)
-
-    @property
-    def id(self):
-        return self._ddict["id"]
-
-    @property
-    def url(self):
-        return self._ddict["url"]
-
-    @property
-    def number(self):
-        return self._ddict["number"]
-        
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class RepoMilestone -(repo, githubObj=None) -
-
-

milestone as defined on 1 specific repo

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class RepoMilestone(base):
-    """
-    milestone as defined on 1 specific repo
-    """
-
-    def __init__(self, repo, githubObj=None):
-        base.__init__(self)
-        self._ddict = {}
-        self._githubObj = githubObj
-        if githubObj is not None:
-            self.load()
-        self.repo = repo
-
-    # @property
-    # def api(self):
-    #     if self._githubObj is None:
-    #         j.application.break_into_jshell("DEBUG NOW get api for milestone")
-    #     return self._githubObj
-
-    def load(self):
-        self._ddict = {}
-        #self._ddict["deadline"] = j.data.time.any2HRDateTime(self.api.due_on)
-        self._ddict["id"] = self.api.id
-        self._ddict["url"] = self.api.url
-        self._ddict["title"] = self.api.title
-        self._ddict["body"] = self.api.description
-        self._ddict["number"] = self.api.number
-
-    @property
-    def title(self):
-        return self._ddict["title"]
-
-    @title.setter
-    def title(self, val):
-        self._ddict["title"] = val
-        self.api.edit(title=val)
-
-    @property
-    def ddict(self):
-        if not self._ddict:
-            # no dict yet, fetch from github
-            self.load()
-        return self._ddict
-
-
-
-    # synonym to let the tags of super class work
-    @property
-    def body(self):
-        return self._ddict["body"]
-
-    @body.setter
-    def body(self, val):
-        if self._ddict["body"] != val:
-            self._ddict["body"] = val
-            self.api.edit(self.title, description=val)
-
-    # @property
-    # def deadline(self):
-    #     return self._ddict["deadline"]
-
-    # @deadline.setter
-    # def deadline(self, val):
-    #     #due = j.data.time.epoch2pythonDateTime(int(j.data.time.getEpochFuture(val)))
-
-    #     self._ddict["deadline"] = val
-    #     self.api.edit(title=self.title)
-
-    @property
-    def id(self):
-        return self._ddict["id"]
-
-    @property
-    def url(self):
-        return self._ddict["url"]
-
-    @property
-    def number(self):
-        return self._ddict["number"]
-
-

Ancestors

- -

Instance variables

-
-
var body
-
-
-
-Source code -
@property
-def body(self):
-    return self._ddict["body"]
-
-
-
var ddict
-
-
-
-Source code -
@property
-def ddict(self):
-    if not self._ddict:
-        # no dict yet, fetch from github
-        self.load()
-    return self._ddict
-
-
-
var id
-
-
-
-Source code -
@property
-def id(self):
-    return self._ddict["id"]
-
-
-
var number
-
-
-
-Source code -
@property
-def number(self):
-    return self._ddict["number"]
-
-
-
var title
-
-
-
-Source code -
@property
-def title(self):
-    return self._ddict["title"]
-
-
-
var url
-
-
-
-Source code -
@property
-def url(self):
-    return self._ddict["url"]
-
-
-
-

Methods

-
-
-def load(self) -
-
-
-
-Source code -
def load(self):
-    self._ddict = {}
-    #self._ddict["deadline"] = j.data.time.any2HRDateTime(self.api.due_on)
-    self._ddict["id"] = self.api.id
-    self._ddict["url"] = self.api.url
-    self._ddict["title"] = self.api.title
-    self._ddict["body"] = self.api.description
-    self._ddict["number"] = self.api.number
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/github/repo.html b/docs/api/jumpscale/clients/github/repo.html deleted file mode 100644 index 958542a1f..000000000 --- a/docs/api/jumpscale/clients/github/repo.html +++ /dev/null @@ -1,1525 +0,0 @@ - - - - - - -jumpscale.clients.github.repo API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.github.repo

-
-
-
-Source code -
import threading
-import copy
-import base64
-from .issue import Issue
-
-from .base import replacelabels
-from jumpscale.clients.base import Client
-from jumpscale.core.base import Base, fields
-from jumpscale.loader import j
-
-# import collections
-import urllib
-from .milestone import RepoMilestone
-from github.GithubException import UnknownObjectException
-
-
-class GithubRepo:
-    TYPES = ["story", "ticket", "task", "bug", "feature", "question", "monitor", "unknown"]
-    PRIORITIES = ["critical", "urgent", "normal", "minor"]
-
-    STATES = ["new", "accepted", "question", "inprogress", "verification", "closed"]
-
-    def __init__(self, client, fullname):
-        self.client = client
-        self.fullname = fullname
-        self._repoclient = None
-        self._labels = None
-        self._issues = None
-        self._lock = threading.RLock()
-        self._milestones = None
-
-    def _log_info(self, s):
-        pass
-
-    @property
-    def api(self):
-        if self._repoclient is None:
-            self._repoclient = self.client.get_repo(self.fullname)
-        return self._repoclient
-
-    @property
-    def name(self):
-        return self.fullname.split("/", 1)[-1]
-
-    @property
-    def type(self):
-        if self.name in ["home"]:
-            return "home"
-        elif self.name.startswith("proj"):
-            return "proj"
-        elif self.name.startswith("org_"):
-            return "org"
-        elif self.name.startswith("www"):
-            return "www"
-        elif self.name.startswith("doc"):
-            return "doc"
-        elif self.name.startswith("cockpit"):
-            return "cockpit"
-        else:
-            return "code"
-
-    @property
-    def labelnames(self):
-        return [item.name for item in self.labels]
-
-    @property
-    def labels(self):
-        with self._lock:
-            if self._labels is None:
-                self._labels = [item for item in self.api.get_labels()]
-
-        return self._labels
-
-    @property
-    def stories(self):
-        # walk overall issues find the stories (based on type)
-        # only for home type repo, otherwise return []
-        return self.issues_by_type("story")
-
-    @property
-    def tasks(self):
-        # walk overall issues find the stories (based on type)
-        # only for home type repo, otherwise return []
-        return self.issues_by_type("task")
-
-    def labelsSet(self, labels2set, ignoreDelete=["p_"], delete=True):
-        """
-        @param ignore all labels starting with ignore will not be deleted
-        """
-
-        for item in labels2set:
-            if not isinstance(item, str):
-                raise Exception("Labels to set need to be in string format, found:%s" % labels2set)
-
-        # walk over github existing labels
-        labelstowalk = copy.copy(self.labels)
-        for item in labelstowalk:
-            name = item.name.lower()
-            if name not in labels2set:
-                # label in repo does not correspond to label we need
-                if name in replacelabels:
-                    nameNew = replacelabels[item.name.lower()]
-                    if nameNew not in self.labelnames:
-                        color = self.get_color(name)
-                        self._log_info(
-                            "change label in repo: %s oldlabel:'%s' to:'%s' color:%s"
-                            % (self.fullname, item.name, nameNew, color)
-                        )
-                        item.edit(nameNew, color)
-                        self._labels = None
-                else:
-                    # no replacement
-                    name = "type_unknown"
-                    color = self.get_color(name)
-                    try:
-                        item.edit(name, color)
-                    except BaseException:
-                        item.delete()
-                    self._labels = None
-
-        # walk over new labels we need to set
-        for name in labels2set:
-            if name not in self.labelnames:
-                # does not exist yet in repo
-                color = self.get_color(name)
-                self._log_info("create label: %s %s %s" % (self.fullname, name, color))
-                self.api.create_label(name, color)
-                self._labels = None
-
-        name = ""
-
-        if delete:
-            labelstowalk = copy.copy(self.labels)
-            for item in labelstowalk:
-                if item.name not in labels2set:
-                    self._log_info("delete label: %s %s" % (self.fullname, item.name))
-                    ignoreDeleteDo = False
-                    for filteritem in ignoreDelete:
-                        if item.name.startswith(filteritem):
-                            ignoreDeleteDo = True
-                    if ignoreDeleteDo is False:
-                        item.delete()
-                    self._labels = None
-
-        # check the colors
-        labelstowalk = copy.copy(self.labels)
-        for item in labelstowalk:
-            # we recognise the label
-            self._log_info("check color of repo:%s labelname:'%s'" % (self.fullname, item.name))
-            color = self.get_color(item.name)
-            if item.color != color:
-                self._log_info("change label color for repo %s %s" % (item.name, color))
-                item.edit(item.name, color)
-                self._labels = None
-
-    def getlabel(self, name):
-        for item in self.labels:
-            self._log_info("%s:look for name:'%s'" % (item.name, name))
-            if item.name == name:
-                return item
-        raise Exception("Dit not find label: '%s'" % name)
-
-    def get_issue_from_markdown(self, issueNumber, markdown):
-        i = self.get_issue(issueNumber, False)
-        i._loadMD(markdown)
-        self.issues.append(i)
-        return i
-
-    def get_issue(self, issueNumber, die=True):
-        for issue in self.issues:
-            if issue.number == issueNumber:
-                return issue
-        # not found in cache, try to load from github
-        github_issue = self.api.get_issue(issueNumber)
-
-        if github_issue:
-            issue = Issue(repo=self, githubObj=github_issue)
-            self._issues.append(issue)
-            return issue
-
-        if die:
-            raise Exception("cannot find issue:%s in repo:%s" % (issueNumber, self))
-        else:
-            i = Issue(self)
-            i._ddict["number"] = issueNumber
-            return i
-
-    def issues_by_type(self, *types):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        issues = []
-        for issue in self.issues:
-            if issue.type in types:
-                issues.append(issue)
-
-        return issues
-
-    def issues_by_state(self, filter=None):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        res = {}
-        for item in self.states:
-            res[item] = []
-            for issue in self.issues:
-                if issue.state == item:
-                    if filter is None or filter(issue):
-                        res[item].append(issue)
-        return res
-
-    def issues_by_priority(self, filter=None):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        res = {}
-        for item in self.priorities:
-            res[item] = []
-            for issue in self.issues:
-                if issue.priority == item:
-                    if filter is None or filter(issue):
-                        res[item].append(issue)
-        return res
-
-    def issues_by_type_state(self, filter=None, collapsepriority=True):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        returns dict of dict keys: type, state and then issues sorted following priority
-        """
-        res = {}
-        for type in self.types:
-            res[type] = {}
-            for state in self.states:
-                res[type][state] = {}
-                for priority in self.priorities:
-                    res[type][state][priority] = []
-                    for issue in self.issues:
-                        if issue.type == type and issue.state == state:
-                            if filter is None or filter(issue):
-                                res[type][state][priority].append(issue)
-                if collapsepriority:
-                    # sort the issues following priority
-                    temp = res[type][state]
-                    res[type][state] = []
-                    for priority in self.priorities:
-                        for subitem in temp[priority]:
-                            res[type][state].append(subitem)
-        return res
-
-    @property
-    def types(self):
-        return GithubRepo.TYPES
-
-    @property
-    def priorities(self):
-        return GithubRepo.PRIORITIES
-
-    @property
-    def states(self):
-        return GithubRepo.STATES
-
-    @property
-    def milestones(self):
-        if self._milestones is None:
-            self._milestones = [RepoMilestone(self, x) for x in self.api.get_milestones()]
-
-        return self._milestones
-
-    @property
-    def milestone_titles(self):
-        return [item.title for item in self.milestones]
-
-    @property
-    def milestone_names(self):
-        return [item.name for item in self.milestones]
-
-    def get_milestone(self, name, die=True):
-        name = name.strip()
-        if name == "":
-            raise Exception("Name cannot be empty.")
-        for item in self.milestones:
-            if name == item.name.strip() or name == item.title.strip():
-                return item
-        if die:
-            raise Exception("Could not find milestone with name:%s" % name)
-        else:
-            return None
-
-    def create_milestone(self, name, title, description="", deadline="", owner=""):
-        self._log_info('Attempt to create milestone "%s" [%s] deadline %s' % (name, title, deadline))
-
-        def getBody(descr, name, owner):
-            out = "%s\n\n" % descr
-            out += "## name:%s\n" % name
-            out += "## owner:%s\n" % owner
-            return out
-
-        ms = None
-        for s in [name, title]:
-            ms = self.get_milestone(s, die=False)
-            if ms is not None:
-                break
-
-        if ms is not None:
-            if ms.title != title:
-                ms.title = title
-            # if ms.deadline != deadline:
-            #     ms.deadline = deadline
-            tocheck = getBody(description.strip(), name, owner)
-            if ms.body.strip() != tocheck.strip():
-                ms.body = tocheck
-        else:
-            # due = j.data.time.epoch2pythonDateTime(int(j.data.time.getEpochFuture(deadline)))
-            self._log_info("Create milestone on %s: %s" % (self, title))
-            body = getBody(description.strip(), name, owner)
-            # workaround for https://github.com/PyGithub/PyGithub/issues/396
-            milestone = self.api.create_milestone(title=title, description=body)
-            milestone.edit(title=title)
-
-            self._milestones.append(RepoMilestone(self, milestone))
-
-    def delete_milestone(self, name):
-        if name.strip() == "":
-            raise Exception("Name cannot be empty.")
-        self._log_info("Delete milestone on %s: '%s'" % (self, name))
-        try:
-            ms = self.get_milestone(name)
-            ms.api.delete()
-            self._milestones = []
-        except Exception:
-            self._log_info("Milestone '%s' doesn't exist. no need to delete" % name)
-
-    def _labelsubset(self, cat):
-        res = []
-        for item in self.labels:
-            if item.startswith(cat):
-                item = item[len(cat) :].strip("_")
-                res.append(item)
-        res.sort()
-        return res
-
-    def get_color(self, name):
-
-        # colors={'state_question':'fbca04',
-        #  'priority_urgent':'d93f0b',
-        #  'state_verification':'006b75',
-        #  'priority_minor':'',
-        #  'type_task':'',
-        #  'type_feature':'',
-        #  'process_wontfix':"ffffff",
-        #  'priority_critical':"b60205",
-        #  'state_inprogress':"e6e6e6",
-        #  'priority_normal':"e6e6e6",
-        #  'type_story':"ee9a00",
-        #  'process_duplicate':"",
-        #  'state_closed':"5319e7",
-        #  'type_bug':"fc2929",
-        #  'state_accepted':"0e8a16",
-        #  'type_question':"fbca04",
-        #  'state_new':"1d76db"}
-
-        if name.startswith("state"):
-            return "c2e0c6"  # light green
-
-        if name.startswith("process"):
-            return "d4c5f9"  # light purple
-
-        if name.startswith("type"):
-            return "fef2c0"  # light yellow
-
-        if name in ("priority_critical", "task_no_estimation"):
-            return "b60205"  # red
-
-        if name.startswith("priority_urgent"):
-            return "d93f0b"
-
-        if name.startswith("priority"):
-            return "f9d0c4"  # roze
-
-        return "ffffff"
-
-    def set_file(self, path, content, message="update file"):
-        """
-        Creates or updates the file content at path with given content
-        :param path: file path `README.md`
-        :param content: Plain content of file
-        :return:
-        """
-        bytes = content.encode()
-        encoded = base64.encodebytes(bytes)
-
-        params = {"message": message, "content": encoded.decode()}
-
-        path = urllib.parse.quote(path)
-        try:
-            obj = self.api.get_contents(path)
-            params["sha"] = obj.sha
-            if base64.decodebytes(obj.content.encode()) == bytes:
-                return
-        except UnknownObjectException:
-            pass
-
-        self._log_info('Updating file "%s"' % path)
-        self.api._requester.requestJsonAndCheck("PUT", self.api.url + "/contents/" + path, input=params)
-
-    @property
-    def issues(self):
-        with self._lock:
-            if self._issues is None:
-                issues = []
-                for item in self.api.get_issues(state="all"):
-                    issues.append(Issue(self, githubObj=item))
-
-                self._issues = issues
-
-        return self._issues
-
-    def __str__(self):
-        return "gitrepo:%s" % self.fullname
-
-    __repr__ = __str__
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class GithubRepo -(client, fullname) -
-
-
-
-Source code -
class GithubRepo:
-    TYPES = ["story", "ticket", "task", "bug", "feature", "question", "monitor", "unknown"]
-    PRIORITIES = ["critical", "urgent", "normal", "minor"]
-
-    STATES = ["new", "accepted", "question", "inprogress", "verification", "closed"]
-
-    def __init__(self, client, fullname):
-        self.client = client
-        self.fullname = fullname
-        self._repoclient = None
-        self._labels = None
-        self._issues = None
-        self._lock = threading.RLock()
-        self._milestones = None
-
-    def _log_info(self, s):
-        pass
-
-    @property
-    def api(self):
-        if self._repoclient is None:
-            self._repoclient = self.client.get_repo(self.fullname)
-        return self._repoclient
-
-    @property
-    def name(self):
-        return self.fullname.split("/", 1)[-1]
-
-    @property
-    def type(self):
-        if self.name in ["home"]:
-            return "home"
-        elif self.name.startswith("proj"):
-            return "proj"
-        elif self.name.startswith("org_"):
-            return "org"
-        elif self.name.startswith("www"):
-            return "www"
-        elif self.name.startswith("doc"):
-            return "doc"
-        elif self.name.startswith("cockpit"):
-            return "cockpit"
-        else:
-            return "code"
-
-    @property
-    def labelnames(self):
-        return [item.name for item in self.labels]
-
-    @property
-    def labels(self):
-        with self._lock:
-            if self._labels is None:
-                self._labels = [item for item in self.api.get_labels()]
-
-        return self._labels
-
-    @property
-    def stories(self):
-        # walk overall issues find the stories (based on type)
-        # only for home type repo, otherwise return []
-        return self.issues_by_type("story")
-
-    @property
-    def tasks(self):
-        # walk overall issues find the stories (based on type)
-        # only for home type repo, otherwise return []
-        return self.issues_by_type("task")
-
-    def labelsSet(self, labels2set, ignoreDelete=["p_"], delete=True):
-        """
-        @param ignore all labels starting with ignore will not be deleted
-        """
-
-        for item in labels2set:
-            if not isinstance(item, str):
-                raise Exception("Labels to set need to be in string format, found:%s" % labels2set)
-
-        # walk over github existing labels
-        labelstowalk = copy.copy(self.labels)
-        for item in labelstowalk:
-            name = item.name.lower()
-            if name not in labels2set:
-                # label in repo does not correspond to label we need
-                if name in replacelabels:
-                    nameNew = replacelabels[item.name.lower()]
-                    if nameNew not in self.labelnames:
-                        color = self.get_color(name)
-                        self._log_info(
-                            "change label in repo: %s oldlabel:'%s' to:'%s' color:%s"
-                            % (self.fullname, item.name, nameNew, color)
-                        )
-                        item.edit(nameNew, color)
-                        self._labels = None
-                else:
-                    # no replacement
-                    name = "type_unknown"
-                    color = self.get_color(name)
-                    try:
-                        item.edit(name, color)
-                    except BaseException:
-                        item.delete()
-                    self._labels = None
-
-        # walk over new labels we need to set
-        for name in labels2set:
-            if name not in self.labelnames:
-                # does not exist yet in repo
-                color = self.get_color(name)
-                self._log_info("create label: %s %s %s" % (self.fullname, name, color))
-                self.api.create_label(name, color)
-                self._labels = None
-
-        name = ""
-
-        if delete:
-            labelstowalk = copy.copy(self.labels)
-            for item in labelstowalk:
-                if item.name not in labels2set:
-                    self._log_info("delete label: %s %s" % (self.fullname, item.name))
-                    ignoreDeleteDo = False
-                    for filteritem in ignoreDelete:
-                        if item.name.startswith(filteritem):
-                            ignoreDeleteDo = True
-                    if ignoreDeleteDo is False:
-                        item.delete()
-                    self._labels = None
-
-        # check the colors
-        labelstowalk = copy.copy(self.labels)
-        for item in labelstowalk:
-            # we recognise the label
-            self._log_info("check color of repo:%s labelname:'%s'" % (self.fullname, item.name))
-            color = self.get_color(item.name)
-            if item.color != color:
-                self._log_info("change label color for repo %s %s" % (item.name, color))
-                item.edit(item.name, color)
-                self._labels = None
-
-    def getlabel(self, name):
-        for item in self.labels:
-            self._log_info("%s:look for name:'%s'" % (item.name, name))
-            if item.name == name:
-                return item
-        raise Exception("Dit not find label: '%s'" % name)
-
-    def get_issue_from_markdown(self, issueNumber, markdown):
-        i = self.get_issue(issueNumber, False)
-        i._loadMD(markdown)
-        self.issues.append(i)
-        return i
-
-    def get_issue(self, issueNumber, die=True):
-        for issue in self.issues:
-            if issue.number == issueNumber:
-                return issue
-        # not found in cache, try to load from github
-        github_issue = self.api.get_issue(issueNumber)
-
-        if github_issue:
-            issue = Issue(repo=self, githubObj=github_issue)
-            self._issues.append(issue)
-            return issue
-
-        if die:
-            raise Exception("cannot find issue:%s in repo:%s" % (issueNumber, self))
-        else:
-            i = Issue(self)
-            i._ddict["number"] = issueNumber
-            return i
-
-    def issues_by_type(self, *types):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        issues = []
-        for issue in self.issues:
-            if issue.type in types:
-                issues.append(issue)
-
-        return issues
-
-    def issues_by_state(self, filter=None):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        res = {}
-        for item in self.states:
-            res[item] = []
-            for issue in self.issues:
-                if issue.state == item:
-                    if filter is None or filter(issue):
-                        res[item].append(issue)
-        return res
-
-    def issues_by_priority(self, filter=None):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        """
-        res = {}
-        for item in self.priorities:
-            res[item] = []
-            for issue in self.issues:
-                if issue.priority == item:
-                    if filter is None or filter(issue):
-                        res[item].append(issue)
-        return res
-
-    def issues_by_type_state(self, filter=None, collapsepriority=True):
-        """
-        filter is method which takes  issue as argument and returns True or False to include
-        returns dict of dict keys: type, state and then issues sorted following priority
-        """
-        res = {}
-        for type in self.types:
-            res[type] = {}
-            for state in self.states:
-                res[type][state] = {}
-                for priority in self.priorities:
-                    res[type][state][priority] = []
-                    for issue in self.issues:
-                        if issue.type == type and issue.state == state:
-                            if filter is None or filter(issue):
-                                res[type][state][priority].append(issue)
-                if collapsepriority:
-                    # sort the issues following priority
-                    temp = res[type][state]
-                    res[type][state] = []
-                    for priority in self.priorities:
-                        for subitem in temp[priority]:
-                            res[type][state].append(subitem)
-        return res
-
-    @property
-    def types(self):
-        return GithubRepo.TYPES
-
-    @property
-    def priorities(self):
-        return GithubRepo.PRIORITIES
-
-    @property
-    def states(self):
-        return GithubRepo.STATES
-
-    @property
-    def milestones(self):
-        if self._milestones is None:
-            self._milestones = [RepoMilestone(self, x) for x in self.api.get_milestones()]
-
-        return self._milestones
-
-    @property
-    def milestone_titles(self):
-        return [item.title for item in self.milestones]
-
-    @property
-    def milestone_names(self):
-        return [item.name for item in self.milestones]
-
-    def get_milestone(self, name, die=True):
-        name = name.strip()
-        if name == "":
-            raise Exception("Name cannot be empty.")
-        for item in self.milestones:
-            if name == item.name.strip() or name == item.title.strip():
-                return item
-        if die:
-            raise Exception("Could not find milestone with name:%s" % name)
-        else:
-            return None
-
-    def create_milestone(self, name, title, description="", deadline="", owner=""):
-        self._log_info('Attempt to create milestone "%s" [%s] deadline %s' % (name, title, deadline))
-
-        def getBody(descr, name, owner):
-            out = "%s\n\n" % descr
-            out += "## name:%s\n" % name
-            out += "## owner:%s\n" % owner
-            return out
-
-        ms = None
-        for s in [name, title]:
-            ms = self.get_milestone(s, die=False)
-            if ms is not None:
-                break
-
-        if ms is not None:
-            if ms.title != title:
-                ms.title = title
-            # if ms.deadline != deadline:
-            #     ms.deadline = deadline
-            tocheck = getBody(description.strip(), name, owner)
-            if ms.body.strip() != tocheck.strip():
-                ms.body = tocheck
-        else:
-            # due = j.data.time.epoch2pythonDateTime(int(j.data.time.getEpochFuture(deadline)))
-            self._log_info("Create milestone on %s: %s" % (self, title))
-            body = getBody(description.strip(), name, owner)
-            # workaround for https://github.com/PyGithub/PyGithub/issues/396
-            milestone = self.api.create_milestone(title=title, description=body)
-            milestone.edit(title=title)
-
-            self._milestones.append(RepoMilestone(self, milestone))
-
-    def delete_milestone(self, name):
-        if name.strip() == "":
-            raise Exception("Name cannot be empty.")
-        self._log_info("Delete milestone on %s: '%s'" % (self, name))
-        try:
-            ms = self.get_milestone(name)
-            ms.api.delete()
-            self._milestones = []
-        except Exception:
-            self._log_info("Milestone '%s' doesn't exist. no need to delete" % name)
-
-    def _labelsubset(self, cat):
-        res = []
-        for item in self.labels:
-            if item.startswith(cat):
-                item = item[len(cat) :].strip("_")
-                res.append(item)
-        res.sort()
-        return res
-
-    def get_color(self, name):
-
-        # colors={'state_question':'fbca04',
-        #  'priority_urgent':'d93f0b',
-        #  'state_verification':'006b75',
-        #  'priority_minor':'',
-        #  'type_task':'',
-        #  'type_feature':'',
-        #  'process_wontfix':"ffffff",
-        #  'priority_critical':"b60205",
-        #  'state_inprogress':"e6e6e6",
-        #  'priority_normal':"e6e6e6",
-        #  'type_story':"ee9a00",
-        #  'process_duplicate':"",
-        #  'state_closed':"5319e7",
-        #  'type_bug':"fc2929",
-        #  'state_accepted':"0e8a16",
-        #  'type_question':"fbca04",
-        #  'state_new':"1d76db"}
-
-        if name.startswith("state"):
-            return "c2e0c6"  # light green
-
-        if name.startswith("process"):
-            return "d4c5f9"  # light purple
-
-        if name.startswith("type"):
-            return "fef2c0"  # light yellow
-
-        if name in ("priority_critical", "task_no_estimation"):
-            return "b60205"  # red
-
-        if name.startswith("priority_urgent"):
-            return "d93f0b"
-
-        if name.startswith("priority"):
-            return "f9d0c4"  # roze
-
-        return "ffffff"
-
-    def set_file(self, path, content, message="update file"):
-        """
-        Creates or updates the file content at path with given content
-        :param path: file path `README.md`
-        :param content: Plain content of file
-        :return:
-        """
-        bytes = content.encode()
-        encoded = base64.encodebytes(bytes)
-
-        params = {"message": message, "content": encoded.decode()}
-
-        path = urllib.parse.quote(path)
-        try:
-            obj = self.api.get_contents(path)
-            params["sha"] = obj.sha
-            if base64.decodebytes(obj.content.encode()) == bytes:
-                return
-        except UnknownObjectException:
-            pass
-
-        self._log_info('Updating file "%s"' % path)
-        self.api._requester.requestJsonAndCheck("PUT", self.api.url + "/contents/" + path, input=params)
-
-    @property
-    def issues(self):
-        with self._lock:
-            if self._issues is None:
-                issues = []
-                for item in self.api.get_issues(state="all"):
-                    issues.append(Issue(self, githubObj=item))
-
-                self._issues = issues
-
-        return self._issues
-
-    def __str__(self):
-        return "gitrepo:%s" % self.fullname
-
-    __repr__ = __str__
-
-

Class variables

-
-
var PRIORITIES
-
-
-
-
var STATES
-
-
-
-
var TYPES
-
-
-
-
-

Instance variables

-
-
var api
-
-
-
-Source code -
@property
-def api(self):
-    if self._repoclient is None:
-        self._repoclient = self.client.get_repo(self.fullname)
-    return self._repoclient
-
-
-
var issues
-
-
-
-Source code -
@property
-def issues(self):
-    with self._lock:
-        if self._issues is None:
-            issues = []
-            for item in self.api.get_issues(state="all"):
-                issues.append(Issue(self, githubObj=item))
-
-            self._issues = issues
-
-    return self._issues
-
-
-
var labelnames
-
-
-
-Source code -
@property
-def labelnames(self):
-    return [item.name for item in self.labels]
-
-
-
var labels
-
-
-
-Source code -
@property
-def labels(self):
-    with self._lock:
-        if self._labels is None:
-            self._labels = [item for item in self.api.get_labels()]
-
-    return self._labels
-
-
-
var milestone_names
-
-
-
-Source code -
@property
-def milestone_names(self):
-    return [item.name for item in self.milestones]
-
-
-
var milestone_titles
-
-
-
-Source code -
@property
-def milestone_titles(self):
-    return [item.title for item in self.milestones]
-
-
-
var milestones
-
-
-
-Source code -
@property
-def milestones(self):
-    if self._milestones is None:
-        self._milestones = [RepoMilestone(self, x) for x in self.api.get_milestones()]
-
-    return self._milestones
-
-
-
var name
-
-
-
-Source code -
@property
-def name(self):
-    return self.fullname.split("/", 1)[-1]
-
-
-
var priorities
-
-
-
-Source code -
@property
-def priorities(self):
-    return GithubRepo.PRIORITIES
-
-
-
var states
-
-
-
-Source code -
@property
-def states(self):
-    return GithubRepo.STATES
-
-
-
var stories
-
-
-
-Source code -
@property
-def stories(self):
-    # walk overall issues find the stories (based on type)
-    # only for home type repo, otherwise return []
-    return self.issues_by_type("story")
-
-
-
var tasks
-
-
-
-Source code -
@property
-def tasks(self):
-    # walk overall issues find the stories (based on type)
-    # only for home type repo, otherwise return []
-    return self.issues_by_type("task")
-
-
-
var type
-
-
-
-Source code -
@property
-def type(self):
-    if self.name in ["home"]:
-        return "home"
-    elif self.name.startswith("proj"):
-        return "proj"
-    elif self.name.startswith("org_"):
-        return "org"
-    elif self.name.startswith("www"):
-        return "www"
-    elif self.name.startswith("doc"):
-        return "doc"
-    elif self.name.startswith("cockpit"):
-        return "cockpit"
-    else:
-        return "code"
-
-
-
var types
-
-
-
-Source code -
@property
-def types(self):
-    return GithubRepo.TYPES
-
-
-
-

Methods

-
-
-def create_milestone(self, name, title, description='', deadline='', owner='') -
-
-
-
-Source code -
def create_milestone(self, name, title, description="", deadline="", owner=""):
-    self._log_info('Attempt to create milestone "%s" [%s] deadline %s' % (name, title, deadline))
-
-    def getBody(descr, name, owner):
-        out = "%s\n\n" % descr
-        out += "## name:%s\n" % name
-        out += "## owner:%s\n" % owner
-        return out
-
-    ms = None
-    for s in [name, title]:
-        ms = self.get_milestone(s, die=False)
-        if ms is not None:
-            break
-
-    if ms is not None:
-        if ms.title != title:
-            ms.title = title
-        # if ms.deadline != deadline:
-        #     ms.deadline = deadline
-        tocheck = getBody(description.strip(), name, owner)
-        if ms.body.strip() != tocheck.strip():
-            ms.body = tocheck
-    else:
-        # due = j.data.time.epoch2pythonDateTime(int(j.data.time.getEpochFuture(deadline)))
-        self._log_info("Create milestone on %s: %s" % (self, title))
-        body = getBody(description.strip(), name, owner)
-        # workaround for https://github.com/PyGithub/PyGithub/issues/396
-        milestone = self.api.create_milestone(title=title, description=body)
-        milestone.edit(title=title)
-
-        self._milestones.append(RepoMilestone(self, milestone))
-
-
-
-def delete_milestone(self, name) -
-
-
-
-Source code -
def delete_milestone(self, name):
-    if name.strip() == "":
-        raise Exception("Name cannot be empty.")
-    self._log_info("Delete milestone on %s: '%s'" % (self, name))
-    try:
-        ms = self.get_milestone(name)
-        ms.api.delete()
-        self._milestones = []
-    except Exception:
-        self._log_info("Milestone '%s' doesn't exist. no need to delete" % name)
-
-
-
-def get_color(self, name) -
-
-
-
-Source code -
def get_color(self, name):
-
-    # colors={'state_question':'fbca04',
-    #  'priority_urgent':'d93f0b',
-    #  'state_verification':'006b75',
-    #  'priority_minor':'',
-    #  'type_task':'',
-    #  'type_feature':'',
-    #  'process_wontfix':"ffffff",
-    #  'priority_critical':"b60205",
-    #  'state_inprogress':"e6e6e6",
-    #  'priority_normal':"e6e6e6",
-    #  'type_story':"ee9a00",
-    #  'process_duplicate':"",
-    #  'state_closed':"5319e7",
-    #  'type_bug':"fc2929",
-    #  'state_accepted':"0e8a16",
-    #  'type_question':"fbca04",
-    #  'state_new':"1d76db"}
-
-    if name.startswith("state"):
-        return "c2e0c6"  # light green
-
-    if name.startswith("process"):
-        return "d4c5f9"  # light purple
-
-    if name.startswith("type"):
-        return "fef2c0"  # light yellow
-
-    if name in ("priority_critical", "task_no_estimation"):
-        return "b60205"  # red
-
-    if name.startswith("priority_urgent"):
-        return "d93f0b"
-
-    if name.startswith("priority"):
-        return "f9d0c4"  # roze
-
-    return "ffffff"
-
-
-
-def get_issue(self, issueNumber, die=True) -
-
-
-
-Source code -
def get_issue(self, issueNumber, die=True):
-    for issue in self.issues:
-        if issue.number == issueNumber:
-            return issue
-    # not found in cache, try to load from github
-    github_issue = self.api.get_issue(issueNumber)
-
-    if github_issue:
-        issue = Issue(repo=self, githubObj=github_issue)
-        self._issues.append(issue)
-        return issue
-
-    if die:
-        raise Exception("cannot find issue:%s in repo:%s" % (issueNumber, self))
-    else:
-        i = Issue(self)
-        i._ddict["number"] = issueNumber
-        return i
-
-
-
-def get_issue_from_markdown(self, issueNumber, markdown) -
-
-
-
-Source code -
def get_issue_from_markdown(self, issueNumber, markdown):
-    i = self.get_issue(issueNumber, False)
-    i._loadMD(markdown)
-    self.issues.append(i)
-    return i
-
-
-
-def get_milestone(self, name, die=True) -
-
-
-
-Source code -
def get_milestone(self, name, die=True):
-    name = name.strip()
-    if name == "":
-        raise Exception("Name cannot be empty.")
-    for item in self.milestones:
-        if name == item.name.strip() or name == item.title.strip():
-            return item
-    if die:
-        raise Exception("Could not find milestone with name:%s" % name)
-    else:
-        return None
-
-
-
-def getlabel(self, name) -
-
-
-
-Source code -
def getlabel(self, name):
-    for item in self.labels:
-        self._log_info("%s:look for name:'%s'" % (item.name, name))
-        if item.name == name:
-            return item
-    raise Exception("Dit not find label: '%s'" % name)
-
-
-
-def issues_by_priority(self, filter=None) -
-
-

filter is method which takes -issue as argument and returns True or False to include

-
-Source code -
def issues_by_priority(self, filter=None):
-    """
-    filter is method which takes  issue as argument and returns True or False to include
-    """
-    res = {}
-    for item in self.priorities:
-        res[item] = []
-        for issue in self.issues:
-            if issue.priority == item:
-                if filter is None or filter(issue):
-                    res[item].append(issue)
-    return res
-
-
-
-def issues_by_state(self, filter=None) -
-
-

filter is method which takes -issue as argument and returns True or False to include

-
-Source code -
def issues_by_state(self, filter=None):
-    """
-    filter is method which takes  issue as argument and returns True or False to include
-    """
-    res = {}
-    for item in self.states:
-        res[item] = []
-        for issue in self.issues:
-            if issue.state == item:
-                if filter is None or filter(issue):
-                    res[item].append(issue)
-    return res
-
-
-
-def issues_by_type(self, *types) -
-
-

filter is method which takes -issue as argument and returns True or False to include

-
-Source code -
def issues_by_type(self, *types):
-    """
-    filter is method which takes  issue as argument and returns True or False to include
-    """
-    issues = []
-    for issue in self.issues:
-        if issue.type in types:
-            issues.append(issue)
-
-    return issues
-
-
-
-def issues_by_type_state(self, filter=None, collapsepriority=True) -
-
-

filter is method which takes -issue as argument and returns True or False to include -returns dict of dict keys: type, state and then issues sorted following priority

-
-Source code -
def issues_by_type_state(self, filter=None, collapsepriority=True):
-    """
-    filter is method which takes  issue as argument and returns True or False to include
-    returns dict of dict keys: type, state and then issues sorted following priority
-    """
-    res = {}
-    for type in self.types:
-        res[type] = {}
-        for state in self.states:
-            res[type][state] = {}
-            for priority in self.priorities:
-                res[type][state][priority] = []
-                for issue in self.issues:
-                    if issue.type == type and issue.state == state:
-                        if filter is None or filter(issue):
-                            res[type][state][priority].append(issue)
-            if collapsepriority:
-                # sort the issues following priority
-                temp = res[type][state]
-                res[type][state] = []
-                for priority in self.priorities:
-                    for subitem in temp[priority]:
-                        res[type][state].append(subitem)
-    return res
-
-
-
-def labelsSet(self, labels2set, ignoreDelete=['p_'], delete=True) -
-
-

@param ignore all labels starting with ignore will not be deleted

-
-Source code -
def labelsSet(self, labels2set, ignoreDelete=["p_"], delete=True):
-    """
-    @param ignore all labels starting with ignore will not be deleted
-    """
-
-    for item in labels2set:
-        if not isinstance(item, str):
-            raise Exception("Labels to set need to be in string format, found:%s" % labels2set)
-
-    # walk over github existing labels
-    labelstowalk = copy.copy(self.labels)
-    for item in labelstowalk:
-        name = item.name.lower()
-        if name not in labels2set:
-            # label in repo does not correspond to label we need
-            if name in replacelabels:
-                nameNew = replacelabels[item.name.lower()]
-                if nameNew not in self.labelnames:
-                    color = self.get_color(name)
-                    self._log_info(
-                        "change label in repo: %s oldlabel:'%s' to:'%s' color:%s"
-                        % (self.fullname, item.name, nameNew, color)
-                    )
-                    item.edit(nameNew, color)
-                    self._labels = None
-            else:
-                # no replacement
-                name = "type_unknown"
-                color = self.get_color(name)
-                try:
-                    item.edit(name, color)
-                except BaseException:
-                    item.delete()
-                self._labels = None
-
-    # walk over new labels we need to set
-    for name in labels2set:
-        if name not in self.labelnames:
-            # does not exist yet in repo
-            color = self.get_color(name)
-            self._log_info("create label: %s %s %s" % (self.fullname, name, color))
-            self.api.create_label(name, color)
-            self._labels = None
-
-    name = ""
-
-    if delete:
-        labelstowalk = copy.copy(self.labels)
-        for item in labelstowalk:
-            if item.name not in labels2set:
-                self._log_info("delete label: %s %s" % (self.fullname, item.name))
-                ignoreDeleteDo = False
-                for filteritem in ignoreDelete:
-                    if item.name.startswith(filteritem):
-                        ignoreDeleteDo = True
-                if ignoreDeleteDo is False:
-                    item.delete()
-                self._labels = None
-
-    # check the colors
-    labelstowalk = copy.copy(self.labels)
-    for item in labelstowalk:
-        # we recognise the label
-        self._log_info("check color of repo:%s labelname:'%s'" % (self.fullname, item.name))
-        color = self.get_color(item.name)
-        if item.color != color:
-            self._log_info("change label color for repo %s %s" % (item.name, color))
-            item.edit(item.name, color)
-            self._labels = None
-
-
-
-def set_file(self, path, content, message='update file') -
-
-

Creates or updates the file content at path with given content -:param path: file path README.md -:param content: Plain content of file -:return:

-
-Source code -
def set_file(self, path, content, message="update file"):
-    """
-    Creates or updates the file content at path with given content
-    :param path: file path `README.md`
-    :param content: Plain content of file
-    :return:
-    """
-    bytes = content.encode()
-    encoded = base64.encodebytes(bytes)
-
-    params = {"message": message, "content": encoded.decode()}
-
-    path = urllib.parse.quote(path)
-    try:
-        obj = self.api.get_contents(path)
-        params["sha"] = obj.sha
-        if base64.decodebytes(obj.content.encode()) == bytes:
-            return
-    except UnknownObjectException:
-        pass
-
-    self._log_info('Updating file "%s"' % path)
-    self.api._requester.requestJsonAndCheck("PUT", self.api.url + "/contents/" + path, input=params)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/gogs/gogs.html b/docs/api/jumpscale/clients/gogs/gogs.html deleted file mode 100644 index a01571824..000000000 --- a/docs/api/jumpscale/clients/gogs/gogs.html +++ /dev/null @@ -1,323 +0,0 @@ - - - - - - -jumpscale.clients.gogs.gogs API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gogs.gogs

-
-
-
-Source code -
from jumpscale.clients.base import Base, Client
-from jumpscale.core.base import fields
-
-
-class User(Base):
-    username = fields.String(required=True)
-    password = fields.Secret(required=True)
-
-
-class Gogs(Client):
-    access_token = fields.Secret(required=True)
-    user = fields.Object(User)
-    admins = fields.List(fields.String(required=True), required=True)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class Gogs -(parent_=None, instance_name_=None, **values) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class Gogs(Client):
-    access_token = fields.Secret(required=True)
-    user = fields.Object(User)
-    admins = fields.List(fields.String(required=True), required=True)
-
-

Ancestors

- -

Instance variables

-
-
var access_token
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var admins
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var user
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Inherited members

- -
-
-class User -(parent_=None, instance_name_=None, **values) -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class User(Base):
-    username = fields.String(required=True)
-    password = fields.Secret(required=True)
-
-

Ancestors

-
    -
  • Base
  • -
  • types.SimpleNamespace
  • -
-

Instance variables

-
-
var password
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var username
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/gogs/index.html b/docs/api/jumpscale/clients/gogs/index.html deleted file mode 100644 index 53209f519..000000000 --- a/docs/api/jumpscale/clients/gogs/index.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.clients.gogs API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.gogs

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .gogs import Gogs
-
-    return StoredFactory(Gogs)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.gogs.gogs
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .gogs import Gogs
-
-    return StoredFactory(Gogs)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/mail/index.html b/docs/api/jumpscale/clients/mail/index.html deleted file mode 100644 index b4d989318..000000000 --- a/docs/api/jumpscale/clients/mail/index.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.clients.mail API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.mail

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .mail import MailClient
-
-    return StoredFactory(MailClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.mail.mail
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .mail import MailClient
-
-    return StoredFactory(MailClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/mail/mail.html b/docs/api/jumpscale/clients/mail/mail.html deleted file mode 100644 index cf6f2ccc6..000000000 --- a/docs/api/jumpscale/clients/mail/mail.html +++ /dev/null @@ -1,575 +0,0 @@ - - - - - - -jumpscale.clients.mail.mail API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.mail.mail

-
-
-
-Source code -
from jumpscale.loader import j
-import smtplib
-import mimetypes
-from email import encoders
-from email.mime.audio import MIMEAudio
-from email.mime.base import MIMEBase
-from email.mime.image import MIMEImage
-from email.mime.multipart import MIMEMultipart
-from email.mime.text import MIMEText
-
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-
-class MailClient(Client):
-    name = fields.String()
-    smtp_server = fields.String()
-    smtp_port = fields.Integer()
-    login = fields.String()
-    password = fields.String()
-    sender_email = fields.String()
-
-    def __init__(self):
-        super().__init__()
-
-    @property
-    def is_ssl(self):
-        self.smtp_port in [465, 587]
-
-    def send(self, recipients, sender="", subject="", message="", files=None, mimetype=None):
-        """ Send an email to the recipients from the sender containing the message required and any attached files given by the paths in files
-        :param recipients: Recipients of the message
-        :type recipients: mixed, str or list
-        :param sender: Sender of the email
-        :type sender: str
-        :param subject: Subject of the email
-        :type subject: str
-        :param message: Body of the email
-        :type message: str
-        :param files: List of paths to files to attach
-        :type files: list of strings
-        :param mimetype: Type of the body plain, html or None for autodetection
-        :type mimetype: str
-        """
-        if not sender:
-            sender = self.sender_email
-        if isinstance(recipients, str):
-            recipients = [recipients]
-        server = smtplib.SMTP(self.smtp_server, self.smtp_port)
-        server.ehlo()
-        if self._ssl:
-            server.starttls()
-        if self.login:
-            server.login(self.login, self.password)
-
-        if mimetype is None:
-            if "<html>" in message:
-                mimetype = "html"
-            else:
-                mimetype = "plain"
-
-        msg = MIMEText(message, mimetype)
-
-        msg["Subject"] = subject
-        msg["From"] = sender
-        msg["To"] = ",".join(recipients)
-
-        if files:
-            txtmsg = msg
-            msg = MIMEMultipart()
-            msg["Subject"] = subject
-            msg["From"] = sender
-            msg["To"] = ",".join(recipients)
-            msg.attach(txtmsg)
-            for fl in files:
-                # Guess the content type based on the file's extension.  Encoding
-                # will be ignored, although we should check for simple things like
-                # gzip'd or compressed files.
-                filename = j.sals.fs.basename(fl)
-                ctype, encoding = mimetypes.guess_type(fl)
-                content = j.sals.fs.read_file(fl)
-                if ctype is None or encoding is not None:
-                    # No guess could be made, or the file is encoded (compressed), so
-                    # use a generic bag-of-bits type.
-                    ctype = "application/octet-stream"
-                maintype, subtype = ctype.split("/", 1)
-                if maintype == "text":
-                    attachement = MIMEText(content, _subtype=subtype)
-                elif maintype == "image":
-                    attachement = MIMEImage(content, _subtype=subtype)
-                elif maintype == "audio":
-                    attachement = MIMEAudio(content, _subtype=subtype)
-                else:
-                    attachement = MIMEBase(maintype, subtype)
-                    attachement.set_payload(content)
-                    # Encode the payload using Base64
-                    encoders.encode_base64(attachement)
-                # Set the filename parameter
-                attachement.add_header("Content-Disposition", "attachment", filename=filename)
-                msg.attach(attachement)
-        server.sendmail(sender, recipients, msg.as_string())
-        server.close()
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class MailClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class MailClient(Client):
-    name = fields.String()
-    smtp_server = fields.String()
-    smtp_port = fields.Integer()
-    login = fields.String()
-    password = fields.String()
-    sender_email = fields.String()
-
-    def __init__(self):
-        super().__init__()
-
-    @property
-    def is_ssl(self):
-        self.smtp_port in [465, 587]
-
-    def send(self, recipients, sender="", subject="", message="", files=None, mimetype=None):
-        """ Send an email to the recipients from the sender containing the message required and any attached files given by the paths in files
-        :param recipients: Recipients of the message
-        :type recipients: mixed, str or list
-        :param sender: Sender of the email
-        :type sender: str
-        :param subject: Subject of the email
-        :type subject: str
-        :param message: Body of the email
-        :type message: str
-        :param files: List of paths to files to attach
-        :type files: list of strings
-        :param mimetype: Type of the body plain, html or None for autodetection
-        :type mimetype: str
-        """
-        if not sender:
-            sender = self.sender_email
-        if isinstance(recipients, str):
-            recipients = [recipients]
-        server = smtplib.SMTP(self.smtp_server, self.smtp_port)
-        server.ehlo()
-        if self._ssl:
-            server.starttls()
-        if self.login:
-            server.login(self.login, self.password)
-
-        if mimetype is None:
-            if "<html>" in message:
-                mimetype = "html"
-            else:
-                mimetype = "plain"
-
-        msg = MIMEText(message, mimetype)
-
-        msg["Subject"] = subject
-        msg["From"] = sender
-        msg["To"] = ",".join(recipients)
-
-        if files:
-            txtmsg = msg
-            msg = MIMEMultipart()
-            msg["Subject"] = subject
-            msg["From"] = sender
-            msg["To"] = ",".join(recipients)
-            msg.attach(txtmsg)
-            for fl in files:
-                # Guess the content type based on the file's extension.  Encoding
-                # will be ignored, although we should check for simple things like
-                # gzip'd or compressed files.
-                filename = j.sals.fs.basename(fl)
-                ctype, encoding = mimetypes.guess_type(fl)
-                content = j.sals.fs.read_file(fl)
-                if ctype is None or encoding is not None:
-                    # No guess could be made, or the file is encoded (compressed), so
-                    # use a generic bag-of-bits type.
-                    ctype = "application/octet-stream"
-                maintype, subtype = ctype.split("/", 1)
-                if maintype == "text":
-                    attachement = MIMEText(content, _subtype=subtype)
-                elif maintype == "image":
-                    attachement = MIMEImage(content, _subtype=subtype)
-                elif maintype == "audio":
-                    attachement = MIMEAudio(content, _subtype=subtype)
-                else:
-                    attachement = MIMEBase(maintype, subtype)
-                    attachement.set_payload(content)
-                    # Encode the payload using Base64
-                    encoders.encode_base64(attachement)
-                # Set the filename parameter
-                attachement.add_header("Content-Disposition", "attachment", filename=filename)
-                msg.attach(attachement)
-        server.sendmail(sender, recipients, msg.as_string())
-        server.close()
-
-

Ancestors

- -

Instance variables

-
-
var is_ssl
-
-
-
-Source code -
@property
-def is_ssl(self):
-    self.smtp_port in [465, 587]
-
-
-
var login
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var password
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var sender_email
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var smtp_port
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var smtp_server
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def send(self, recipients, sender='', subject='', message='', files=None, mimetype=None) -
-
-

Send an email to the recipients from the sender containing the message required and any attached files given by the paths in files -:param recipients: Recipients of the message -:type recipients: mixed, str or list -:param sender: Sender of the email -:type sender: str -:param subject: Subject of the email -:type subject: str -:param message: Body of the email -:type message: str -:param files: List of paths to files to attach -:type files: list of strings -:param mimetype: Type of the body plain, html or None for autodetection -:type mimetype: str

-
-Source code -
def send(self, recipients, sender="", subject="", message="", files=None, mimetype=None):
-    """ Send an email to the recipients from the sender containing the message required and any attached files given by the paths in files
-    :param recipients: Recipients of the message
-    :type recipients: mixed, str or list
-    :param sender: Sender of the email
-    :type sender: str
-    :param subject: Subject of the email
-    :type subject: str
-    :param message: Body of the email
-    :type message: str
-    :param files: List of paths to files to attach
-    :type files: list of strings
-    :param mimetype: Type of the body plain, html or None for autodetection
-    :type mimetype: str
-    """
-    if not sender:
-        sender = self.sender_email
-    if isinstance(recipients, str):
-        recipients = [recipients]
-    server = smtplib.SMTP(self.smtp_server, self.smtp_port)
-    server.ehlo()
-    if self._ssl:
-        server.starttls()
-    if self.login:
-        server.login(self.login, self.password)
-
-    if mimetype is None:
-        if "<html>" in message:
-            mimetype = "html"
-        else:
-            mimetype = "plain"
-
-    msg = MIMEText(message, mimetype)
-
-    msg["Subject"] = subject
-    msg["From"] = sender
-    msg["To"] = ",".join(recipients)
-
-    if files:
-        txtmsg = msg
-        msg = MIMEMultipart()
-        msg["Subject"] = subject
-        msg["From"] = sender
-        msg["To"] = ",".join(recipients)
-        msg.attach(txtmsg)
-        for fl in files:
-            # Guess the content type based on the file's extension.  Encoding
-            # will be ignored, although we should check for simple things like
-            # gzip'd or compressed files.
-            filename = j.sals.fs.basename(fl)
-            ctype, encoding = mimetypes.guess_type(fl)
-            content = j.sals.fs.read_file(fl)
-            if ctype is None or encoding is not None:
-                # No guess could be made, or the file is encoded (compressed), so
-                # use a generic bag-of-bits type.
-                ctype = "application/octet-stream"
-            maintype, subtype = ctype.split("/", 1)
-            if maintype == "text":
-                attachement = MIMEText(content, _subtype=subtype)
-            elif maintype == "image":
-                attachement = MIMEImage(content, _subtype=subtype)
-            elif maintype == "audio":
-                attachement = MIMEAudio(content, _subtype=subtype)
-            else:
-                attachement = MIMEBase(maintype, subtype)
-                attachement.set_payload(content)
-                # Encode the payload using Base64
-                encoders.encode_base64(attachement)
-            # Set the filename parameter
-            attachement.add_header("Content-Disposition", "attachment", filename=filename)
-            msg.attach(attachement)
-    server.sendmail(sender, recipients, msg.as_string())
-    server.close()
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/s3/index.html b/docs/api/jumpscale/clients/s3/index.html deleted file mode 100644 index 8576b6079..000000000 --- a/docs/api/jumpscale/clients/s3/index.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.clients.s3 API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.s3

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .s3 import S3Client
-
-    return StoredFactory(S3Client)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.s3.s3
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .s3 import S3Client
-
-    return StoredFactory(S3Client)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/s3/s3.html b/docs/api/jumpscale/clients/s3/s3.html deleted file mode 100644 index e86413912..000000000 --- a/docs/api/jumpscale/clients/s3/s3.html +++ /dev/null @@ -1,719 +0,0 @@ - - - - - - -jumpscale.clients.s3.s3 API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.s3.s3

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import Base, fields
-import urllib3
-import certifi
-
-from minio import Minio
-from minio.error import ResponseError, BucketAlreadyOwnedByYou, BucketAlreadyExists
-
-
-class S3Client(Client):
-    name = fields.String()
-    address = fields.String()
-    port = fields.Integer()
-    access_key = fields.String()
-    secret_key = fields.String()
-    bucket = fields.String()
-    create_bucket = fields.Boolean()
-
-    def __init__(self):
-        super().__init__()
-        # Create the http client to be able to set timeout
-        http_client = urllib3.PoolManager(
-            timeout=5,
-            cert_reqs="CERT_REQUIRED",
-            ca_certs=certifi.where(),
-            retries=urllib3.Retry(total=3, backoff_factor=0.2, status_forcelist=[500, 502, 503, 504]),
-        )
-        # Create Minio client
-        self.client = Minio(
-            "{}:{}".format(self.address, self.port),
-            access_key=self.access_key,
-            secret_key=self.secret_key,
-            secure=False,
-            http_client=http_client,
-        )
-
-        if self.bucket_create:
-            self._bucket_create(self.bucket)
-
-    def _bucket_create(self, name):
-        try:
-            self.client.make_bucket(name, location="us-east-1")
-        except BucketAlreadyOwnedByYou as err:
-            pass
-        except BucketAlreadyExists as err:
-            pass
-        except ResponseError as err:
-            raise
-
-    def upload(self, bucket_name, object_name, file_path, content_type="text/plain", meta_data=None):
-        """Upload contents from a file specified by file_path, to object_name
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object
-        :type object_name: str
-        :param file_path: local path from which object data will be read
-        :type file_path: str
-        :param content_type: content type of the object, defaults to 'text/plain'
-        :type content_type: str, optional
-        :param meta_data: additional metadata, defaults to None
-        :type meta_data: dict, optional
-        :raises ValueError: if file given by file_path is not found
-        :return: str
-        :rtype: Object etag computed by the minio server.
-        """
-        if not j.sals.fs.exists(file_path):
-            raise j.exceptions.Value("file: {} not found".format(file_path))
-        return self.client.fput_object(bucket_name, object_name, file_path, content_type, meta_data)
-
-    def download(self, bucket_name, object_name, file_path):
-        """Download and save the object as a file in the local filesystem
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object
-        :type object_name: str
-        :param file_path: local path to which object data will be written
-        :type file_path: str
-        :return: object stat info (includes: size, etag, content_type,last_modified, metadata)
-        :rtype: Object
-        """
-
-        return self.client.fget_object(bucket_name, object_name, file_path)
-
-    def list_buckets(self):
-        """List all buckets
-
-        :return: bucketList, bucket.name, bucket.creation_date
-        :rtype: function, str, date
-        """
-        return self.client.list_buckets()
-
-    def list_objects(self, bucket_name, prefix=None, recursive=None):
-        """List objects in a specific bucket
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param prefix: prefix of the objects that should be listed, defaults to None
-        :type prefix: str, optional
-        :param recursive: True indicates recursive style listing and False indicates directory style listing delimited by '/', defaults to None
-        :type recursive: bool, optional
-        :return: Iterator for all the objects in the bucket (includes: bucket_name, object_name,is_dir, size, etag, last_modified)
-        :rtype: Object
-        """
-
-        return self.client.list_objects(bucket_name, prefix=prefix, recursive=recursive)
-
-    def remove_bucket(self, bucket_name):
-        """Remove a bucket.
-
-        :param bucket_name: name of bucket to be removed
-        :type bucket_name: str
-        """
-        return self.client.remove_bucket(bucket_name)
-
-    def remove_object(self, bucket_name, object_name):
-        """Remove object from bucket
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object to be removed
-        :type object_name: str
-        """
-
-        return self.client.remove_object(bucket_name, object_name)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class S3Client -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class S3Client(Client):
-    name = fields.String()
-    address = fields.String()
-    port = fields.Integer()
-    access_key = fields.String()
-    secret_key = fields.String()
-    bucket = fields.String()
-    create_bucket = fields.Boolean()
-
-    def __init__(self):
-        super().__init__()
-        # Create the http client to be able to set timeout
-        http_client = urllib3.PoolManager(
-            timeout=5,
-            cert_reqs="CERT_REQUIRED",
-            ca_certs=certifi.where(),
-            retries=urllib3.Retry(total=3, backoff_factor=0.2, status_forcelist=[500, 502, 503, 504]),
-        )
-        # Create Minio client
-        self.client = Minio(
-            "{}:{}".format(self.address, self.port),
-            access_key=self.access_key,
-            secret_key=self.secret_key,
-            secure=False,
-            http_client=http_client,
-        )
-
-        if self.bucket_create:
-            self._bucket_create(self.bucket)
-
-    def _bucket_create(self, name):
-        try:
-            self.client.make_bucket(name, location="us-east-1")
-        except BucketAlreadyOwnedByYou as err:
-            pass
-        except BucketAlreadyExists as err:
-            pass
-        except ResponseError as err:
-            raise
-
-    def upload(self, bucket_name, object_name, file_path, content_type="text/plain", meta_data=None):
-        """Upload contents from a file specified by file_path, to object_name
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object
-        :type object_name: str
-        :param file_path: local path from which object data will be read
-        :type file_path: str
-        :param content_type: content type of the object, defaults to 'text/plain'
-        :type content_type: str, optional
-        :param meta_data: additional metadata, defaults to None
-        :type meta_data: dict, optional
-        :raises ValueError: if file given by file_path is not found
-        :return: str
-        :rtype: Object etag computed by the minio server.
-        """
-        if not j.sals.fs.exists(file_path):
-            raise j.exceptions.Value("file: {} not found".format(file_path))
-        return self.client.fput_object(bucket_name, object_name, file_path, content_type, meta_data)
-
-    def download(self, bucket_name, object_name, file_path):
-        """Download and save the object as a file in the local filesystem
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object
-        :type object_name: str
-        :param file_path: local path to which object data will be written
-        :type file_path: str
-        :return: object stat info (includes: size, etag, content_type,last_modified, metadata)
-        :rtype: Object
-        """
-
-        return self.client.fget_object(bucket_name, object_name, file_path)
-
-    def list_buckets(self):
-        """List all buckets
-
-        :return: bucketList, bucket.name, bucket.creation_date
-        :rtype: function, str, date
-        """
-        return self.client.list_buckets()
-
-    def list_objects(self, bucket_name, prefix=None, recursive=None):
-        """List objects in a specific bucket
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param prefix: prefix of the objects that should be listed, defaults to None
-        :type prefix: str, optional
-        :param recursive: True indicates recursive style listing and False indicates directory style listing delimited by '/', defaults to None
-        :type recursive: bool, optional
-        :return: Iterator for all the objects in the bucket (includes: bucket_name, object_name,is_dir, size, etag, last_modified)
-        :rtype: Object
-        """
-
-        return self.client.list_objects(bucket_name, prefix=prefix, recursive=recursive)
-
-    def remove_bucket(self, bucket_name):
-        """Remove a bucket.
-
-        :param bucket_name: name of bucket to be removed
-        :type bucket_name: str
-        """
-        return self.client.remove_bucket(bucket_name)
-
-    def remove_object(self, bucket_name, object_name):
-        """Remove object from bucket
-
-        :param bucket_name: name of bucket
-        :type bucket_name: str
-        :param object_name: name of object to be removed
-        :type object_name: str
-        """
-
-        return self.client.remove_object(bucket_name, object_name)
-
-

Ancestors

- -

Instance variables

-
-
var access_key
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var address
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var bucket
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var create_bucket
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var port
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var secret_key
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def download(self, bucket_name, object_name, file_path) -
-
-

Download and save the object as a file in the local filesystem

-

:param bucket_name: name of bucket -:type bucket_name: str -:param object_name: name of object -:type object_name: str -:param file_path: local path to which object data will be written -:type file_path: str -:return: object stat info (includes: size, etag, content_type,last_modified, metadata) -:rtype: Object

-
-Source code -
def download(self, bucket_name, object_name, file_path):
-    """Download and save the object as a file in the local filesystem
-
-    :param bucket_name: name of bucket
-    :type bucket_name: str
-    :param object_name: name of object
-    :type object_name: str
-    :param file_path: local path to which object data will be written
-    :type file_path: str
-    :return: object stat info (includes: size, etag, content_type,last_modified, metadata)
-    :rtype: Object
-    """
-
-    return self.client.fget_object(bucket_name, object_name, file_path)
-
-
-
-def list_buckets(self) -
-
-

List all buckets

-

:return: bucketList, bucket.name, bucket.creation_date -:rtype: function, str, date

-
-Source code -
def list_buckets(self):
-    """List all buckets
-
-    :return: bucketList, bucket.name, bucket.creation_date
-    :rtype: function, str, date
-    """
-    return self.client.list_buckets()
-
-
-
-def list_objects(self, bucket_name, prefix=None, recursive=None) -
-
-

List objects in a specific bucket

-

:param bucket_name: name of bucket -:type bucket_name: str -:param prefix: prefix of the objects that should be listed, defaults to None -:type prefix: str, optional -:param recursive: True indicates recursive style listing and False indicates directory style listing delimited by '/', defaults to None -:type recursive: bool, optional -:return: Iterator for all the objects in the bucket (includes: bucket_name, object_name,is_dir, size, etag, last_modified) -:rtype: Object

-
-Source code -
def list_objects(self, bucket_name, prefix=None, recursive=None):
-    """List objects in a specific bucket
-
-    :param bucket_name: name of bucket
-    :type bucket_name: str
-    :param prefix: prefix of the objects that should be listed, defaults to None
-    :type prefix: str, optional
-    :param recursive: True indicates recursive style listing and False indicates directory style listing delimited by '/', defaults to None
-    :type recursive: bool, optional
-    :return: Iterator for all the objects in the bucket (includes: bucket_name, object_name,is_dir, size, etag, last_modified)
-    :rtype: Object
-    """
-
-    return self.client.list_objects(bucket_name, prefix=prefix, recursive=recursive)
-
-
-
-def remove_bucket(self, bucket_name) -
-
-

Remove a bucket.

-

:param bucket_name: name of bucket to be removed -:type bucket_name: str

-
-Source code -
def remove_bucket(self, bucket_name):
-    """Remove a bucket.
-
-    :param bucket_name: name of bucket to be removed
-    :type bucket_name: str
-    """
-    return self.client.remove_bucket(bucket_name)
-
-
-
-def remove_object(self, bucket_name, object_name) -
-
-

Remove object from bucket

-

:param bucket_name: name of bucket -:type bucket_name: str -:param object_name: name of object to be removed -:type object_name: str

-
-Source code -
def remove_object(self, bucket_name, object_name):
-    """Remove object from bucket
-
-    :param bucket_name: name of bucket
-    :type bucket_name: str
-    :param object_name: name of object to be removed
-    :type object_name: str
-    """
-
-    return self.client.remove_object(bucket_name, object_name)
-
-
-
-def upload(self, bucket_name, object_name, file_path, content_type='text/plain', meta_data=None) -
-
-

Upload contents from a file specified by file_path, to object_name

-

:param bucket_name: name of bucket -:type bucket_name: str -:param object_name: name of object -:type object_name: str -:param file_path: local path from which object data will be read -:type file_path: str -:param content_type: content type of the object, defaults to 'text/plain' -:type content_type: str, optional -:param meta_data: additional metadata, defaults to None -:type meta_data: dict, optional -:raises ValueError: if file given by file_path is not found -:return: str -:rtype: Object etag computed by the minio server.

-
-Source code -
def upload(self, bucket_name, object_name, file_path, content_type="text/plain", meta_data=None):
-    """Upload contents from a file specified by file_path, to object_name
-
-    :param bucket_name: name of bucket
-    :type bucket_name: str
-    :param object_name: name of object
-    :type object_name: str
-    :param file_path: local path from which object data will be read
-    :type file_path: str
-    :param content_type: content type of the object, defaults to 'text/plain'
-    :type content_type: str, optional
-    :param meta_data: additional metadata, defaults to None
-    :type meta_data: dict, optional
-    :raises ValueError: if file given by file_path is not found
-    :return: str
-    :rtype: Object etag computed by the minio server.
-    """
-    if not j.sals.fs.exists(file_path):
-        raise j.exceptions.Value("file: {} not found".format(file_path))
-    return self.client.fput_object(bucket_name, object_name, file_path, content_type, meta_data)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/sendgrid/index.html b/docs/api/jumpscale/clients/sendgrid/index.html deleted file mode 100644 index dff1c7ffa..000000000 --- a/docs/api/jumpscale/clients/sendgrid/index.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.clients.sendgrid API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.sendgrid

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .sendgrid import SendGridClient
-
-    return StoredFactory(SendGridClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.sendgrid.sendgrid
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .sendgrid import SendGridClient
-
-    return StoredFactory(SendGridClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/sendgrid/sendgrid.html b/docs/api/jumpscale/clients/sendgrid/sendgrid.html deleted file mode 100644 index b4d36f57d..000000000 --- a/docs/api/jumpscale/clients/sendgrid/sendgrid.html +++ /dev/null @@ -1,292 +0,0 @@ - - - - - - -jumpscale.clients.sendgrid.sendgrid API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.sendgrid.sendgrid

-
-
-
-Source code -
import base64
-import os
-import io
-import sendgrid
-from sendgrid.helpers.mail import Mail, Attachment
-from python_http_client.exceptions import HTTPError
-from jumpscale.loader import j
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-
-
-class SendGridClient(Client):
-    apikey = fields.String()
-
-    def __init__(self):
-        super().__init__()
-
-    def build_attachment(self, filepath, typ="application/pdf"):
-        """
-        Returns a valid sendgrid attachment from typical attachment object.
-        """
-        data = io.BytesIO()
-        with open(filepath, "rb") as f:
-            while True:
-                d = f.read(2 ** 20)
-                if not d:
-                    break
-                data.write(d)
-        data.seek(0)
-        attachment = sendgrid.Attachment()
-        attachment.file_content = j.data.serializers.base64.encode(data.read()).decode()
-        attachment.file_type = typ
-        attachment.file_name = os.path.basename(filepath)
-        attachment.disposition = "attachment"
-        return attachment
-
-    def send(self, sender, subject, html_content="<strong>Email</strong>", recipients=None, attachments=None):
-        recipients = recipients or []
-        attachments = attachments or []
-        recipients = list(set(recipients))
-        mail = Mail(from_email=sender, to_emails=recipients, subject=subject, html_content=html_content)
-        for at in attachments:
-            mail.add_attachment(at)
-        try:
-            sg = sendgrid.SendGridAPIClient(self.apikey)
-            # response=sg.send(mail)
-            response = sg.client.mail.send.post(request_body=mail.get())
-            print(response.status_code)
-            print(response.body)
-            print(response.headers)
-        except HTTPError as e:
-            raise e
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class SendGridClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class SendGridClient(Client):
-    apikey = fields.String()
-
-    def __init__(self):
-        super().__init__()
-
-    def build_attachment(self, filepath, typ="application/pdf"):
-        """
-        Returns a valid sendgrid attachment from typical attachment object.
-        """
-        data = io.BytesIO()
-        with open(filepath, "rb") as f:
-            while True:
-                d = f.read(2 ** 20)
-                if not d:
-                    break
-                data.write(d)
-        data.seek(0)
-        attachment = sendgrid.Attachment()
-        attachment.file_content = j.data.serializers.base64.encode(data.read()).decode()
-        attachment.file_type = typ
-        attachment.file_name = os.path.basename(filepath)
-        attachment.disposition = "attachment"
-        return attachment
-
-    def send(self, sender, subject, html_content="<strong>Email</strong>", recipients=None, attachments=None):
-        recipients = recipients or []
-        attachments = attachments or []
-        recipients = list(set(recipients))
-        mail = Mail(from_email=sender, to_emails=recipients, subject=subject, html_content=html_content)
-        for at in attachments:
-            mail.add_attachment(at)
-        try:
-            sg = sendgrid.SendGridAPIClient(self.apikey)
-            # response=sg.send(mail)
-            response = sg.client.mail.send.post(request_body=mail.get())
-            print(response.status_code)
-            print(response.body)
-            print(response.headers)
-        except HTTPError as e:
-            raise e
-
-

Ancestors

- -

Instance variables

-
-
var apikey
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def build_attachment(self, filepath, typ='application/pdf') -
-
-

Returns a valid sendgrid attachment from typical attachment object.

-
-Source code -
def build_attachment(self, filepath, typ="application/pdf"):
-    """
-    Returns a valid sendgrid attachment from typical attachment object.
-    """
-    data = io.BytesIO()
-    with open(filepath, "rb") as f:
-        while True:
-            d = f.read(2 ** 20)
-            if not d:
-                break
-            data.write(d)
-    data.seek(0)
-    attachment = sendgrid.Attachment()
-    attachment.file_content = j.data.serializers.base64.encode(data.read()).decode()
-    attachment.file_type = typ
-    attachment.file_name = os.path.basename(filepath)
-    attachment.disposition = "attachment"
-    return attachment
-
-
-
-def send(self, sender, subject, html_content='<strong>Email</strong>', recipients=None, attachments=None) -
-
-
-
-Source code -
def send(self, sender, subject, html_content="<strong>Email</strong>", recipients=None, attachments=None):
-    recipients = recipients or []
-    attachments = attachments or []
-    recipients = list(set(recipients))
-    mail = Mail(from_email=sender, to_emails=recipients, subject=subject, html_content=html_content)
-    for at in attachments:
-        mail.add_attachment(at)
-    try:
-        sg = sendgrid.SendGridAPIClient(self.apikey)
-        # response=sg.send(mail)
-        response = sg.client.mail.send.post(request_body=mail.get())
-        print(response.status_code)
-        print(response.body)
-        print(response.headers)
-    except HTTPError as e:
-        raise e
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/sonic/client.html b/docs/api/jumpscale/clients/sonic/client.html deleted file mode 100644 index 232d74b36..000000000 --- a/docs/api/jumpscale/clients/sonic/client.html +++ /dev/null @@ -1,293 +0,0 @@ - - - - - - -jumpscale.clients.sonic.client API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.sonic.client

-
-
-
-Source code -
from sonic import SearchClient, IngestClient
-from jumpscale.clients.base import Client
-from jumpscale.core.base import Base, fields
-
-
-class SonicClient(Client):
-    host = fields.String(default="127.0.0.1")
-    port = fields.Integer(default=1491)
-    password = fields.String(default="pass")
-
-    def __init__(self):
-        super().__init__()
-
-        self.cached_client_search = None
-        self.cached_client_ingest = None
-
-        self.push = self.client_ingest.push
-        self.pop = self.client_ingest.pop
-        self.count = self.client_ingest.count
-        self.flush = self.client_ingest.flush
-        self.flush_collection = self.client_ingest.flush_collection
-        self.flush_bucket = self.client_ingest.flush_bucket
-        self.flush_object = self.client_ingest.flush_object
-
-        self.query = self.client_search.query
-        self.suggest = self.client_search.suggest
-
-    @property
-    def client_ingest(self):
-        if not self.cached_client_ingest:
-            self.cached_client_ingest = IngestClient(host=self.host, port=self.port, password=self.password)
-        return self.cached_client_ingest
-
-    @property
-    def client_search(self):
-        if not self.cached_client_search:
-            self.cached_client_search = SearchClient(host=self.host, port=self.port, password=self.password)
-        return self.cached_client_search
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class SonicClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class SonicClient(Client):
-    host = fields.String(default="127.0.0.1")
-    port = fields.Integer(default=1491)
-    password = fields.String(default="pass")
-
-    def __init__(self):
-        super().__init__()
-
-        self.cached_client_search = None
-        self.cached_client_ingest = None
-
-        self.push = self.client_ingest.push
-        self.pop = self.client_ingest.pop
-        self.count = self.client_ingest.count
-        self.flush = self.client_ingest.flush
-        self.flush_collection = self.client_ingest.flush_collection
-        self.flush_bucket = self.client_ingest.flush_bucket
-        self.flush_object = self.client_ingest.flush_object
-
-        self.query = self.client_search.query
-        self.suggest = self.client_search.suggest
-
-    @property
-    def client_ingest(self):
-        if not self.cached_client_ingest:
-            self.cached_client_ingest = IngestClient(host=self.host, port=self.port, password=self.password)
-        return self.cached_client_ingest
-
-    @property
-    def client_search(self):
-        if not self.cached_client_search:
-            self.cached_client_search = SearchClient(host=self.host, port=self.port, password=self.password)
-        return self.cached_client_search
-
-

Ancestors

- -

Instance variables

-
-
var client_ingest
-
-
-
-Source code -
@property
-def client_ingest(self):
-    if not self.cached_client_ingest:
-        self.cached_client_ingest = IngestClient(host=self.host, port=self.port, password=self.password)
-    return self.cached_client_ingest
-
-
- -
-
-
-Source code -
@property
-def client_search(self):
-    if not self.cached_client_search:
-        self.cached_client_search = SearchClient(host=self.host, port=self.port, password=self.password)
-    return self.cached_client_search
-
-
-
var host
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var password
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var port
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/sonic/index.html b/docs/api/jumpscale/clients/sonic/index.html deleted file mode 100644 index ee3ca2c5d..000000000 --- a/docs/api/jumpscale/clients/sonic/index.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.clients.sonic API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.sonic

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .client import SonicClient
-
-    return StoredFactory(SonicClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.sonic.client
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .client import SonicClient
-
-    return StoredFactory(SonicClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/syncthing/index.html b/docs/api/jumpscale/clients/syncthing/index.html deleted file mode 100644 index 5c669c1c0..000000000 --- a/docs/api/jumpscale/clients/syncthing/index.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.clients.syncthing API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.syncthing

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .syncthing import SyncthingClient
-
-    return StoredFactory(SyncthingClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.syncthing.syncthing
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .syncthing import SyncthingClient
-
-    return StoredFactory(SyncthingClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/syncthing/syncthing.html b/docs/api/jumpscale/clients/syncthing/syncthing.html deleted file mode 100644 index d014f62aa..000000000 --- a/docs/api/jumpscale/clients/syncthing/syncthing.html +++ /dev/null @@ -1,789 +0,0 @@ - - - - - - -jumpscale.clients.syncthing.syncthing API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.syncthing.syncthing

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-from jumpscale.loader import j
-
-
-class SyncthingClient(Client):
-    host = fields.String()
-    port = fields.Integer()
-    apikey = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__url = None
-        self.__session = None
-        self.__config = None
-
-    @property
-    def url(self):
-        if not self.__url:
-            self.__url = f"http://{self.host}:{self.port}/rest"
-        return self.__url
-
-    @property
-    def config(self):
-        if not self.__config:
-            self.__config = self._call("system/config")
-        return self.__config
-
-    @property
-    def session(self):
-        if not self.__session:
-            self.__session = j.tools.http.Session()
-            self.__session.headers = {
-                "Content-Type": "application/json",
-                "User-Agent": "Syncthing Python client",
-                "X-API-Key": self.apikey,
-            }
-        return self.__session
-
-    def _call(self, endpoint, method="get", data=None, return_json=True):
-        method_call = getattr(self.session, method)
-        response = method_call(f"{self.url}/{endpoint}", json=data)
-        response.raise_for_status()
-
-        if return_json:
-            return response.json()
-        else:
-            return response.content
-
-    def restart(self):
-        self._call("system/restart", "post")
-        if not j.sals.nettools.wait_connection_test(self.host, self.port, timeout=3):
-            j.exceptions.Timeout("Server didn't start in 3 seconds")
-
-    def get_status(self):
-        return self._call("system/status")
-
-    def get_id(self):
-        return self.get_status()["myID"]
-
-    def reload_config(self):
-        self.__config = None
-
-    def set_config(self, config=None):
-        self._call("system/config", "post", config or self.config, False)
-
-    def get_folders(self):
-        return self.config["folders"]
-
-    def get_devices(self):
-        return self.config["devices"]
-
-    def _get_folder(self, name):
-        for idx, folder in enumerate(self.get_folders()):
-            if folder["id"] == name:
-                return idx
-
-    def _get_device(self, name):
-        for idx, device in enumerate(self.get_devices()):
-            if device["name"] == name:
-                return idx
-
-    def check_folder(self, name):
-        return self._get_folder(name) is not None
-
-    def check_device(self, name):
-        return self._get_device(name) is not None
-
-    def delete_folder(self, name):
-        folders = self.get_folders()
-        idx = self._get_folder(name)
-        if idx:
-            folders.pop(idx)
-            return self.set_config(self.config)
-
-    def delete_device(self, name):
-        devices = self.get_devices()
-        idx = self._get_device(name)
-        if idx:
-            devices.pop(idx)
-            return self.set_config(self.config)
-
-    def add_folder(
-        self,
-        name,
-        path,
-        ignore_perms=False,
-        read_only=False,
-        rescan_intervals=10,
-        devices=None,
-        overwrite=False,
-    ):
-        folders = self.get_folders()
-        idx = self._get_folder(name)
-        if idx:
-            if overwrite:
-                folders.pop(idx)
-            else:
-                raise j.exceptions.Input(f"Folder with name: {name} already exists")
-        devices = devices or []
-        my_id = self.get_id()
-        if my_id not in devices:
-            devices.append(my_id)
-        devices = [{"deviceID": device} for device in devices]
-        folder = {
-            "autoNormalize": False,
-            "copiers": 0,
-            "devices": devices,
-            "hashers": 0,
-            "id": name,
-            "ignoreDelete": False,
-            "ignorePerms": ignore_perms,
-            "invalid": "",
-            "minDiskFreePct": 5,
-            "order": "random",
-            "path": path,
-            "pullers": 0,
-            "readOnly": read_only,
-            "rescanIntervalS": rescan_intervals,
-            "versioning": {"params": {}, "type": ""},
-        }
-        folders.append(folder)
-        return self.set_config(self.config)
-
-    def add_device(
-        self, name, device_id, introducer=False, compression="always", overwrite=False
-    ):
-        devices = self.get_devices()
-        idx = self._get_device(name)
-        if idx:
-            if overwrite:
-                devices.pop(idx)
-            else:
-                raise j.exceptions.Input(f"Device with name: {name} already exists")
-        device = {
-            "addresses": ["dynamic"],
-            "certName": "",
-            "compression": compression,
-            "deviceID": device_id,
-            "introducer": introducer,
-            "name": name,
-        }
-        devices.append(device)
-        return self.set_config(self.config)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class SyncthingClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class SyncthingClient(Client):
-    host = fields.String()
-    port = fields.Integer()
-    apikey = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__url = None
-        self.__session = None
-        self.__config = None
-
-    @property
-    def url(self):
-        if not self.__url:
-            self.__url = f"http://{self.host}:{self.port}/rest"
-        return self.__url
-
-    @property
-    def config(self):
-        if not self.__config:
-            self.__config = self._call("system/config")
-        return self.__config
-
-    @property
-    def session(self):
-        if not self.__session:
-            self.__session = j.tools.http.Session()
-            self.__session.headers = {
-                "Content-Type": "application/json",
-                "User-Agent": "Syncthing Python client",
-                "X-API-Key": self.apikey,
-            }
-        return self.__session
-
-    def _call(self, endpoint, method="get", data=None, return_json=True):
-        method_call = getattr(self.session, method)
-        response = method_call(f"{self.url}/{endpoint}", json=data)
-        response.raise_for_status()
-
-        if return_json:
-            return response.json()
-        else:
-            return response.content
-
-    def restart(self):
-        self._call("system/restart", "post")
-        if not j.sals.nettools.wait_connection_test(self.host, self.port, timeout=3):
-            j.exceptions.Timeout("Server didn't start in 3 seconds")
-
-    def get_status(self):
-        return self._call("system/status")
-
-    def get_id(self):
-        return self.get_status()["myID"]
-
-    def reload_config(self):
-        self.__config = None
-
-    def set_config(self, config=None):
-        self._call("system/config", "post", config or self.config, False)
-
-    def get_folders(self):
-        return self.config["folders"]
-
-    def get_devices(self):
-        return self.config["devices"]
-
-    def _get_folder(self, name):
-        for idx, folder in enumerate(self.get_folders()):
-            if folder["id"] == name:
-                return idx
-
-    def _get_device(self, name):
-        for idx, device in enumerate(self.get_devices()):
-            if device["name"] == name:
-                return idx
-
-    def check_folder(self, name):
-        return self._get_folder(name) is not None
-
-    def check_device(self, name):
-        return self._get_device(name) is not None
-
-    def delete_folder(self, name):
-        folders = self.get_folders()
-        idx = self._get_folder(name)
-        if idx:
-            folders.pop(idx)
-            return self.set_config(self.config)
-
-    def delete_device(self, name):
-        devices = self.get_devices()
-        idx = self._get_device(name)
-        if idx:
-            devices.pop(idx)
-            return self.set_config(self.config)
-
-    def add_folder(
-        self,
-        name,
-        path,
-        ignore_perms=False,
-        read_only=False,
-        rescan_intervals=10,
-        devices=None,
-        overwrite=False,
-    ):
-        folders = self.get_folders()
-        idx = self._get_folder(name)
-        if idx:
-            if overwrite:
-                folders.pop(idx)
-            else:
-                raise j.exceptions.Input(f"Folder with name: {name} already exists")
-        devices = devices or []
-        my_id = self.get_id()
-        if my_id not in devices:
-            devices.append(my_id)
-        devices = [{"deviceID": device} for device in devices]
-        folder = {
-            "autoNormalize": False,
-            "copiers": 0,
-            "devices": devices,
-            "hashers": 0,
-            "id": name,
-            "ignoreDelete": False,
-            "ignorePerms": ignore_perms,
-            "invalid": "",
-            "minDiskFreePct": 5,
-            "order": "random",
-            "path": path,
-            "pullers": 0,
-            "readOnly": read_only,
-            "rescanIntervalS": rescan_intervals,
-            "versioning": {"params": {}, "type": ""},
-        }
-        folders.append(folder)
-        return self.set_config(self.config)
-
-    def add_device(
-        self, name, device_id, introducer=False, compression="always", overwrite=False
-    ):
-        devices = self.get_devices()
-        idx = self._get_device(name)
-        if idx:
-            if overwrite:
-                devices.pop(idx)
-            else:
-                raise j.exceptions.Input(f"Device with name: {name} already exists")
-        device = {
-            "addresses": ["dynamic"],
-            "certName": "",
-            "compression": compression,
-            "deviceID": device_id,
-            "introducer": introducer,
-            "name": name,
-        }
-        devices.append(device)
-        return self.set_config(self.config)
-
-

Ancestors

- -

Instance variables

-
-
var apikey
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var config
-
-
-
-Source code -
@property
-def config(self):
-    if not self.__config:
-        self.__config = self._call("system/config")
-    return self.__config
-
-
-
var host
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var port
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var session
-
-
-
-Source code -
@property
-def session(self):
-    if not self.__session:
-        self.__session = j.tools.http.Session()
-        self.__session.headers = {
-            "Content-Type": "application/json",
-            "User-Agent": "Syncthing Python client",
-            "X-API-Key": self.apikey,
-        }
-    return self.__session
-
-
-
var url
-
-
-
-Source code -
@property
-def url(self):
-    if not self.__url:
-        self.__url = f"http://{self.host}:{self.port}/rest"
-    return self.__url
-
-
-
-

Methods

-
-
-def add_device(self, name, device_id, introducer=False, compression='always', overwrite=False) -
-
-
-
-Source code -
def add_device(
-    self, name, device_id, introducer=False, compression="always", overwrite=False
-):
-    devices = self.get_devices()
-    idx = self._get_device(name)
-    if idx:
-        if overwrite:
-            devices.pop(idx)
-        else:
-            raise j.exceptions.Input(f"Device with name: {name} already exists")
-    device = {
-        "addresses": ["dynamic"],
-        "certName": "",
-        "compression": compression,
-        "deviceID": device_id,
-        "introducer": introducer,
-        "name": name,
-    }
-    devices.append(device)
-    return self.set_config(self.config)
-
-
-
-def add_folder(self, name, path, ignore_perms=False, read_only=False, rescan_intervals=10, devices=None, overwrite=False) -
-
-
-
-Source code -
def add_folder(
-    self,
-    name,
-    path,
-    ignore_perms=False,
-    read_only=False,
-    rescan_intervals=10,
-    devices=None,
-    overwrite=False,
-):
-    folders = self.get_folders()
-    idx = self._get_folder(name)
-    if idx:
-        if overwrite:
-            folders.pop(idx)
-        else:
-            raise j.exceptions.Input(f"Folder with name: {name} already exists")
-    devices = devices or []
-    my_id = self.get_id()
-    if my_id not in devices:
-        devices.append(my_id)
-    devices = [{"deviceID": device} for device in devices]
-    folder = {
-        "autoNormalize": False,
-        "copiers": 0,
-        "devices": devices,
-        "hashers": 0,
-        "id": name,
-        "ignoreDelete": False,
-        "ignorePerms": ignore_perms,
-        "invalid": "",
-        "minDiskFreePct": 5,
-        "order": "random",
-        "path": path,
-        "pullers": 0,
-        "readOnly": read_only,
-        "rescanIntervalS": rescan_intervals,
-        "versioning": {"params": {}, "type": ""},
-    }
-    folders.append(folder)
-    return self.set_config(self.config)
-
-
-
-def check_device(self, name) -
-
-
-
-Source code -
def check_device(self, name):
-    return self._get_device(name) is not None
-
-
-
-def check_folder(self, name) -
-
-
-
-Source code -
def check_folder(self, name):
-    return self._get_folder(name) is not None
-
-
-
-def delete_device(self, name) -
-
-
-
-Source code -
def delete_device(self, name):
-    devices = self.get_devices()
-    idx = self._get_device(name)
-    if idx:
-        devices.pop(idx)
-        return self.set_config(self.config)
-
-
-
-def delete_folder(self, name) -
-
-
-
-Source code -
def delete_folder(self, name):
-    folders = self.get_folders()
-    idx = self._get_folder(name)
-    if idx:
-        folders.pop(idx)
-        return self.set_config(self.config)
-
-
-
-def get_devices(self) -
-
-
-
-Source code -
def get_devices(self):
-    return self.config["devices"]
-
-
-
-def get_folders(self) -
-
-
-
-Source code -
def get_folders(self):
-    return self.config["folders"]
-
-
-
-def get_id(self) -
-
-
-
-Source code -
def get_id(self):
-    return self.get_status()["myID"]
-
-
-
-def get_status(self) -
-
-
-
-Source code -
def get_status(self):
-    return self._call("system/status")
-
-
-
-def reload_config(self) -
-
-
-
-Source code -
def reload_config(self):
-    self.__config = None
-
-
-
-def restart(self) -
-
-
-
-Source code -
def restart(self):
-    self._call("system/restart", "post")
-    if not j.sals.nettools.wait_connection_test(self.host, self.port, timeout=3):
-        j.exceptions.Timeout("Server didn't start in 3 seconds")
-
-
-
-def set_config(self, config=None) -
-
-
-
-Source code -
def set_config(self, config=None):
-    self._call("system/config", "post", config or self.config, False)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/trello/index.html b/docs/api/jumpscale/clients/trello/index.html deleted file mode 100644 index d301609e9..000000000 --- a/docs/api/jumpscale/clients/trello/index.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.clients.trello API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.trello

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .trello import TrelloClient
-
-    return StoredFactory(TrelloClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.trello.trello
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .trello import TrelloClient
-
-    return StoredFactory(TrelloClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/trello/trello.html b/docs/api/jumpscale/clients/trello/trello.html deleted file mode 100644 index f5021f9e2..000000000 --- a/docs/api/jumpscale/clients/trello/trello.html +++ /dev/null @@ -1,319 +0,0 @@ - - - - - - -jumpscale.clients.trello.trello API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.trello.trello

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-from jumpscale.loader import j
-from trello import TrelloClient as TrelloAPIClient
-from trello.util import create_oauth_token
-
-
-class TrelloClient(Client):
-
-    name = fields.String()
-    api_key_ = fields.String()
-    secret = fields.String()
-    access_token = fields.String()
-    acess_token_secret= fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def trello_client(self):
-
-        if not self.token_secret:
-            # print("**WILL TRY TO DO OAUTH SESSION")
-            access_token = create_oauth_token(key=self.api_key, secret=self.secret)
-            self.access_token_ = access_token["oauth_token"]
-            self.access_token_secret = access_token["oauth_token_secret"]
-
-        self.client = TrelloAPIClient(api_key=self.api_key_, api_secret=self.secret, token=self.token, token_secret=self.token_secret)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class TrelloClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class TrelloClient(Client):
-
-    name = fields.String()
-    api_key_ = fields.String()
-    secret = fields.String()
-    access_token = fields.String()
-    acess_token_secret= fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def trello_client(self):
-
-        if not self.token_secret:
-            # print("**WILL TRY TO DO OAUTH SESSION")
-            access_token = create_oauth_token(key=self.api_key, secret=self.secret)
-            self.access_token_ = access_token["oauth_token"]
-            self.access_token_secret = access_token["oauth_token_secret"]
-
-        self.client = TrelloAPIClient(api_key=self.api_key_, api_secret=self.secret, token=self.token, token_secret=self.token_secret)
-
-

Ancestors

- -

Instance variables

-
-
var access_token
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var acess_token_secret
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var api_key_
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var name
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var secret
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var trello_client
-
-
-
-Source code -
@property
-def trello_client(self):
-
-    if not self.token_secret:
-        # print("**WILL TRY TO DO OAUTH SESSION")
-        access_token = create_oauth_token(key=self.api_key, secret=self.secret)
-        self.access_token_ = access_token["oauth_token"]
-        self.access_token_secret = access_token["oauth_token_secret"]
-
-    self.client = TrelloAPIClient(api_key=self.api_key_, api_secret=self.secret, token=self.token, token_secret=self.token_secret)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/twilio/index.html b/docs/api/jumpscale/clients/twilio/index.html deleted file mode 100644 index 0bddcecc2..000000000 --- a/docs/api/jumpscale/clients/twilio/index.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.clients.twilio API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.twilio

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .twilio import TwilioSMSClient
-
-    StoredFactory(TwilioSMSClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.twilio.twilio
-
-
-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-    from .twilio import TwilioSMSClient
-
-    StoredFactory(TwilioSMSClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/twilio/twilio.html b/docs/api/jumpscale/clients/twilio/twilio.html deleted file mode 100644 index b1f4baba5..000000000 --- a/docs/api/jumpscale/clients/twilio/twilio.html +++ /dev/null @@ -1,290 +0,0 @@ - - - - - - -jumpscale.clients.twilio.twilio API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.twilio.twilio

-
-
-
-Source code -
from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-
-# Download the helper library from https://www.twilio.com/docs/python/install
-from twilio.rest import Client as TwilioRestClient
-
-
-class TwilioSMSClient(Client):
-    """Your Account Sid and Auth Token from twilio.com/console
-        DANGER! This is insecure. See http://twil.io/secure
-    """
-
-    account_sid = fields.String()
-    auth_token = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def twilio_rest_client(self):
-        if not self.__client:
-            self.__client = TwilioRestClient(self.account_sid, self.auth_token)
-        return self.__client
-
-    def send_sms(self, body, sender, recievers=None):
-        """send sms
-            Your Account Sid and Auth Token from twilio.com/console
-            DANGER! This is insecure. See http://twil.io/secure
-        Arguments:
-            body (string) : the sms text
-            sender (text) : sender full number ex: +15558675310
-
-        Keyword Arguments:
-            recievers (list) : recievers phone numbers
-        """
-        recievers = recievers or []
-        for r in recievers:
-            message = self.twilio_rest_client.messages.create(body=body, from_=sender, to=r)
-            print(message.sid)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class TwilioSMSClient -
-
-

Your Account Sid and Auth Token from twilio.com/console -DANGER! This is insecure. See http://twil.io/secure

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class TwilioSMSClient(Client):
-    """Your Account Sid and Auth Token from twilio.com/console
-        DANGER! This is insecure. See http://twil.io/secure
-    """
-
-    account_sid = fields.String()
-    auth_token = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self.__client = None
-
-    @property
-    def twilio_rest_client(self):
-        if not self.__client:
-            self.__client = TwilioRestClient(self.account_sid, self.auth_token)
-        return self.__client
-
-    def send_sms(self, body, sender, recievers=None):
-        """send sms
-            Your Account Sid and Auth Token from twilio.com/console
-            DANGER! This is insecure. See http://twil.io/secure
-        Arguments:
-            body (string) : the sms text
-            sender (text) : sender full number ex: +15558675310
-
-        Keyword Arguments:
-            recievers (list) : recievers phone numbers
-        """
-        recievers = recievers or []
-        for r in recievers:
-            message = self.twilio_rest_client.messages.create(body=body, from_=sender, to=r)
-            print(message.sid)
-
-

Ancestors

- -

Instance variables

-
-
var account_sid
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var auth_token
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var twilio_rest_client
-
-
-
-Source code -
@property
-def twilio_rest_client(self):
-    if not self.__client:
-        self.__client = TwilioRestClient(self.account_sid, self.auth_token)
-    return self.__client
-
-
-
-

Methods

-
-
-def send_sms(self, body, sender, recievers=None) -
-
-

send sms -Your Account Sid and Auth Token from twilio.com/console -DANGER! This is insecure. See http://twil.io/secure

-

Arguments

-

body (string) : the sms text -sender (text) : sender full number ex: +15558675310 -Keyword Arguments: -recievers (list) : recievers phone numbers

-
-Source code -
def send_sms(self, body, sender, recievers=None):
-    """send sms
-        Your Account Sid and Auth Token from twilio.com/console
-        DANGER! This is insecure. See http://twil.io/secure
-    Arguments:
-        body (string) : the sms text
-        sender (text) : sender full number ex: +15558675310
-
-    Keyword Arguments:
-        recievers (list) : recievers phone numbers
-    """
-    recievers = recievers or []
-    for r in recievers:
-        message = self.twilio_rest_client.messages.create(body=body, from_=sender, to=r)
-        print(message.sid)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/zerotier/index.html b/docs/api/jumpscale/clients/zerotier/index.html deleted file mode 100644 index e24357f31..000000000 --- a/docs/api/jumpscale/clients/zerotier/index.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.clients.zerotier API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.zerotier

-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .zerotier import ZerotierClient
-
-    return StoredFactory(ZerotierClient)
-
-
-
-

Sub-modules

-
-
jumpscale.clients.zerotier.zerotier
-
-

A client that gives an interface to the zerotier api …

-
-
-
-
-
-
-

Functions

-
-
-def export_module_as() -
-
-
-
-Source code -
def export_module_as():
-    from jumpscale.core.base import StoredFactory
-
-    from .zerotier import ZerotierClient
-
-    return StoredFactory(ZerotierClient)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/clients/zerotier/zerotier.html b/docs/api/jumpscale/clients/zerotier/zerotier.html deleted file mode 100644 index fedf24a9b..000000000 --- a/docs/api/jumpscale/clients/zerotier/zerotier.html +++ /dev/null @@ -1,1048 +0,0 @@ - - - - - - -jumpscale.clients.zerotier.zerotier API documentation - - - - - - - - - -
-
-
-

Module jumpscale.clients.zerotier.zerotier

-
-
-

A client that gives an interface to the zerotier api

-
zcl = j.clients.zerotier.get("instance")
-
-network = zcl.get_network("network_id")
-
-#  list routes
-network.routes
-
-# add members
-
-member = network.add_member(address, name="guest")
-
-# Authorize member to this network
-member.authorize()
-
-
-
-Source code -
"""
-A client that gives an interface to the zerotier api
-
-```python
-zcl = j.clients.zerotier.get("instance")
-
-network = zcl.get_network("network_id")
-
-#  list routes
-network.routes
-
-# add members
-
-member = network.add_member(address, name="guest")
-
-# Authorize member to this network
-member.authorize()
-
-```
-
-"""
-
-
-import requests
-import ipaddress
-from jumpscale.loader import j
-from jumpscale.clients.base import Client
-from jumpscale.core.base import fields
-
-
-class Member:
-    def __init__(self, member_data, network, address=None):
-        self.raw_data = member_data
-        self._address = address
-        self._network = network
-        self.id = member_data["id"]
-
-    @property
-    def address(self):
-        if not self._address:
-            self._address = self.identity.split(":")[0]
-        return self._address
-
-    @property
-    def identity(self):
-        return self.raw_data["config"]["identity"]
-
-    @property
-    def private_ip(self):
-        return self.raw_data["config"]["ipAssignments"]
-
-    def _update_authorization(self, authorize):
-        if self.raw_data["config"]["authorized"] == authorize:
-            return
-        self._network.update_member(self.address, authorized=authorize)
-        self.raw_data["config"]["authorized"] = authorize
-
-    def authorize(self):
-        """Authorize member to the zerotier network
-        """
-        self._update_authorization(True)
-
-    def unauthorize(self):
-        """Unauthorize member to the zerotier network
-        """
-        self._update_authorization(False)
-
-    def __repr__(self):
-        return f"Member({self.id})"
-
-
-class Network:
-    def __init__(self, network_data, client):
-        self.id = network_data["id"]
-        self._client = client
-        self.raw_data = network_data
-
-    @property
-    def name(self):
-        return self.raw_data["config"]["name"]
-
-    @property
-    def routes(self):
-        return self.raw_data["config"]["routes"]
-
-    def list_members(self):
-        """List all members of  that network
-
-        Returns:
-            list: List of all members
-        """
-        return [Member(member, self) for member in self._client._send_request(f"network/{self.id}/member")]
-
-    def add_member(self, address, name=None, private_ip=None, authorized=True):
-        """Add a member to the network
-
-        Args:
-            address (str): Address of the member
-            name (str, optional): Name of the member. Defaults to None.
-            private_ip (str, optional): Private IP to assign. Defaults to None.
-            authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-        Returns:
-            Member: Added member
-        """
-        data = {"config": {"authorized": authorized}, "name": name}
-        if private_ip:
-            data["config"]["ipAssignments"] = [private_ip]
-        member_data = self._client._send_request(f"network/{self.id}/member/{address}", method="post", data=data)
-        return Member(member_data, self, address)
-
-    def update_member(self, address, name=None, private_ip=None, authorized=None):
-        """Update a member in the network
-
-        Args:
-            address (str): Address of the member
-            name (str, optional): Name of the member. Defaults to None.
-            private_ip (str, optional): Private IP to assign. Defaults to None.
-            authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-        Returns:
-            Member: Added member
-        """
-        return self.add_member(address, name, private_ip, authorized)
-
-    def get_member(self, address):
-        """Returns member by address
-
-        Args:
-            address (str): Member address
-
-        Returns:
-            Member: Found member
-        """
-        return Member(self._client._send_request(f"network/{self.id}/member/{address}"), self, address)
-
-    def delete_member(self, address):
-        """Deletes a member
-
-        Args:
-            address (str): Member address
-        """
-        self._client._send_request(f"network/{self.id}/member/{address}", method="delete", return_json=False)
-
-    def __repr__(self):
-        return f"Network({self.id})"
-
-
-class ZerotierClient(Client):
-    base_url = fields.String(default="https://my.zerotier.com/api")
-    token = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self._session = None
-
-    def _send_request(self, path, method="get", data=None, return_json=True):
-        url = f"{self.base_url}/{path}"
-        func_method = getattr(self.session, method)
-        res = func_method(url, json=data)
-        res.raise_for_status()
-        if return_json:
-            return res.json()
-        else:
-            return res.content
-
-    @property
-    def session(self):
-        if not self._session:
-            if not self.token:
-                raise j.exceptions.Value("Please set token to use the client")
-            self._session = requests.Session()
-            self._session.headers["Authorization"] = f"Bearer {self.token}"
-        return self._session
-
-    def list_networks(self):
-        """List networks available to user
-
-        Returns:
-            list: All available networks
-        """
-        return [Network(network, self) for network in self._send_request("network")]
-
-    def get_network(self, network_id):
-        """Get network by id
-
-        Args:
-            network_id (str): Network id
-
-        Returns:
-            Network: Found network
-        """
-        return Network(self._send_request(f"network/{network_id}"), self)
-
-    def create_network(self, public, target_subnet=None, name=None, auto_assign=True):
-        """Create a new network
-
-        Args:
-            public (bool): Specify if network is public or not
-            target_subnet (str, optional): Target network to be pick assignment ips from. Defaults to None.
-            name (str, optional): Name of the network. Defaults to None.
-            auto_assign (bool, optional): If true auto assign addresses. Defaults to True.
-
-        Returns:
-            Network: Created network
-        """
-        routes = None
-        config = {"private": not public, "noAutoAssignIps": not auto_assign, "routes": routes}
-        if target_subnet:
-            routes.append({"target": target_subnet, "via": None})
-            network = ipaddress.IPv4Network(target_subnet)
-            config["ipAssignmentPools"] = [{"ipRangeStart": network[0], "ipRangeEnd": network[-1]}]
-
-        if name:
-            config.update({"name": name})
-
-        data = {"config": config}
-        return Network(self._send_request(f"network", data=data, method="post"), self)
-
-    def delete_network(self, network_id):
-        """Deletes network
-
-        Args:
-            network_id (str): Network id
-        """
-        self._send_request(f"network/{network_id}", method="delete", return_json=False)
-
-    def get_status(self):
-        return self._send_request("status")
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class Member -(member_data, network, address=None) -
-
-
-
-Source code -
class Member:
-    def __init__(self, member_data, network, address=None):
-        self.raw_data = member_data
-        self._address = address
-        self._network = network
-        self.id = member_data["id"]
-
-    @property
-    def address(self):
-        if not self._address:
-            self._address = self.identity.split(":")[0]
-        return self._address
-
-    @property
-    def identity(self):
-        return self.raw_data["config"]["identity"]
-
-    @property
-    def private_ip(self):
-        return self.raw_data["config"]["ipAssignments"]
-
-    def _update_authorization(self, authorize):
-        if self.raw_data["config"]["authorized"] == authorize:
-            return
-        self._network.update_member(self.address, authorized=authorize)
-        self.raw_data["config"]["authorized"] = authorize
-
-    def authorize(self):
-        """Authorize member to the zerotier network
-        """
-        self._update_authorization(True)
-
-    def unauthorize(self):
-        """Unauthorize member to the zerotier network
-        """
-        self._update_authorization(False)
-
-    def __repr__(self):
-        return f"Member({self.id})"
-
-

Instance variables

-
-
var address
-
-
-
-Source code -
@property
-def address(self):
-    if not self._address:
-        self._address = self.identity.split(":")[0]
-    return self._address
-
-
-
var identity
-
-
-
-Source code -
@property
-def identity(self):
-    return self.raw_data["config"]["identity"]
-
-
-
var private_ip
-
-
-
-Source code -
@property
-def private_ip(self):
-    return self.raw_data["config"]["ipAssignments"]
-
-
-
-

Methods

-
-
-def authorize(self) -
-
-

Authorize member to the zerotier network

-
-Source code -
def authorize(self):
-    """Authorize member to the zerotier network
-    """
-    self._update_authorization(True)
-
-
-
-def unauthorize(self) -
-
-

Unauthorize member to the zerotier network

-
-Source code -
def unauthorize(self):
-    """Unauthorize member to the zerotier network
-    """
-    self._update_authorization(False)
-
-
-
-
-
-class Network -(network_data, client) -
-
-
-
-Source code -
class Network:
-    def __init__(self, network_data, client):
-        self.id = network_data["id"]
-        self._client = client
-        self.raw_data = network_data
-
-    @property
-    def name(self):
-        return self.raw_data["config"]["name"]
-
-    @property
-    def routes(self):
-        return self.raw_data["config"]["routes"]
-
-    def list_members(self):
-        """List all members of  that network
-
-        Returns:
-            list: List of all members
-        """
-        return [Member(member, self) for member in self._client._send_request(f"network/{self.id}/member")]
-
-    def add_member(self, address, name=None, private_ip=None, authorized=True):
-        """Add a member to the network
-
-        Args:
-            address (str): Address of the member
-            name (str, optional): Name of the member. Defaults to None.
-            private_ip (str, optional): Private IP to assign. Defaults to None.
-            authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-        Returns:
-            Member: Added member
-        """
-        data = {"config": {"authorized": authorized}, "name": name}
-        if private_ip:
-            data["config"]["ipAssignments"] = [private_ip]
-        member_data = self._client._send_request(f"network/{self.id}/member/{address}", method="post", data=data)
-        return Member(member_data, self, address)
-
-    def update_member(self, address, name=None, private_ip=None, authorized=None):
-        """Update a member in the network
-
-        Args:
-            address (str): Address of the member
-            name (str, optional): Name of the member. Defaults to None.
-            private_ip (str, optional): Private IP to assign. Defaults to None.
-            authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-        Returns:
-            Member: Added member
-        """
-        return self.add_member(address, name, private_ip, authorized)
-
-    def get_member(self, address):
-        """Returns member by address
-
-        Args:
-            address (str): Member address
-
-        Returns:
-            Member: Found member
-        """
-        return Member(self._client._send_request(f"network/{self.id}/member/{address}"), self, address)
-
-    def delete_member(self, address):
-        """Deletes a member
-
-        Args:
-            address (str): Member address
-        """
-        self._client._send_request(f"network/{self.id}/member/{address}", method="delete", return_json=False)
-
-    def __repr__(self):
-        return f"Network({self.id})"
-
-

Instance variables

-
-
var name
-
-
-
-Source code -
@property
-def name(self):
-    return self.raw_data["config"]["name"]
-
-
-
var routes
-
-
-
-Source code -
@property
-def routes(self):
-    return self.raw_data["config"]["routes"]
-
-
-
-

Methods

-
-
-def add_member(self, address, name=None, private_ip=None, authorized=True) -
-
-

Add a member to the network

-

Args

-
-
address : str
-
Address of the member
-
name : str, optional
-
Name of the member. Defaults to None.
-
private_ip : str, optional
-
Private IP to assign. Defaults to None.
-
authorized : bool, optional
-
Whether to authorize the user or not. Defaults to True.
-
-

Returns

-
-
Member
-
Added member
-
-
-Source code -
def add_member(self, address, name=None, private_ip=None, authorized=True):
-    """Add a member to the network
-
-    Args:
-        address (str): Address of the member
-        name (str, optional): Name of the member. Defaults to None.
-        private_ip (str, optional): Private IP to assign. Defaults to None.
-        authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-    Returns:
-        Member: Added member
-    """
-    data = {"config": {"authorized": authorized}, "name": name}
-    if private_ip:
-        data["config"]["ipAssignments"] = [private_ip]
-    member_data = self._client._send_request(f"network/{self.id}/member/{address}", method="post", data=data)
-    return Member(member_data, self, address)
-
-
-
-def delete_member(self, address) -
-
-

Deletes a member

-

Args

-
-
address : str
-
Member address
-
-
-Source code -
def delete_member(self, address):
-    """Deletes a member
-
-    Args:
-        address (str): Member address
-    """
-    self._client._send_request(f"network/{self.id}/member/{address}", method="delete", return_json=False)
-
-
-
-def get_member(self, address) -
-
-

Returns member by address

-

Args

-
-
address : str
-
Member address
-
-

Returns

-
-
Member
-
Found member
-
-
-Source code -
def get_member(self, address):
-    """Returns member by address
-
-    Args:
-        address (str): Member address
-
-    Returns:
-        Member: Found member
-    """
-    return Member(self._client._send_request(f"network/{self.id}/member/{address}"), self, address)
-
-
-
-def list_members(self) -
-
-

List all members of -that network

-

Returns

-
-
list
-
List of all members
-
-
-Source code -
def list_members(self):
-    """List all members of  that network
-
-    Returns:
-        list: List of all members
-    """
-    return [Member(member, self) for member in self._client._send_request(f"network/{self.id}/member")]
-
-
-
-def update_member(self, address, name=None, private_ip=None, authorized=None) -
-
-

Update a member in the network

-

Args

-
-
address : str
-
Address of the member
-
name : str, optional
-
Name of the member. Defaults to None.
-
private_ip : str, optional
-
Private IP to assign. Defaults to None.
-
authorized : bool, optional
-
Whether to authorize the user or not. Defaults to True.
-
-

Returns

-
-
Member
-
Added member
-
-
-Source code -
def update_member(self, address, name=None, private_ip=None, authorized=None):
-    """Update a member in the network
-
-    Args:
-        address (str): Address of the member
-        name (str, optional): Name of the member. Defaults to None.
-        private_ip (str, optional): Private IP to assign. Defaults to None.
-        authorized (bool, optional): Whether to authorize the user or not. Defaults to True.
-
-    Returns:
-        Member: Added member
-    """
-    return self.add_member(address, name, private_ip, authorized)
-
-
-
-
-
-class ZerotierClient -
-
-

A simple attribute-based namespace.

-

SimpleNamespace(**kwargs)

-

base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

-

any instance can have an optional name and a parent.

-
class Person(Base):
-    name = fields.String()
-    age = fields.Float()
-
-p = Person(name="ahmed", age="19")
-print(p.name, p.age)
-
-

Args

-
-
parent_ : Base, optional
-
parent instance. Defaults to None.
-
instance_name_ : str, optional
-
instance name. Defaults to None.
-
**values
-
any given field values to initiate the instance with
-
-
-Source code -
class ZerotierClient(Client):
-    base_url = fields.String(default="https://my.zerotier.com/api")
-    token = fields.String()
-
-    def __init__(self):
-        super().__init__()
-        self._session = None
-
-    def _send_request(self, path, method="get", data=None, return_json=True):
-        url = f"{self.base_url}/{path}"
-        func_method = getattr(self.session, method)
-        res = func_method(url, json=data)
-        res.raise_for_status()
-        if return_json:
-            return res.json()
-        else:
-            return res.content
-
-    @property
-    def session(self):
-        if not self._session:
-            if not self.token:
-                raise j.exceptions.Value("Please set token to use the client")
-            self._session = requests.Session()
-            self._session.headers["Authorization"] = f"Bearer {self.token}"
-        return self._session
-
-    def list_networks(self):
-        """List networks available to user
-
-        Returns:
-            list: All available networks
-        """
-        return [Network(network, self) for network in self._send_request("network")]
-
-    def get_network(self, network_id):
-        """Get network by id
-
-        Args:
-            network_id (str): Network id
-
-        Returns:
-            Network: Found network
-        """
-        return Network(self._send_request(f"network/{network_id}"), self)
-
-    def create_network(self, public, target_subnet=None, name=None, auto_assign=True):
-        """Create a new network
-
-        Args:
-            public (bool): Specify if network is public or not
-            target_subnet (str, optional): Target network to be pick assignment ips from. Defaults to None.
-            name (str, optional): Name of the network. Defaults to None.
-            auto_assign (bool, optional): If true auto assign addresses. Defaults to True.
-
-        Returns:
-            Network: Created network
-        """
-        routes = None
-        config = {"private": not public, "noAutoAssignIps": not auto_assign, "routes": routes}
-        if target_subnet:
-            routes.append({"target": target_subnet, "via": None})
-            network = ipaddress.IPv4Network(target_subnet)
-            config["ipAssignmentPools"] = [{"ipRangeStart": network[0], "ipRangeEnd": network[-1]}]
-
-        if name:
-            config.update({"name": name})
-
-        data = {"config": config}
-        return Network(self._send_request(f"network", data=data, method="post"), self)
-
-    def delete_network(self, network_id):
-        """Deletes network
-
-        Args:
-            network_id (str): Network id
-        """
-        self._send_request(f"network/{network_id}", method="delete", return_json=False)
-
-    def get_status(self):
-        return self._send_request("status")
-
-

Ancestors

- -

Instance variables

-
-
var base_url
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
var session
-
-
-
-Source code -
@property
-def session(self):
-    if not self._session:
-        if not self.token:
-            raise j.exceptions.Value("Please set token to use the client")
-        self._session = requests.Session()
-        self._session.headers["Authorization"] = f"Bearer {self.token}"
-    return self._session
-
-
-
var token
-
-

getter method this property

-

Returns

-
-
any
-
the field value
-
-
-Source code -
def getter(self):
-    """
-    getter method this property
-
-    Returns:
-        any: the field value
-    """
-    # if it's already defined, just return it
-    if hasattr(self, inner_name):
-        return getattr(self, inner_name)
-
-    # if not, it will just return the default value of the field
-    # accept raw value as default too
-    return field.from_raw(field.default)
-
-
-
-

Methods

-
-
-def create_network(self, public, target_subnet=None, name=None, auto_assign=True) -
-
-

Create a new network

-

Args

-
-
public : bool
-
Specify if network is public or not
-
target_subnet : str, optional
-
Target network to be pick assignment ips from. Defaults to None.
-
name : str, optional
-
Name of the network. Defaults to None.
-
auto_assign : bool, optional
-
If true auto assign addresses. Defaults to True.
-
-

Returns

-
-
Network
-
Created network
-
-
-Source code -
def create_network(self, public, target_subnet=None, name=None, auto_assign=True):
-    """Create a new network
-
-    Args:
-        public (bool): Specify if network is public or not
-        target_subnet (str, optional): Target network to be pick assignment ips from. Defaults to None.
-        name (str, optional): Name of the network. Defaults to None.
-        auto_assign (bool, optional): If true auto assign addresses. Defaults to True.
-
-    Returns:
-        Network: Created network
-    """
-    routes = None
-    config = {"private": not public, "noAutoAssignIps": not auto_assign, "routes": routes}
-    if target_subnet:
-        routes.append({"target": target_subnet, "via": None})
-        network = ipaddress.IPv4Network(target_subnet)
-        config["ipAssignmentPools"] = [{"ipRangeStart": network[0], "ipRangeEnd": network[-1]}]
-
-    if name:
-        config.update({"name": name})
-
-    data = {"config": config}
-    return Network(self._send_request(f"network", data=data, method="post"), self)
-
-
-
-def delete_network(self, network_id) -
-
-

Deletes network

-

Args

-
-
network_id : str
-
Network id
-
-
-Source code -
def delete_network(self, network_id):
-    """Deletes network
-
-    Args:
-        network_id (str): Network id
-    """
-    self._send_request(f"network/{network_id}", method="delete", return_json=False)
-
-
-
-def get_network(self, network_id) -
-
-

Get network by id

-

Args

-
-
network_id : str
-
Network id
-
-

Returns

-
-
Network
-
Found network
-
-
-Source code -
def get_network(self, network_id):
-    """Get network by id
-
-    Args:
-        network_id (str): Network id
-
-    Returns:
-        Network: Found network
-    """
-    return Network(self._send_request(f"network/{network_id}"), self)
-
-
-
-def get_status(self) -
-
-
-
-Source code -
def get_status(self):
-    return self._send_request("status")
-
-
-
-def list_networks(self) -
-
-

List networks available to user

-

Returns

-
-
list
-
All available networks
-
-
-Source code -
def list_networks(self):
-    """List networks available to user
-
-    Returns:
-        list: All available networks
-    """
-    return [Network(network, self) for network in self._send_request("network")]
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/core/base/store.html b/docs/api/jumpscale/core/base/store.html deleted file mode 100644 index 500d661ec..000000000 --- a/docs/api/jumpscale/core/base/store.html +++ /dev/null @@ -1,1941 +0,0 @@ - - - - - - -jumpscale.core.base.store API documentation - - - - - - - - - -
-
-
-

Module jumpscale.core.base.store

-
-
-

Store defines the interface for the backend storage, let it be filesystem or redis.

-

This module also defines the abstractions needed for any storage backend.

-

Every backend should be able to organize configuration for multiple instance given a location, also -read/write the config data in raw (string) format.

-
-Source code -
"""
-Store defines the interface for the backend storage, let it be filesystem or redis.
-
-This module also defines the abstractions needed for any storage backend.
-
-Every backend should be able to organize configuration for multiple instance given a location, also
-read/write the config data in raw (string) format.
-"""
-
-
-import os
-import shutil
-
-import redis
-
-from abc import ABC, abstractmethod
-from enum import Enum
-
-from jumpscale.data.nacl import NACL
-from jumpscale.data.serializers import base64, json
-from jumpscale.core.config import Environment
-from jumpscale.sals.fs import read_file_binary, write_file_binary, rmtree
-
-
-class InvalidPrivateKey(Exception):
-    """
-    raised when the private key configured is invalid
-    """
-
-
-class Location:
-    """
-    dot-separated auto-location for any type
-
-    for example, if we have a class in jumpscale/clients/redis/<type>
-    location name will be jumpscale.clients.redis.<type>
-    """
-
-    def __init__(self, *name_list):
-        self.name_list = list(name_list)
-
-    @property
-    def name(self):
-        """
-        get dot seprated string from current name list
-
-        Returns:
-            str: dot separated string
-        """
-        return ".".join(self.name_list)
-
-    @property
-    def path(self):
-        """
-        get a filesystem path with from `name`, where dots are replaced by `os.sep`
-
-        Returns:
-            str: path
-        """
-        return os.path.join(*self.name.split("."))
-
-    @classmethod
-    def from_type(cls, type_):
-        """
-        get a location from any type/class
-
-        Args:
-            type_ (type): any type (class)
-
-        Returns:
-            Location: a location object
-        """
-        return cls(type_.__module__, type_.__name__)
-
-    def __str__(self):
-        args = "', '".join(self.name_list)
-        cls_name = self.__class__.__name__
-        return f"{cls_name}('{args}')"
-
-    __repr__ = __str__
-
-
-class EncryptionMode(Enum):
-    """
-    An enum to select encryption mode based on loading or storing the data
-    """
-
-    Encrypt = 0
-    Decrypt = 1
-
-
-class EncryptionMixin:
-    """
-    A mixin that provides encrypt and decrypt methods, which can be used in any store
-    """
-
-    def encrypt(self, data):
-        """encrypt data
-
-        Args:
-            data (str): input string
-
-        Returns:
-            bytes: encrypted data as byte string
-        """
-        if not isinstance(data, bytes):
-            data = data.encode()
-        return self.nacl.encrypt(data, self.public_key)
-
-    def decrypt(self, data):
-        """decrypt data
-
-        Args:
-            data (bytes): encrypted byte string
-
-        Returns:
-            str: decrypted data
-        """
-        return self.nacl.decrypt(data, self.public_key).decode()
-
-
-class ConfigStore(ABC):
-    """
-    the interface every config store should implement:
-
-    - `read(instance_name)`:  reads the data of this instance name
-    - `write(instance_name, data)`: writes the data of this instance
-    - `list_all(instance_name)`: lists all instance names
-    - `delete(instance_name)`: delete instance data
-    """
-
-    @abstractmethod
-    def read(self, instance_name):
-        pass
-
-    @abstractmethod
-    def write(self, instance_name, data):
-        pass
-
-    @abstractmethod
-    def list_all(self):
-        pass
-
-    @abstractmethod
-    def delete(self, instance_name):
-        pass
-
-
-class EncryptedConfigStore(ConfigStore, EncryptionMixin):
-    """the base class for any config store backend"""
-
-    def __init__(self, location):
-        self.location = location
-        self.config_env = Environment()
-        self.priv_key = base64.decode(self.config_env.get_private_key())
-        self.nacl = NACL(private_key=self.priv_key)
-        self.public_key = self.nacl.public_key.encode()
-
-        if not self.priv_key:
-            raise InvalidPrivateKey
-
-    def _encrypt_value(self, value):
-        """
-        encrypt a single value
-
-        Args:
-            value (str): value
-
-        Returns:
-            str: decrypted value
-        """
-        return base64.encode(self.encrypt(value)).decode("ascii")
-
-    def _decrypt_value(self, value):
-        """
-        decrypt a single value
-
-        Args:
-            value (str): value
-
-        Returns:
-            str: decrypted value
-        """
-        return self.decrypt(base64.decode(value))
-
-    def _process_config(self, config, mode):
-        """
-        process current config according to encryption mode
-
-        Args:
-            config (dict): config dict (can be nested)
-            mode (EncryptionMode)
-        """
-        new_config = {}
-        for name, value in config.items():
-            if name.startswith("__") and value is not None:
-                if mode == EncryptionMode.Decrypt:
-                    new_config[name.lstrip("__")] = self._decrypt_value(value)
-                else:
-                    # preserve __ to know it's an encrypted value
-                    new_config[name] = self._encrypt_value(value)
-            elif isinstance(value, dict):
-                new_config[name] = self._process_config(value, mode)
-            else:
-                new_config[name] = value
-        return new_config
-
-    def get(self, instance_name):
-        """
-        get instance config
-
-        Args:
-            instance_name (str): instance name
-
-        Returns:
-            dict: instance config as dict
-        """
-        config = json.loads(self.read(instance_name))
-        return self._process_config(config, EncryptionMode.Decrypt)
-
-    def save(self, instance_name, config):
-        """
-        save instance config
-
-        Args:
-            instance_name (str): name
-            config (dict): config data, any key that starts with `__` will be encrypted
-
-        Returns:
-            bool: written or not
-        """
-        new_config = self._process_config(config, EncryptionMode.Encrypt)
-        return self.write(instance_name, json.dumps(new_config))
-
-
-class FileSystemStore(EncryptedConfigStore):
-    """
-    Filesystem store is an EncryptedConfigStore
-
-    It saves the config relative to `config_env.get_store_config("filesystem")`
-
-    To store every instance config in a different path, it uses the given `Location`.
-    """
-
-    def __init__(self, location):
-        """
-        create a new `FileSystemStore` that stores config at the given location under configured root.
-
-        The root directory can be configured, see `jumpscale.core.config`
-
-        Args:
-            location (Location): where config will be stored per instance
-        """
-        super(FileSystemStore, self).__init__(location)
-        self.root = self.config_env.get_store_config("filesystem")["path"]
-
-    @property
-    def config_root(self):
-        """
-        get the root directory where all configurations are written
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.root, self.location.path)
-
-    def get_instance_root(self, instance_name):
-        """
-        get the directory where instance config is written
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.config_root, instance_name)
-
-    def get_path(self, instance_name):
-        """
-        get the path to data file where instance config is written
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.get_instance_root(instance_name), "data")
-
-    def make_path(self, path):
-        """
-        to ensure the given path, create it if it does not exist
-
-        Args:
-            path (str): path
-        """
-        if not os.path.exists(path):
-            os.makedirs(os.path.dirname(path), exist_ok=True)
-            os.mknod(path)
-
-    def read(self, instance_name):
-        """
-        read config data from the data file
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: data
-        """
-        path = self.get_path(instance_name)
-        return read_file_binary(path)
-
-    def list_all(self):
-        """
-        list all instance names (directories under config root)
-
-        Returns:
-            list: instance/directory names
-        """
-        if not os.path.exists(self.config_root):
-            return []
-        return os.listdir(self.config_root)
-
-    def write(self, instance_name, data):
-        """
-        write config data to data file
-
-        Args:
-            instance_name (str): config
-            data (str): data
-
-        Returns:
-            bool: written or not
-        """
-        path = self.get_path(instance_name)
-        self.make_path(path)
-        return write_file_binary(path, data.encode())
-
-    def delete(self, instance_name):
-        """
-        delete instance config directory
-
-        Args:
-            instance_name (str):
-        """
-        path = self.get_instance_root(instance_name)
-        if os.path.exists(path):
-            rmtree(path)
-
-
-class RedisStore(EncryptedConfigStore):
-    """
-    RedisStore store is an EncryptedConfigStore
-
-    It saves the data in redis and configuration for redis comes from `config_env.get_store_config("redis")`
-    """
-
-    def __init__(self, location):
-        """
-        create a new redis store, the location given will be used to generate keys
-
-        this keys will be combined to get/set instance config
-
-        Args:
-            location (Location)
-        """
-        super().__init__(location)
-        redis_config = self.config_env.get_store_config("redis")
-        self.redis_client = redis.Redis(redis_config["hostname"], redis_config["port"])
-
-    def get_key(self, instance_name):
-        """
-        get a key for an instance
-
-        this will return a dot-separated key derived from current location
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: key
-        """
-        return ".".join([self.location.name, instance_name])
-
-    def read(self, instance_name):
-        """
-        read instance config from redis
-
-        Args:
-            instance_name (name): name
-
-        Returns:
-            str: data
-        """
-        return self.redis_client.get(self.get_key(instance_name))
-
-    def _full_scan(self, pattern):
-        """
-        get the full result of a scan command on current redis database by this pattern
-
-        Args:
-            pattern ([type]): [description]
-        """
-        keys = []
-        cursor, values = self.redis_client.scan(0, pattern)
-
-        while values:
-            keys += values
-            if not cursor:
-                break
-            cursor, values = self.redis_client.scan(cursor, pattern)
-
-        return keys
-
-    def get_location_keys(self):
-        """
-        get all keys under current location (scanned)
-
-        Returns:
-            list: a list of keys
-        """
-        return self._full_scan(f"{self.location.name}.*")
-
-    def get_instance_keys(self, instance_name):
-        """
-        get all instance related keys (scanned)
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            list: list of keys
-        """
-        return self._full_scan(f"{self.location.name}.{instance_name}*")
-
-    def list_all(self):
-        """
-        get all names of instances (instance keys)
-
-        Returns:
-            [type]: [description]
-        """
-        names = []
-
-        keys = self.get_location_keys()
-        for key in keys:
-            # remove location name part
-            name = key.decode().replace(self.location.name, "").lstrip(".")
-            if "." not in name:
-                names.append(name)
-        return names
-
-    def write(self, instance_name, data):
-        """
-        set data with the corresponding key for this instance
-
-        Args:
-            instance_name (str): name
-            data (str): data
-
-        Returns:
-            bool: written or not
-        """
-        return self.redis_client.set(self.get_key(instance_name), data)
-
-    def delete(self, instance_name):
-        """
-        delete all instance related keys
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            bool
-        """
-        keys = self.get_instance_keys(instance_name)
-        if keys:
-            return self.redis_client.delete(*keys)
-        return True
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class ConfigStore -(*args, **kwargs) -
-
-

the interface every config store should implement:

-
    -
  • read(instance_name): -reads the data of this instance name
  • -
  • write(instance_name, data): writes the data of this instance
  • -
  • list_all(instance_name): lists all instance names
  • -
  • delete(instance_name): delete instance data
  • -
-
-Source code -
class ConfigStore(ABC):
-    """
-    the interface every config store should implement:
-
-    - `read(instance_name)`:  reads the data of this instance name
-    - `write(instance_name, data)`: writes the data of this instance
-    - `list_all(instance_name)`: lists all instance names
-    - `delete(instance_name)`: delete instance data
-    """
-
-    @abstractmethod
-    def read(self, instance_name):
-        pass
-
-    @abstractmethod
-    def write(self, instance_name, data):
-        pass
-
-    @abstractmethod
-    def list_all(self):
-        pass
-
-    @abstractmethod
-    def delete(self, instance_name):
-        pass
-
-

Ancestors

-
    -
  • abc.ABC
  • -
-

Subclasses

- -

Methods

-
-
-def delete(self, instance_name) -
-
-
-
-Source code -
@abstractmethod
-def delete(self, instance_name):
-    pass
-
-
-
-def list_all(self) -
-
-
-
-Source code -
@abstractmethod
-def list_all(self):
-    pass
-
-
-
-def read(self, instance_name) -
-
-
-
-Source code -
@abstractmethod
-def read(self, instance_name):
-    pass
-
-
-
-def write(self, instance_name, data) -
-
-
-
-Source code -
@abstractmethod
-def write(self, instance_name, data):
-    pass
-
-
-
-
-
-class EncryptedConfigStore -(location) -
-
-

the base class for any config store backend

-
-Source code -
class EncryptedConfigStore(ConfigStore, EncryptionMixin):
-    """the base class for any config store backend"""
-
-    def __init__(self, location):
-        self.location = location
-        self.config_env = Environment()
-        self.priv_key = base64.decode(self.config_env.get_private_key())
-        self.nacl = NACL(private_key=self.priv_key)
-        self.public_key = self.nacl.public_key.encode()
-
-        if not self.priv_key:
-            raise InvalidPrivateKey
-
-    def _encrypt_value(self, value):
-        """
-        encrypt a single value
-
-        Args:
-            value (str): value
-
-        Returns:
-            str: decrypted value
-        """
-        return base64.encode(self.encrypt(value)).decode("ascii")
-
-    def _decrypt_value(self, value):
-        """
-        decrypt a single value
-
-        Args:
-            value (str): value
-
-        Returns:
-            str: decrypted value
-        """
-        return self.decrypt(base64.decode(value))
-
-    def _process_config(self, config, mode):
-        """
-        process current config according to encryption mode
-
-        Args:
-            config (dict): config dict (can be nested)
-            mode (EncryptionMode)
-        """
-        new_config = {}
-        for name, value in config.items():
-            if name.startswith("__") and value is not None:
-                if mode == EncryptionMode.Decrypt:
-                    new_config[name.lstrip("__")] = self._decrypt_value(value)
-                else:
-                    # preserve __ to know it's an encrypted value
-                    new_config[name] = self._encrypt_value(value)
-            elif isinstance(value, dict):
-                new_config[name] = self._process_config(value, mode)
-            else:
-                new_config[name] = value
-        return new_config
-
-    def get(self, instance_name):
-        """
-        get instance config
-
-        Args:
-            instance_name (str): instance name
-
-        Returns:
-            dict: instance config as dict
-        """
-        config = json.loads(self.read(instance_name))
-        return self._process_config(config, EncryptionMode.Decrypt)
-
-    def save(self, instance_name, config):
-        """
-        save instance config
-
-        Args:
-            instance_name (str): name
-            config (dict): config data, any key that starts with `__` will be encrypted
-
-        Returns:
-            bool: written or not
-        """
-        new_config = self._process_config(config, EncryptionMode.Encrypt)
-        return self.write(instance_name, json.dumps(new_config))
-
-

Ancestors

- -

Subclasses

- -

Methods

-
-
-def get(self, instance_name) -
-
-

get instance config

-

Args

-
-
instance_name : str
-
instance name
-
-

Returns

-
-
dict
-
instance config as dict
-
-
-Source code -
def get(self, instance_name):
-    """
-    get instance config
-
-    Args:
-        instance_name (str): instance name
-
-    Returns:
-        dict: instance config as dict
-    """
-    config = json.loads(self.read(instance_name))
-    return self._process_config(config, EncryptionMode.Decrypt)
-
-
-
-def save(self, instance_name, config) -
-
-

save instance config

-

Args

-
-
instance_name : str
-
name
-
config : dict
-
config data, any key that starts with __ will be encrypted
-
-

Returns

-
-
bool
-
written or not
-
-
-Source code -
def save(self, instance_name, config):
-    """
-    save instance config
-
-    Args:
-        instance_name (str): name
-        config (dict): config data, any key that starts with `__` will be encrypted
-
-    Returns:
-        bool: written or not
-    """
-    new_config = self._process_config(config, EncryptionMode.Encrypt)
-    return self.write(instance_name, json.dumps(new_config))
-
-
-
-

Inherited members

- -
-
-class EncryptionMixin -(*args, **kwargs) -
-
-

A mixin that provides encrypt and decrypt methods, which can be used in any store

-
-Source code -
class EncryptionMixin:
-    """
-    A mixin that provides encrypt and decrypt methods, which can be used in any store
-    """
-
-    def encrypt(self, data):
-        """encrypt data
-
-        Args:
-            data (str): input string
-
-        Returns:
-            bytes: encrypted data as byte string
-        """
-        if not isinstance(data, bytes):
-            data = data.encode()
-        return self.nacl.encrypt(data, self.public_key)
-
-    def decrypt(self, data):
-        """decrypt data
-
-        Args:
-            data (bytes): encrypted byte string
-
-        Returns:
-            str: decrypted data
-        """
-        return self.nacl.decrypt(data, self.public_key).decode()
-
-

Subclasses

- -

Methods

-
-
-def decrypt(self, data) -
-
-

decrypt data

-

Args

-
-
data : bytes
-
encrypted byte string
-
-

Returns

-
-
str
-
decrypted data
-
-
-Source code -
def decrypt(self, data):
-    """decrypt data
-
-    Args:
-        data (bytes): encrypted byte string
-
-    Returns:
-        str: decrypted data
-    """
-    return self.nacl.decrypt(data, self.public_key).decode()
-
-
-
-def encrypt(self, data) -
-
-

encrypt data

-

Args

-
-
data : str
-
input string
-
-

Returns

-
-
bytes
-
encrypted data as byte string
-
-
-Source code -
def encrypt(self, data):
-    """encrypt data
-
-    Args:
-        data (str): input string
-
-    Returns:
-        bytes: encrypted data as byte string
-    """
-    if not isinstance(data, bytes):
-        data = data.encode()
-    return self.nacl.encrypt(data, self.public_key)
-
-
-
-
-
-class EncryptionMode -(*args, **kwargs) -
-
-

An enum to select encryption mode based on loading or storing the data

-
-Source code -
class EncryptionMode(Enum):
-    """
-    An enum to select encryption mode based on loading or storing the data
-    """
-
-    Encrypt = 0
-    Decrypt = 1
-
-

Ancestors

-
    -
  • enum.Enum
  • -
-

Class variables

-
-
var Decrypt
-
-
-
-
var Encrypt
-
-
-
-
-
-
-class FileSystemStore -(location) -
-
-

Filesystem store is an EncryptedConfigStore

-

It saves the config relative to config_env.get_store_config("filesystem")

-

To store every instance config in a different path, it uses the given Location.

-

create a new FileSystemStore that stores config at the given location under configured root.

-

The root directory can be configured, see jumpscale.core.config

-

Args

-
-
location : Location
-
where config will be stored per instance
-
-
-Source code -
class FileSystemStore(EncryptedConfigStore):
-    """
-    Filesystem store is an EncryptedConfigStore
-
-    It saves the config relative to `config_env.get_store_config("filesystem")`
-
-    To store every instance config in a different path, it uses the given `Location`.
-    """
-
-    def __init__(self, location):
-        """
-        create a new `FileSystemStore` that stores config at the given location under configured root.
-
-        The root directory can be configured, see `jumpscale.core.config`
-
-        Args:
-            location (Location): where config will be stored per instance
-        """
-        super(FileSystemStore, self).__init__(location)
-        self.root = self.config_env.get_store_config("filesystem")["path"]
-
-    @property
-    def config_root(self):
-        """
-        get the root directory where all configurations are written
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.root, self.location.path)
-
-    def get_instance_root(self, instance_name):
-        """
-        get the directory where instance config is written
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.config_root, instance_name)
-
-    def get_path(self, instance_name):
-        """
-        get the path to data file where instance config is written
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: path
-        """
-        return os.path.join(self.get_instance_root(instance_name), "data")
-
-    def make_path(self, path):
-        """
-        to ensure the given path, create it if it does not exist
-
-        Args:
-            path (str): path
-        """
-        if not os.path.exists(path):
-            os.makedirs(os.path.dirname(path), exist_ok=True)
-            os.mknod(path)
-
-    def read(self, instance_name):
-        """
-        read config data from the data file
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: data
-        """
-        path = self.get_path(instance_name)
-        return read_file_binary(path)
-
-    def list_all(self):
-        """
-        list all instance names (directories under config root)
-
-        Returns:
-            list: instance/directory names
-        """
-        if not os.path.exists(self.config_root):
-            return []
-        return os.listdir(self.config_root)
-
-    def write(self, instance_name, data):
-        """
-        write config data to data file
-
-        Args:
-            instance_name (str): config
-            data (str): data
-
-        Returns:
-            bool: written or not
-        """
-        path = self.get_path(instance_name)
-        self.make_path(path)
-        return write_file_binary(path, data.encode())
-
-    def delete(self, instance_name):
-        """
-        delete instance config directory
-
-        Args:
-            instance_name (str):
-        """
-        path = self.get_instance_root(instance_name)
-        if os.path.exists(path):
-            rmtree(path)
-
-

Ancestors

- -

Instance variables

-
-
var config_root
-
-

get the root directory where all configurations are written

-

Returns

-
-
str
-
path
-
-
-Source code -
@property
-def config_root(self):
-    """
-    get the root directory where all configurations are written
-
-    Returns:
-        str: path
-    """
-    return os.path.join(self.root, self.location.path)
-
-
-
-

Methods

-
-
-def delete(self, instance_name) -
-
-

delete instance config directory

-

Args

-

instance_name (str):

-
-Source code -
def delete(self, instance_name):
-    """
-    delete instance config directory
-
-    Args:
-        instance_name (str):
-    """
-    path = self.get_instance_root(instance_name)
-    if os.path.exists(path):
-        rmtree(path)
-
-
-
-def get_instance_root(self, instance_name) -
-
-

get the directory where instance config is written

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
str
-
path
-
-
-Source code -
def get_instance_root(self, instance_name):
-    """
-    get the directory where instance config is written
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        str: path
-    """
-    return os.path.join(self.config_root, instance_name)
-
-
-
-def get_path(self, instance_name) -
-
-

get the path to data file where instance config is written

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
str
-
path
-
-
-Source code -
def get_path(self, instance_name):
-    """
-    get the path to data file where instance config is written
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        str: path
-    """
-    return os.path.join(self.get_instance_root(instance_name), "data")
-
-
-
-def list_all(self) -
-
-

list all instance names (directories under config root)

-

Returns

-
-
list
-
instance/directory names
-
-
-Source code -
def list_all(self):
-    """
-    list all instance names (directories under config root)
-
-    Returns:
-        list: instance/directory names
-    """
-    if not os.path.exists(self.config_root):
-        return []
-    return os.listdir(self.config_root)
-
-
-
-def make_path(self, path) -
-
-

to ensure the given path, create it if it does not exist

-

Args

-
-
path : str
-
path
-
-
-Source code -
def make_path(self, path):
-    """
-    to ensure the given path, create it if it does not exist
-
-    Args:
-        path (str): path
-    """
-    if not os.path.exists(path):
-        os.makedirs(os.path.dirname(path), exist_ok=True)
-        os.mknod(path)
-
-
-
-def read(self, instance_name) -
-
-

read config data from the data file

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
str
-
data
-
-
-Source code -
def read(self, instance_name):
-    """
-    read config data from the data file
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        str: data
-    """
-    path = self.get_path(instance_name)
-    return read_file_binary(path)
-
-
-
-def write(self, instance_name, data) -
-
-

write config data to data file

-

Args

-
-
instance_name : str
-
config
-
data : str
-
data
-
-

Returns

-
-
bool
-
written or not
-
-
-Source code -
def write(self, instance_name, data):
-    """
-    write config data to data file
-
-    Args:
-        instance_name (str): config
-        data (str): data
-
-    Returns:
-        bool: written or not
-    """
-    path = self.get_path(instance_name)
-    self.make_path(path)
-    return write_file_binary(path, data.encode())
-
-
-
-

Inherited members

- -
-
-class InvalidPrivateKey -(*args, **kwargs) -
-
-

raised when the private key configured is invalid

-
-Source code -
class InvalidPrivateKey(Exception):
-    """
-    raised when the private key configured is invalid
-    """
-
-

Ancestors

-
    -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-class Location -(*name_list) -
-
-

dot-separated auto-location for any type

-

for example, if we have a class in jumpscale/clients/redis/ -location name will be jumpscale.clients.redis.

-
-Source code -
class Location:
-    """
-    dot-separated auto-location for any type
-
-    for example, if we have a class in jumpscale/clients/redis/<type>
-    location name will be jumpscale.clients.redis.<type>
-    """
-
-    def __init__(self, *name_list):
-        self.name_list = list(name_list)
-
-    @property
-    def name(self):
-        """
-        get dot seprated string from current name list
-
-        Returns:
-            str: dot separated string
-        """
-        return ".".join(self.name_list)
-
-    @property
-    def path(self):
-        """
-        get a filesystem path with from `name`, where dots are replaced by `os.sep`
-
-        Returns:
-            str: path
-        """
-        return os.path.join(*self.name.split("."))
-
-    @classmethod
-    def from_type(cls, type_):
-        """
-        get a location from any type/class
-
-        Args:
-            type_ (type): any type (class)
-
-        Returns:
-            Location: a location object
-        """
-        return cls(type_.__module__, type_.__name__)
-
-    def __str__(self):
-        args = "', '".join(self.name_list)
-        cls_name = self.__class__.__name__
-        return f"{cls_name}('{args}')"
-
-    __repr__ = __str__
-
-

Static methods

-
-
-def from_type(type_) -
-
-

get a location from any type/class

-

Args

-
-
type_ : type
-
any type (class)
-
-

Returns

-
-
Location
-
a location object
-
-
-Source code -
@classmethod
-def from_type(cls, type_):
-    """
-    get a location from any type/class
-
-    Args:
-        type_ (type): any type (class)
-
-    Returns:
-        Location: a location object
-    """
-    return cls(type_.__module__, type_.__name__)
-
-
-
-

Instance variables

-
-
var name
-
-

get dot seprated string from current name list

-

Returns

-
-
str
-
dot separated string
-
-
-Source code -
@property
-def name(self):
-    """
-    get dot seprated string from current name list
-
-    Returns:
-        str: dot separated string
-    """
-    return ".".join(self.name_list)
-
-
-
var path
-
-

get a filesystem path with from name, where dots are replaced by os.sep

-

Returns

-
-
str
-
path
-
-
-Source code -
@property
-def path(self):
-    """
-    get a filesystem path with from `name`, where dots are replaced by `os.sep`
-
-    Returns:
-        str: path
-    """
-    return os.path.join(*self.name.split("."))
-
-
-
-
-
-class RedisStore -(location) -
-
-

RedisStore store is an EncryptedConfigStore

-

It saves the data in redis and configuration for redis comes from config_env.get_store_config("redis")

-

create a new redis store, the location given will be used to generate keys

-

this keys will be combined to get/set instance config

-

Args

-

location (Location)

-
-Source code -
class RedisStore(EncryptedConfigStore):
-    """
-    RedisStore store is an EncryptedConfigStore
-
-    It saves the data in redis and configuration for redis comes from `config_env.get_store_config("redis")`
-    """
-
-    def __init__(self, location):
-        """
-        create a new redis store, the location given will be used to generate keys
-
-        this keys will be combined to get/set instance config
-
-        Args:
-            location (Location)
-        """
-        super().__init__(location)
-        redis_config = self.config_env.get_store_config("redis")
-        self.redis_client = redis.Redis(redis_config["hostname"], redis_config["port"])
-
-    def get_key(self, instance_name):
-        """
-        get a key for an instance
-
-        this will return a dot-separated key derived from current location
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            str: key
-        """
-        return ".".join([self.location.name, instance_name])
-
-    def read(self, instance_name):
-        """
-        read instance config from redis
-
-        Args:
-            instance_name (name): name
-
-        Returns:
-            str: data
-        """
-        return self.redis_client.get(self.get_key(instance_name))
-
-    def _full_scan(self, pattern):
-        """
-        get the full result of a scan command on current redis database by this pattern
-
-        Args:
-            pattern ([type]): [description]
-        """
-        keys = []
-        cursor, values = self.redis_client.scan(0, pattern)
-
-        while values:
-            keys += values
-            if not cursor:
-                break
-            cursor, values = self.redis_client.scan(cursor, pattern)
-
-        return keys
-
-    def get_location_keys(self):
-        """
-        get all keys under current location (scanned)
-
-        Returns:
-            list: a list of keys
-        """
-        return self._full_scan(f"{self.location.name}.*")
-
-    def get_instance_keys(self, instance_name):
-        """
-        get all instance related keys (scanned)
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            list: list of keys
-        """
-        return self._full_scan(f"{self.location.name}.{instance_name}*")
-
-    def list_all(self):
-        """
-        get all names of instances (instance keys)
-
-        Returns:
-            [type]: [description]
-        """
-        names = []
-
-        keys = self.get_location_keys()
-        for key in keys:
-            # remove location name part
-            name = key.decode().replace(self.location.name, "").lstrip(".")
-            if "." not in name:
-                names.append(name)
-        return names
-
-    def write(self, instance_name, data):
-        """
-        set data with the corresponding key for this instance
-
-        Args:
-            instance_name (str): name
-            data (str): data
-
-        Returns:
-            bool: written or not
-        """
-        return self.redis_client.set(self.get_key(instance_name), data)
-
-    def delete(self, instance_name):
-        """
-        delete all instance related keys
-
-        Args:
-            instance_name (str): name
-
-        Returns:
-            bool
-        """
-        keys = self.get_instance_keys(instance_name)
-        if keys:
-            return self.redis_client.delete(*keys)
-        return True
-
-

Ancestors

- -

Methods

-
-
-def delete(self, instance_name) -
-
-

delete all instance related keys

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
bool
-
 
-
-
-Source code -
def delete(self, instance_name):
-    """
-    delete all instance related keys
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        bool
-    """
-    keys = self.get_instance_keys(instance_name)
-    if keys:
-        return self.redis_client.delete(*keys)
-    return True
-
-
-
-def get_instance_keys(self, instance_name) -
-
-

get all instance related keys (scanned)

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
list
-
list of keys
-
-
-Source code -
def get_instance_keys(self, instance_name):
-    """
-    get all instance related keys (scanned)
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        list: list of keys
-    """
-    return self._full_scan(f"{self.location.name}.{instance_name}*")
-
-
-
-def get_key(self, instance_name) -
-
-

get a key for an instance

-

this will return a dot-separated key derived from current location

-

Args

-
-
instance_name : str
-
name
-
-

Returns

-
-
str
-
key
-
-
-Source code -
def get_key(self, instance_name):
-    """
-    get a key for an instance
-
-    this will return a dot-separated key derived from current location
-
-    Args:
-        instance_name (str): name
-
-    Returns:
-        str: key
-    """
-    return ".".join([self.location.name, instance_name])
-
-
-
-def get_location_keys(self) -
-
-

get all keys under current location (scanned)

-

Returns

-
-
list
-
a list of keys
-
-
-Source code -
def get_location_keys(self):
-    """
-    get all keys under current location (scanned)
-
-    Returns:
-        list: a list of keys
-    """
-    return self._full_scan(f"{self.location.name}.*")
-
-
-
-def list_all(self) -
-
-

get all names of instances (instance keys)

-

Returns

-
-Source code -
def list_all(self):
-    """
-    get all names of instances (instance keys)
-
-    Returns:
-        [type]: [description]
-    """
-    names = []
-
-    keys = self.get_location_keys()
-    for key in keys:
-        # remove location name part
-        name = key.decode().replace(self.location.name, "").lstrip(".")
-        if "." not in name:
-            names.append(name)
-    return names
-
-
-
-def read(self, instance_name) -
-
-

read instance config from redis

-

Args

-
-
instance_name : name
-
name
-
-

Returns

-
-
str
-
data
-
-
-Source code -
def read(self, instance_name):
-    """
-    read instance config from redis
-
-    Args:
-        instance_name (name): name
-
-    Returns:
-        str: data
-    """
-    return self.redis_client.get(self.get_key(instance_name))
-
-
-
-def write(self, instance_name, data) -
-
-

set data with the corresponding key for this instance

-

Args

-
-
instance_name : str
-
name
-
data : str
-
data
-
-

Returns

-
-
bool
-
written or not
-
-
-Source code -
def write(self, instance_name, data):
-    """
-    set data with the corresponding key for this instance
-
-    Args:
-        instance_name (str): name
-        data (str): data
-
-    Returns:
-        bool: written or not
-    """
-    return self.redis_client.set(self.get_key(instance_name), data)
-
-
-
-

Inherited members

- -
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/core/config.html b/docs/api/jumpscale/core/config.html deleted file mode 100644 index ef4d69436..000000000 --- a/docs/api/jumpscale/core/config.html +++ /dev/null @@ -1,233 +0,0 @@ - - - - - - -jumpscale.core.config API documentation - - - - - - - - - -
-
-
-

Module jumpscale.core.config

-
-
-
-Source code -
import os
-import pytoml as toml
-
-
-__all__ = ['config_path', 'js_default_config', 'get_jumpscale_config', 'update_jumpscale_config', 'JumpscaleConfigEnvironment']
-
-config_path = os.path.expanduser(os.path.join("~/.config", "jumpscale", "config.toml"))
-
-def js_default_config():
-    return {
-        "debug": True,
-        "ssh_key_path": "",
-        "log_to_redis": False,
-        "log_to_files": True,
-        "log_level": 15,
-        "private_key_path": "",
-        "secure_config_path": os.path.expanduser(os.path.join("~/.config", "jumpscale", "secureconfig")),
-    }
-
-if not os.path.exists(config_path):
-    os.makedirs(os.path.dirname(config_path), exist_ok=True)
-    with open(config_path, "w") as f:
-        toml.dump(js_default_config(), f)
-
-def get_jumpscale_config():
-    with open(config_path, "r") as f:
-        return toml.load(f)
-
-def update_jumpscale_config(data):
-    with open(config_path, "w") as f:
-        toml.dump(data, f)
-
-
-class JumpscaleConfigEnvironment:
-    def get_private_key_path(self):
-        config = get_jumpscale_config()
-        private_key_path = config['private_key_path']
-        return private_key_path
-    
-    def get_private_key(self):
-        return open(self.get_private_key_path(), "rb").read()
-
-    def get_secure_config_path(self):
-        config = get_jumpscale_config()
-        secure_config_path = config['secure_config_path']
-        return os.path.expanduser(secure_config_path)
-
-
-
-
-
-
-
-

Functions

-
-
-def get_jumpscale_config() -
-
-
-
-Source code -
def get_jumpscale_config():
-    with open(config_path, "r") as f:
-        return toml.load(f)
-
-
-
-def js_default_config() -
-
-
-
-Source code -
def js_default_config():
-    return {
-        "debug": True,
-        "ssh_key_path": "",
-        "log_to_redis": False,
-        "log_to_files": True,
-        "log_level": 15,
-        "private_key_path": "",
-        "secure_config_path": os.path.expanduser(os.path.join("~/.config", "jumpscale", "secureconfig")),
-    }
-
-
-
-def update_jumpscale_config(data) -
-
-
-
-Source code -
def update_jumpscale_config(data):
-    with open(config_path, "w") as f:
-        toml.dump(data, f)
-
-
-
-
-
-

Classes

-
-
-class JumpscaleConfigEnvironment -(*args, **kwargs) -
-
-
-
-Source code -
class JumpscaleConfigEnvironment:
-    def get_private_key_path(self):
-        config = get_jumpscale_config()
-        private_key_path = config['private_key_path']
-        return private_key_path
-    
-    def get_private_key(self):
-        return open(self.get_private_key_path(), "rb").read()
-
-    def get_secure_config_path(self):
-        config = get_jumpscale_config()
-        secure_config_path = config['secure_config_path']
-        return os.path.expanduser(secure_config_path)
-
-

Methods

-
-
-def get_private_key(self) -
-
-
-
-Source code -
def get_private_key(self):
-    return open(self.get_private_key_path(), "rb").read()
-
-
-
-def get_private_key_path(self) -
-
-
-
-Source code -
def get_private_key_path(self):
-    config = get_jumpscale_config()
-    private_key_path = config['private_key_path']
-    return private_key_path
-
-
-
-def get_secure_config_path(self) -
-
-
-
-Source code -
def get_secure_config_path(self):
-    config = get_jumpscale_config()
-    secure_config_path = config['secure_config_path']
-    return os.path.expanduser(secure_config_path)
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/core/config/config.html b/docs/api/jumpscale/core/config/config.html index b0f08b6de..ec3a08e24 100644 --- a/docs/api/jumpscale/core/config/config.html +++ b/docs/api/jumpscale/core/config/config.html @@ -186,7 +186,10 @@

Get/Set

"debug": True, "shell": "ptpython", "logging": { - "default": {"enabled": True, "level": 10,}, + "default": { + "enabled": True, + "level": 10, + }, "redis": { "enabled": True, "level": 15, @@ -211,8 +214,9 @@

Get/Set

}, "factory": {"always_reload": False}, "store": "filesystem", - "threebot": {"default": "",}, - "explorer": {"default_url": "https://explorer.testnet.grid.tf/explorer",}, + "threebot": { + "default": "", + }, } @@ -237,7 +241,7 @@

Get/Set

def get(key, default=None): - """ Retrives value from jumpscale config + """Retrives value from jumpscale config Arguments: key (str): the key you wish to retrieve @@ -248,7 +252,7 @@

Get/Set

def set(key, val): - """ Sets value in jumpscale config + """Sets value in jumpscale config Arguments: key (str): the key you wish to update @@ -260,7 +264,7 @@

Get/Set

def set_default(key, val): - """ Sets key to value in jumpscale config and returns + """Sets key to value in jumpscale config and returns Arguments: key (str): the key you wish to update @@ -372,7 +376,7 @@

Arguments

Expand source code
def get(key, default=None):
-    """ Retrives value from jumpscale config
+    """Retrives value from jumpscale config
 
     Arguments:
         key (str): the key you wish to retrieve
@@ -440,7 +444,10 @@ 

Returns

"debug": True, "shell": "ptpython", "logging": { - "default": {"enabled": True, "level": 10,}, + "default": { + "enabled": True, + "level": 10, + }, "redis": { "enabled": True, "level": 15, @@ -465,8 +472,9 @@

Returns

}, "factory": {"always_reload": False}, "store": "filesystem", - "threebot": {"default": "",}, - "explorer": {"default_url": "https://explorer.testnet.grid.tf/explorer",}, + "threebot": { + "default": "", + }, }
@@ -483,7 +491,7 @@

Arguments

Expand source code
def set(key, val):
-    """ Sets value in jumpscale config
+    """Sets value in jumpscale config
 
     Arguments:
         key (str): the key you wish to update
@@ -509,7 +517,7 @@ 

Returns

Expand source code
def set_default(key, val):
-    """ Sets key to value in jumpscale config and returns
+    """Sets key to value in jumpscale config and returns
 
     Arguments:
         key (str): the key you wish to update
diff --git a/docs/api/jumpscale/core/exceptions.html b/docs/api/jumpscale/core/exceptions.html
deleted file mode 100644
index a11f5ead1..000000000
--- a/docs/api/jumpscale/core/exceptions.html
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
-
-
-
-
-jumpscale.core.exceptions API documentation
-
-
-
-
-
-
-
-
-
-
-
-
-

Module jumpscale.core.exceptions

-
-
-
-Source code -
class JSException(Exception):
-    pass
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class JSException -(*args, **kwargs) -
-
-

Common base class for all non-exit exceptions.

-
-Source code -
class JSException(Exception):
-    pass
-
-

Ancestors

-
    -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/core/logging.html b/docs/api/jumpscale/core/logging.html deleted file mode 100644 index c2767eeb6..000000000 --- a/docs/api/jumpscale/core/logging.html +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - -jumpscale.core.logging API documentation - - - - - - - - - -
-
-
-

Module jumpscale.core.logging

-
-
-
-Source code -
class JSLogger:
-    pass
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class JSLogger -(*args, **kwargs) -
-
-
-
-Source code -
class JSLogger:
-    pass
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/countries/index.html b/docs/api/jumpscale/data/countries/index.html deleted file mode 100644 index d78689065..000000000 --- a/docs/api/jumpscale/data/countries/index.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - - - -jumpscale.data.countries API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.countries

-
-
-

This module helps picking a random country or even listing all countries.

-
JS-NG> j.data.countries.names()                                                        
-['Aruba', 'Afghanistan', 'Angola', 'Anguilla', 'Åland Islands', 'Albania', 'Andorra', '
-United Arab Emirates', 'Argentina', 'Armenia', 'American Samoa', 'Antarctica', 'French 
-Southern Territories', 'Antigua and Barbuda', 'Australia', 'Austria', 'Azerbaijan', 'Bu
-rundi', 'Belgium', 'Benin', 'Bonaire, Sint Eustatius and Saba', 'Burkina Faso', 'Bangla
-desh', 'Bulgaria', 'Bahrain', 'Bahamas', 'Bosnia and Herzegovina', 'Saint Barthélemy', 
-'Belarus', 'Belize', 'Bermuda', 'Bolivia, Plurinational State of', 'Brazil', 'Barbados', 'Brunei Darussalam', 'Bhutan', 'Bouvet Island', 'Botswana', 'Central African Republic', 'Canada', 'Cocos (Keeling) Islands', 'Switzerland', 'Chile', 'China', "Côte d'Ivoire", 'Cameroon', 'Congo, The Democratic Republic of the', 'Congo', 'Cook Islands', 'Colombia', 'Comoros', 'Cabo Verde', 'Costa Rica', 'Cuba', 'Curaçao', 'Christmas Island', 'Cayman Islands', 'Cyprus', 'Czechia', 'Germany', 'Djibouti', 'Dominica', 'Denmark', 'Dominican Republic', 'Algeria', 'Ecuador', 'Egypt', 'Eritrea', 'Western Sahara', 'Spain', 'Estonia', 'Ethiopia', 'Finland', 'Fiji', 'Falkland Islands (Malvinas)', 'France', 'Faroe Islands', 'Micronesia, Federated States of', 'Gabon', 'United Kingdom', 'Georgia', 'Guernsey', 'Ghana', 'Gibraltar', 'Guinea', 'Guadeloupe', 'Gambia', 'Guinea-Bissau', 'Equatorial Guinea', 'Greece', 'Grenada', 'Greenland', 'Guatemala', 'French Guiana', 'Guam', 'Guyana', 'Hong Kong', 'Heard Island and McDonald Islands', 'Honduras', 'Croatia', 'Haiti', 'Hungary', 'Indonesia', 'Isle of Man', 'India', 'British Indian Ocean Territory', 'Ireland', 'Iran, Islamic Republic of', 'Iraq', 'Iceland', 'Israel', 'Italy', 'Jamaica', 'Jersey', 'Jordan', 'Japan', 'Kazakhstan', 'Kenya', 'Kyrgyzstan', 'Cambodia', 'Kiribati', 'Saint Kitts and Nevis', 'Korea, Republic of', 'Kuwait', "Lao People's Democratic Republic", 'Lebanon', 'Liberia', 'Libya', 'Saint Lucia', 'Liechtenstein', 'Sri Lanka', 'Lesotho', 'Lithuania', 'Luxembourg', 'Latvia', 'Macao', 'Saint Martin (French part)', 'Morocco', 'Monaco', 'Moldova, Republic of', 'Madagascar', 'Maldives', 'Mexico', 'Marshall Islands', 'North Macedonia', 'Mali', 'Malta', 'Myanmar', 'Montenegro', 'Mongolia', 'Northern Mariana Islands', 'Mozambique', 'Mauritania', 'Montserrat', 'Martinique', 'Mauritius', 'Malawi', 'Malaysia', 'Mayotte', 'Namibia', 'New Caledonia', 'Niger', 'Norfolk Island', 'Nigeria', 'Nicaragua', 'Niue', 'Netherlands', 'Norway', 'Nepal', 'Nauru', 'New Zealand', 'Oman', 'Pakistan', 'Panama', 'Pitcairn', 'Peru', 'Philippines', 'Palau', 'Papua New Guinea', 'Poland', 'Puerto Rico', "Korea, Democratic People's Republic of", 'Portugal', 'Paraguay', 'Palestine, State of', 'French Polynesia', 'Qatar', 'Réunion', 'Romania', 'Russian Federation', 'Rwanda', 'Saudi Arabia', 'Sudan', 'Senegal', 'Singapore', 'South Georgia and the South Sandwich Islands', 'Saint Helena, Ascension and Tristan da Cunha', 'Svalbard and Jan Mayen', 'Solomon Islands', 'Sierra Leone', 'El Salvador', 'San Marino', 'Somalia', 'Saint Pierre and Miquelon', 'Serbia', 'South Sudan', 'Sao Tome and Principe', 'Suriname', 'Slovakia', 'Slovenia', 'Sweden', 'Eswatini', 'Sint Maarten (Dutch part)', 'Seychelles', 'Syrian Arab Republic', 'Turks and Caicos Islands', 'Chad', 'Togo', 'Thailand', 'Tajikistan', 'Tokelau', 'Turkmenistan', 'Timor-Leste', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Tuvalu', 'Taiwan, Province of China', 'Tanzania, United Republic of', 'Uganda', 'Ukraine', 'United States Minor Outlying Islands', 'Uruguay', 'United States', 'Uzbekistan', 'Holy See (Vatican City State)', 'Saint Vincent and the Grenadines', 'Venezuela, Bolivarian Republic of', 'Virgin Islands, British', 'Virgin Islands, U.S.', 'Viet Nam', 'Vanuatu', 'Wallis and Futuna', 'Samoa', 'Yemen', 'South Africa', 'Zambia', 'Zimbabwe']
-
-JS-NG> j.data.countries.random_country()                                               
-'Seychelles'
-
-JS-NG> j.data.countries.random_country()                                               
-'Malawi'
-
-
-Source code -
"""This module helps picking a random country or even listing all countries.
-```
-JS-NG> j.data.countries.names()                                                        
-['Aruba', 'Afghanistan', 'Angola', 'Anguilla', 'Åland Islands', 'Albania', 'Andorra', '
-United Arab Emirates', 'Argentina', 'Armenia', 'American Samoa', 'Antarctica', 'French 
-Southern Territories', 'Antigua and Barbuda', 'Australia', 'Austria', 'Azerbaijan', 'Bu
-rundi', 'Belgium', 'Benin', 'Bonaire, Sint Eustatius and Saba', 'Burkina Faso', 'Bangla
-desh', 'Bulgaria', 'Bahrain', 'Bahamas', 'Bosnia and Herzegovina', 'Saint Barthélemy', 
-'Belarus', 'Belize', 'Bermuda', 'Bolivia, Plurinational State of', 'Brazil', 'Barbados', 'Brunei Darussalam', 'Bhutan', 'Bouvet Island', 'Botswana', 'Central African Republic', 'Canada', 'Cocos (Keeling) Islands', 'Switzerland', 'Chile', 'China', "Côte d'Ivoire", 'Cameroon', 'Congo, The Democratic Republic of the', 'Congo', 'Cook Islands', 'Colombia', 'Comoros', 'Cabo Verde', 'Costa Rica', 'Cuba', 'Curaçao', 'Christmas Island', 'Cayman Islands', 'Cyprus', 'Czechia', 'Germany', 'Djibouti', 'Dominica', 'Denmark', 'Dominican Republic', 'Algeria', 'Ecuador', 'Egypt', 'Eritrea', 'Western Sahara', 'Spain', 'Estonia', 'Ethiopia', 'Finland', 'Fiji', 'Falkland Islands (Malvinas)', 'France', 'Faroe Islands', 'Micronesia, Federated States of', 'Gabon', 'United Kingdom', 'Georgia', 'Guernsey', 'Ghana', 'Gibraltar', 'Guinea', 'Guadeloupe', 'Gambia', 'Guinea-Bissau', 'Equatorial Guinea', 'Greece', 'Grenada', 'Greenland', 'Guatemala', 'French Guiana', 'Guam', 'Guyana', 'Hong Kong', 'Heard Island and McDonald Islands', 'Honduras', 'Croatia', 'Haiti', 'Hungary', 'Indonesia', 'Isle of Man', 'India', 'British Indian Ocean Territory', 'Ireland', 'Iran, Islamic Republic of', 'Iraq', 'Iceland', 'Israel', 'Italy', 'Jamaica', 'Jersey', 'Jordan', 'Japan', 'Kazakhstan', 'Kenya', 'Kyrgyzstan', 'Cambodia', 'Kiribati', 'Saint Kitts and Nevis', 'Korea, Republic of', 'Kuwait', "Lao People's Democratic Republic", 'Lebanon', 'Liberia', 'Libya', 'Saint Lucia', 'Liechtenstein', 'Sri Lanka', 'Lesotho', 'Lithuania', 'Luxembourg', 'Latvia', 'Macao', 'Saint Martin (French part)', 'Morocco', 'Monaco', 'Moldova, Republic of', 'Madagascar', 'Maldives', 'Mexico', 'Marshall Islands', 'North Macedonia', 'Mali', 'Malta', 'Myanmar', 'Montenegro', 'Mongolia', 'Northern Mariana Islands', 'Mozambique', 'Mauritania', 'Montserrat', 'Martinique', 'Mauritius', 'Malawi', 'Malaysia', 'Mayotte', 'Namibia', 'New Caledonia', 'Niger', 'Norfolk Island', 'Nigeria', 'Nicaragua', 'Niue', 'Netherlands', 'Norway', 'Nepal', 'Nauru', 'New Zealand', 'Oman', 'Pakistan', 'Panama', 'Pitcairn', 'Peru', 'Philippines', 'Palau', 'Papua New Guinea', 'Poland', 'Puerto Rico', "Korea, Democratic People's Republic of", 'Portugal', 'Paraguay', 'Palestine, State of', 'French Polynesia', 'Qatar', 'Réunion', 'Romania', 'Russian Federation', 'Rwanda', 'Saudi Arabia', 'Sudan', 'Senegal', 'Singapore', 'South Georgia and the South Sandwich Islands', 'Saint Helena, Ascension and Tristan da Cunha', 'Svalbard and Jan Mayen', 'Solomon Islands', 'Sierra Leone', 'El Salvador', 'San Marino', 'Somalia', 'Saint Pierre and Miquelon', 'Serbia', 'South Sudan', 'Sao Tome and Principe', 'Suriname', 'Slovakia', 'Slovenia', 'Sweden', 'Eswatini', 'Sint Maarten (Dutch part)', 'Seychelles', 'Syrian Arab Republic', 'Turks and Caicos Islands', 'Chad', 'Togo', 'Thailand', 'Tajikistan', 'Tokelau', 'Turkmenistan', 'Timor-Leste', 'Tonga', 'Trinidad and Tobago', 'Tunisia', 'Turkey', 'Tuvalu', 'Taiwan, Province of China', 'Tanzania, United Republic of', 'Uganda', 'Ukraine', 'United States Minor Outlying Islands', 'Uruguay', 'United States', 'Uzbekistan', 'Holy See (Vatican City State)', 'Saint Vincent and the Grenadines', 'Venezuela, Bolivarian Republic of', 'Virgin Islands, British', 'Virgin Islands, U.S.', 'Viet Nam', 'Vanuatu', 'Wallis and Futuna', 'Samoa', 'Yemen', 'South Africa', 'Zambia', 'Zimbabwe']
-
-JS-NG> j.data.countries.random_country()                                               
-'Seychelles'
-
-JS-NG> j.data.countries.random_country()                                               
-'Malawi'
-```
-"""
-import pycountry
-import random
-
-
-def names():
-    """Generates list of country names."""
-    return [country.name for country in pycountry.countries]
-
-
-def random_country():
-    """Generates a random country name"""
-    return random.choice(names())
-
-
-
-
-
-
-
-

Functions

-
-
-def names() -
-
-

Generates list of country names.

-
-Source code -
def names():
-    """Generates list of country names."""
-    return [country.name for country in pycountry.countries]
-
-
-
-def random_country() -
-
-

Generates a random country name

-
-Source code -
def random_country():
-    """Generates a random country name"""
-    return random.choice(names())
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/encryption/encryption.html b/docs/api/jumpscale/data/encryption/encryption.html deleted file mode 100644 index 8b7878036..000000000 --- a/docs/api/jumpscale/data/encryption/encryption.html +++ /dev/null @@ -1,269 +0,0 @@ - - - - - - -jumpscale.data.encryption.encryption API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.encryption.encryption

-
-
-
-Source code -
from jumpscale.loader import j
-from .mnemonic import key_to_mnemonic, mnemonic_to_key, generate_mnemonic
-
-
-def encrypt(message, private_key, receiver_public_key):
-    """Encrypt the message using the public key of the reciever and the sender's private key.
-
-    Args:
-        message (bytes): The message.
-        private_key (bytes): sender's private key.
-        receiver_public_key (bytes): receiver's public key.
-
-    Returns:
-        bytes: The encryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(private_key=private_key)
-    message = nacl_obj.encrypt(message, receiver_public_key)
-    return message
-
-
-def decrypt(message, private_key, sender_public_key):
-    """Decrypt the message using the private key of the reciever and the sender's public key.
-
-    Args:
-        message (bytes): The message.
-        private_key (bytes): reciever's private key.
-        sender_public_key (bytes): sender's public key.
-
-    Returns:
-        bytes: The decryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(private_key=private_key)
-    message = nacl_obj.decrypt(message, sender_public_key)
-    return message
-
-
-def encrypt_symmetric(message, symmetric_key):
-    """Encrypt the message using the secret key.
-
-    Args:
-        message (bytes): The message.
-        symmetric_key (bytes): The secret key.
-
-    Returns:
-        bytes: The encryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(symmetric_key=symmetric_key)
-    return nacl_obj.encrypt_symmetric(message)
-
-
-def decrypt_symmetric(message, symmetric_key):
-    """Decrypt the message using the secret key.
-
-    Args:
-        message (bytes): The message.
-        symmetric_key (bytes): The secret key.
-
-    Returns:
-        bytes: The decryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(symmetric_key=symmetric_key)
-    return nacl_obj.decrypt_symmetric(message, symmetric_key)
-
-
-
-
-
-
-
-

Functions

-
-
-def decrypt(message, private_key, sender_public_key) -
-
-

Decrypt the message using the private key of the reciever and the sender's public key.

-

Args

-
-
message : bytes
-
The message.
-
private_key : bytes
-
reciever's private key.
-
sender_public_key : bytes
-
sender's public key.
-
-

Returns

-
-
bytes
-
The decryption of the message.
-
-
-Source code -
def decrypt(message, private_key, sender_public_key):
-    """Decrypt the message using the private key of the reciever and the sender's public key.
-
-    Args:
-        message (bytes): The message.
-        private_key (bytes): reciever's private key.
-        sender_public_key (bytes): sender's public key.
-
-    Returns:
-        bytes: The decryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(private_key=private_key)
-    message = nacl_obj.decrypt(message, sender_public_key)
-    return message
-
-
-
-def decrypt_symmetric(message, symmetric_key) -
-
-

Decrypt the message using the secret key.

-

Args

-
-
message : bytes
-
The message.
-
symmetric_key : bytes
-
The secret key.
-
-

Returns

-
-
bytes
-
The decryption of the message.
-
-
-Source code -
def decrypt_symmetric(message, symmetric_key):
-    """Decrypt the message using the secret key.
-
-    Args:
-        message (bytes): The message.
-        symmetric_key (bytes): The secret key.
-
-    Returns:
-        bytes: The decryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(symmetric_key=symmetric_key)
-    return nacl_obj.decrypt_symmetric(message, symmetric_key)
-
-
-
-def encrypt(message, private_key, receiver_public_key) -
-
-

Encrypt the message using the public key of the reciever and the sender's private key.

-

Args

-
-
message : bytes
-
The message.
-
private_key : bytes
-
sender's private key.
-
receiver_public_key : bytes
-
receiver's public key.
-
-

Returns

-
-
bytes
-
The encryption of the message.
-
-
-Source code -
def encrypt(message, private_key, receiver_public_key):
-    """Encrypt the message using the public key of the reciever and the sender's private key.
-
-    Args:
-        message (bytes): The message.
-        private_key (bytes): sender's private key.
-        receiver_public_key (bytes): receiver's public key.
-
-    Returns:
-        bytes: The encryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(private_key=private_key)
-    message = nacl_obj.encrypt(message, receiver_public_key)
-    return message
-
-
-
-def encrypt_symmetric(message, symmetric_key) -
-
-

Encrypt the message using the secret key.

-

Args

-
-
message : bytes
-
The message.
-
symmetric_key : bytes
-
The secret key.
-
-

Returns

-
-
bytes
-
The encryption of the message.
-
-
-Source code -
def encrypt_symmetric(message, symmetric_key):
-    """Encrypt the message using the secret key.
-
-    Args:
-        message (bytes): The message.
-        symmetric_key (bytes): The secret key.
-
-    Returns:
-        bytes: The encryption of the message.
-    """
-    nacl_obj = j.data.nacl.NACL(symmetric_key=symmetric_key)
-    return nacl_obj.encrypt_symmetric(message)
-
-
-
-
-
-
-
- -
- - - - - diff --git a/docs/api/jumpscale/data/hash/HashTool.py b/docs/api/jumpscale/data/hash/HashTool.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/api/jumpscale/data/hash/__init__.py b/docs/api/jumpscale/data/hash/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/api/jumpscale/data/randomnames/generate.html b/docs/api/jumpscale/data/randomnames/generate.html deleted file mode 100644 index fc635e617..000000000 --- a/docs/api/jumpscale/data/randomnames/generate.html +++ /dev/null @@ -1,256 +0,0 @@ - - - - - - -jumpscale.data.randomnames.generate API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.randomnames.generate

-
-
-

This is the code of random names

-
-Source code -
""" This is the code of random names   """
-
-from random import choice
-
-left_names = [
-    "albattani",
-    "allen",
-    "almeida",
-    "antonelli",
-    "agnesi",
-    "archimedes",
-    "ardinghelli",
-    "aryabhata",
-    "austin",
-    "babbage",
-    "banach",
-    "banzai",
-    "bardeen",
-    "bartik",
-    "bassi",
-    "beaver",
-    "bell",
-    "benz",
-    "bhabha",
-    "bhaskara",
-    "black",
-    "blackburn",
-    "blackwell",
-    "bohr",
-    "booth",
-    "borg",
-    "bose",
-    "boyd",
-    "brahmagupta",
-    "brattain",
-    "brown",
-    "burnell",
-    "buck",
-    "burnell",
-    "cannon",
-    "carson",
-    "cartwright",
-    "chandrasekhar",
-    "chaplygin",
-    "chatelet",
-    "chatterjee",
-    "chebyshev",
-    "cocks",
-    "cohen",
-    "chaum",
-    "clarke",
-    "colden",
-    "cori",
-    "cray",
-    "wiles",
-    "williams",
-    "williamson",
-    "wilson",
-    "wing",
-    "wozniak",
-    "wright",
-    "wu",
-    "yalow",
-    "yonath",
-    "zhukovsky",
-]
-right_names = [
-    "admiring",
-    "adoring",
-    "affectionate",
-    "agitated",
-    "amazing",
-    "angry",
-    "awesome",
-    "blissful",
-    "bold",
-    "boring",
-    "brave",
-    "charming",
-    "clever",
-    "cocky",
-    "cool",
-    "compassionate",
-    "competent",
-    "condescending",
-    "confident",
-    "cranky",
-    "crazy",
-    "dazzling",
-    "determined",
-    "distracted",
-    "dreamy",
-    "eager",
-    "ecstatic",
-    "elastic",
-    "elated",
-    "elegant",
-    "eloquent",
-    "epic",
-    "fervent",
-    "festive",
-    "flamboyant",
-    "focused",
-    "friendly",
-    "frosty",
-    "gallant",
-    "gifted",
-    "goofy",
-    "gracious",
-    "happy",
-    "hardcore",
-    "heuristic",
-    "hopeful",
-    "hungry",
-    "infallible",
-    "inspiring",
-    "jolly",
-    "jovial",
-    "keen",
-    "kind",
-    "laughing",
-    "loving",
-    "lucid",
-    "magical",
-    "mystifying",
-    "modest",
-    "musing",
-    "naughty",
-    "nervous",
-    "nifty",
-    "nostalgic",
-    "objective",
-    "optimistic",
-    "peaceful",
-    "pedantic",
-    "pensive",
-    "practical",
-    "priceless",
-    "quirky",
-    "quizzical",
-    "recursing",
-    "relaxed",
-    "reverent",
-    "romantic",
-    "sad",
-    "serene",
-    "sharp",
-    "silly",
-    "sleepy",
-    "stoic",
-    "stupefied",
-    "suspicious",
-    "sweet",
-    "tender",
-    "thirsty",
-    "trusting",
-    "unruffled",
-    "upbeat",
-    "vibrant",
-    "vigilant",
-    "vigorous",
-    "wizardly",
-    "wonderful",
-    "xenodochial",
-    "youthful",
-    "zealous",
-    "zen",
-]
-
-
-def generate_random_name():
-    """ Returns a random name "first name" & "last name """
-
-    name = "%s_%s" % (choice(right_names), choice(left_names))
-
-    return name
-
-
-
-
-
-
-
-

Functions

-
-
-def generate_random_name() -
-
-

Returns a random name "first name" & "last name

-
-Source code -
def generate_random_name():
-    """ Returns a random name "first name" & "last name """
-
-    name = "%s_%s" % (choice(right_names), choice(left_names))
-
-    return name
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/randomnames/index.html b/docs/api/jumpscale/data/randomnames/index.html deleted file mode 100644 index 9de032bcb..000000000 --- a/docs/api/jumpscale/data/randomnames/index.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - -jumpscale.data.randomnames API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.randomnames

-
-
-
-Source code -
from .generate import *
-
-
-
-

Sub-modules

-
-
jumpscale.data.randomnames.generate
-
-

This is the code of random names

-
-
-
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/serializers/serializers.html b/docs/api/jumpscale/data/serializers/serializers.html deleted file mode 100644 index 62161b287..000000000 --- a/docs/api/jumpscale/data/serializers/serializers.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - -jumpscale.data.serializers.serializers API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.serializers.serializers

-
-
-
-Source code -
from json import loads as json_loads, dumps as json_dumps
-from pytoml import loads as toml_loads, dumps as toml_dumps
-# from yaml import load as yaml_load, dump as yaml_dump
-
-
-
-
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/terminaltable/terminaltable.html b/docs/api/jumpscale/data/terminaltable/terminaltable.html deleted file mode 100644 index 6cc51bebf..000000000 --- a/docs/api/jumpscale/data/terminaltable/terminaltable.html +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - -jumpscale.data.terminaltable.terminaltable API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.terminaltable.terminaltable

-
-
-
-Source code -
import terminaltables as tt
-
-TABLE_TYPES = {'ascii': tt.AsciiTable, 'single': tt.SingleTable, 'double': tt.DoubleTable}
-
-def create(title, data, type_='ascii'):
-
-    table_type = TABLE_TYPES.get(type_)
-    if not table_type:
-        raise ValueError("invalid type {} allowed types are {}".format(table_type, TABLE_TYPES.keys()))
-
-    table = table_type(data, title)
-
-    return table.table
-
-
-
-
-
-
-
-

Functions

-
-
-def create(title, data, type_='ascii') -
-
-
-
-Source code -
def create(title, data, type_='ascii'):
-
-    table_type = TABLE_TYPES.get(type_)
-    if not table_type:
-        raise ValueError("invalid type {} allowed types are {}".format(table_type, TABLE_TYPES.keys()))
-
-    table = table_type(data, title)
-
-    return table.table
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/treemanager/exceptions.html b/docs/api/jumpscale/data/treemanager/exceptions.html deleted file mode 100644 index 41f446bbf..000000000 --- a/docs/api/jumpscale/data/treemanager/exceptions.html +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - -jumpscale.data.treemanager.exceptions API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.treemanager.exceptions

-
-
-
-Source code -
from jumpscale.core.exceptions import JSException
-
-
-class NameExistsError(JSException):
-    pass
-
-
-class EmptyNameError(JSException):
-    pass
-
-
-class RootRemoveError(JSException):
-    pass
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class EmptyNameError -(message, category=None, level=None, context=None) -
-
-

Common base class for all non-exit exceptions.

-
-Source code -
class EmptyNameError(JSException):
-    pass
-
-

Ancestors

-
    -
  • JSException
  • -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-class NameExistsError -(message, category=None, level=None, context=None) -
-
-

Common base class for all non-exit exceptions.

-
-Source code -
class NameExistsError(JSException):
-    pass
-
-

Ancestors

-
    -
  • JSException
  • -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-class RootRemoveError -(message, category=None, level=None, context=None) -
-
-

Common base class for all non-exit exceptions.

-
-Source code -
class RootRemoveError(JSException):
-    pass
-
-

Ancestors

-
    -
  • JSException
  • -
  • builtins.Exception
  • -
  • builtins.BaseException
  • -
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/treemanager/index.html b/docs/api/jumpscale/data/treemanager/index.html deleted file mode 100644 index 0f72ebb43..000000000 --- a/docs/api/jumpscale/data/treemanager/index.html +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - -jumpscale.data.treemanager API documentation - - - - - - - - - -
- - -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/data/treemanager/treemanager.html b/docs/api/jumpscale/data/treemanager/treemanager.html deleted file mode 100644 index 99b463604..000000000 --- a/docs/api/jumpscale/data/treemanager/treemanager.html +++ /dev/null @@ -1,1189 +0,0 @@ - - - - - - -jumpscale.data.treemanager.treemanager API documentation - - - - - - - - - -
-
-
-

Module jumpscale.data.treemanager.treemanager

-
-
-

This is a module with a general tree implementation. -A sample usage of the Tree class as a file manager

-
if __name__ == "__main__":
-    tree = Tree()
-    tree.add_node_by_path("root", {"file_name": "root",
-                                   "modified": "12/3/2019"})
-    tree.add_node_by_path("etc", {"file_name": "etc",
-                                  "modified": "13/3/2018"})
-    tree.add_node_by_path("etc.hosts", {"file_name": "hosts",
-                                        "modified": "14/3/2017"})
-    tree.add_node_by_path("etc.passwd", {"file_name": "passwd",
-                                         "modified": "14/3/2016"})
-    pred = lambda x: x.data["modified"].split("/")[-1] < "2018"
-    too_old = tree.search_custom(pred)
-    print("Too old files (before 2018):
-")
-    for f in too_old:
-        print(f.name + "
-")
-    print("Tree before removing /etc/hosts")
-    print(tree)
-    print("Tree after removing /etc/hosts")
-    tree.remove_node_by_path("etc.hosts")
-    print(tree)
-    passwd_file = tree.get_by_path("etc.passwd")
-    passwd_date = passwd_file.data["modified"]
-    print("Last time /etc/passwd was modified is: " + passwd_date)
-
-
-Source code -
"""
-This is a module with a general tree implementation.
-A sample usage of the Tree class as a file manager
-```
-if __name__ == "__main__":
-    tree = Tree()
-    tree.add_node_by_path("root", {"file_name": "root",
-                                   "modified": "12/3/2019"})
-    tree.add_node_by_path("etc", {"file_name": "etc",
-                                  "modified": "13/3/2018"})
-    tree.add_node_by_path("etc.hosts", {"file_name": "hosts",
-                                        "modified": "14/3/2017"})
-    tree.add_node_by_path("etc.passwd", {"file_name": "passwd",
-                                         "modified": "14/3/2016"})
-    pred = lambda x: x.data["modified"].split("/")[-1] < "2018"
-    too_old = tree.search_custom(pred)
-    print("Too old files (before 2018):\n")
-    for f in too_old:
-        print(f.name + "\n")
-    print("Tree before removing /etc/hosts")
-    print(tree)
-    print("Tree after removing /etc/hosts")
-    tree.remove_node_by_path("etc.hosts")
-    print(tree)
-    passwd_file = tree.get_by_path("etc.passwd")
-    passwd_date = passwd_file.data["modified"]
-    print("Last time /etc/passwd was modified is: " + passwd_date)
-```
-"""
-from .exceptions import NameExistsError, EmptyNameError, RootRemoveError
-
-
-class TreeNode:
-    def __init__(self, name, parent, data=None):
-        """
-        name     (str)               : The name associated with the node
-        children (dict[str:TreeNode]): A mapping between names and child nodes
-        parent   (TreeNode or None)  : The parent TreeNode (None for the root)
-        data                         : Data associated with the node
-        """
-        self.name = name
-        self.parent = parent
-        self.data = data
-        self.children = {}
-
-    def add_child(self, node):
-        """Adds a new child
-
-        Args:
-            node (TreeNode): The node to be added
-
-        Returns:
-            TreeNode: The newly added node
-        """
-        child_name = node.name
-        if child_name in self.children:
-            raise NameExistsError("A child with the given name already exists")
-        self.children[child_name] = node
-        return node
-
-    def search_by_name(self, name):
-        """Search in the node's subtree for nodes with the given name
-
-        Args:
-            name (str): The name to be searched for
-
-        Returns:
-            list of TreeNode: The found nodes
-        """
-        return self.search_custom(lambda x: x.name == name)
-
-    def search_by_data(self, data):
-        """Search in the node's subtree for nodes with the given data
-
-        Args:
-            data: The data to be searched for
-
-        Returns:
-            list of TreeNode: The found nodes
-        """
-        return self.search_custom(lambda x: x.data == data)
-
-    def search_custom(self, func):
-        """Search the node's subtree the nodes satisfying the given predicate
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        result = []
-        for v in self.children.values():
-            result.extend(v.search_custom(func))
-
-        if self.name != "" and func(self):
-            result.append(self)
-        return result
-
-    def get_child_by_name(self, name):
-        """Get the child with the given name
-
-        Args:
-            name (str): The name of the child
-
-        Returns:
-            TreeNode: The reqiested child. None if it doesn't exist.
-        """
-        return self.children.get(name)
-
-    def remove_child(self, node):
-        """Remove the node from the children if it exists
-
-        Args:
-            node (TreeNode): The node to be deleted
-
-        Returns:
-            TreeNode: The deleted node
-        """
-        return self.remove_child_by_name(node.name)
-
-    def remove_child_by_name(self, name):
-        """Remove the node from the children
-
-        Args:
-            node (TreeNode): The node to be deleted
-
-        Returns:
-            TreeNode: The deleted node. None if it doesn't exist
-        """
-        if name in self.children:
-            node = self.children[name]
-            del self.children[name]
-            return node
-
-    def get_path(self):
-        """Retrieves the path of the node
-
-        Returns:
-            str: The path
-        """
-        if self.name == "":
-            return ""
-        parent_path = self.parent.get_path()
-        if parent_path == "":
-            return self.name
-        else:
-            return parent_path + "." + self.name
-
-    def __str__(self, indentation=0):
-        """Returns a string representing the node's subtree
-
-        Args:
-            indentation (int, optional): The level to which the representation\
-                                         will be indented. Defaults to 0.
-
-        Returns:
-            str: The tree representation
-        """
-        result = "\t" * indentation + self._string_repr() + "\n"
-        for v in self.children.values():
-            result += v.__str__(indentation + 1)
-        return result
-
-    def _string_repr(self):
-        """A helper function to return the node's name and data as a string
-
-        Returns:
-            str: The node's string representation
-        """
-        if self.name == "":
-            return "dummy_root"
-        else:
-            return self.name + str(self.data).replace("\n", "\\n")
-
-
-class Tree:
-    """"
-    A class to represent a tree
-    """
-
-    def __init__(self):
-        self.root = TreeNode("", None)
-
-    def search_by_data(self, data):
-        """Search the nodes in the tree with the given data
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_by_data(data)
-
-    def search_by_name(self, name):
-        """Search the nodes in the tree with the passed name
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_by_name(name)
-
-    def search_custom(self, func):
-        """Search the nodes in the tree satisfying the given predicate
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_custom(func)
-
-    def get_by_path(self, path):
-        """Retrieves a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-
-            data: The data associated with the newly added node
-
-        Returns:
-            None if an intermidiate node is not found.\
-            Else the searched node is returned
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        for name in path_arr:
-            next_node = current_node.get_child_by_name(name)
-            if next_node is None:
-                return None
-            current_node = next_node
-        return current_node
-
-    def remove_node(self, node):
-        """Remove a node from the tree.
-
-        Args:
-            node (TreeNode): The node to be removed
-        """
-        if node == self.root:
-            raise RootRemoveError("Can't remove the root node")
-        node.parent.remove_child(node)
-        return node
-
-    def add_node_by_path(self, path, data=None):
-        """Add a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-
-            data: The data associated with the newly added node
-
-        Notes:
-            If intermidiate nodes are not found while traversing the path,\
-            they are created with data=None.
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        for path_name in path_arr[:-1]:
-            if path_name == "":
-                raise EmptyNameError("Nodes with empty names are not allowed")
-            next_node = current_node.get_child_by_name(path_name)
-            if next_node is None:
-                next_node = TreeNode(path_name, current_node)
-                current_node.add_child(next_node)
-            current_node = next_node
-        new_node = TreeNode(path_arr[-1], current_node, data)
-        return current_node.add_child(new_node)
-
-    def remove_node_by_path(self, path):
-        """Remove a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        parent_node = None
-        for path_name in path_arr:
-            next_node = current_node.get_child_by_name(path_name)
-            if next_node is None:
-                return None
-            parent_node = current_node
-            current_node = next_node
-        return parent_node.remove_child(current_node)
-
-    def __str__(self):
-        "Return a string representation of the tree"
-        return self.root.__str__(0)
-
-
-
-
-
-
-
-
-
-

Classes

-
-
-class Tree -
-
-

" -A class to represent a tree

-
-Source code -
class Tree:
-    """"
-    A class to represent a tree
-    """
-
-    def __init__(self):
-        self.root = TreeNode("", None)
-
-    def search_by_data(self, data):
-        """Search the nodes in the tree with the given data
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_by_data(data)
-
-    def search_by_name(self, name):
-        """Search the nodes in the tree with the passed name
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_by_name(name)
-
-    def search_custom(self, func):
-        """Search the nodes in the tree satisfying the given predicate
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        return self.root.search_custom(func)
-
-    def get_by_path(self, path):
-        """Retrieves a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-
-            data: The data associated with the newly added node
-
-        Returns:
-            None if an intermidiate node is not found.\
-            Else the searched node is returned
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        for name in path_arr:
-            next_node = current_node.get_child_by_name(name)
-            if next_node is None:
-                return None
-            current_node = next_node
-        return current_node
-
-    def remove_node(self, node):
-        """Remove a node from the tree.
-
-        Args:
-            node (TreeNode): The node to be removed
-        """
-        if node == self.root:
-            raise RootRemoveError("Can't remove the root node")
-        node.parent.remove_child(node)
-        return node
-
-    def add_node_by_path(self, path, data=None):
-        """Add a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-
-            data: The data associated with the newly added node
-
-        Notes:
-            If intermidiate nodes are not found while traversing the path,\
-            they are created with data=None.
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        for path_name in path_arr[:-1]:
-            if path_name == "":
-                raise EmptyNameError("Nodes with empty names are not allowed")
-            next_node = current_node.get_child_by_name(path_name)
-            if next_node is None:
-                next_node = TreeNode(path_name, current_node)
-                current_node.add_child(next_node)
-            current_node = next_node
-        new_node = TreeNode(path_arr[-1], current_node, data)
-        return current_node.add_child(new_node)
-
-    def remove_node_by_path(self, path):
-        """Remove a node designated by the given path
-
-        Args:
-            path (str): A string of names separated by a '.' that reaches\
-             the desired node when followed
-        """
-        path_arr = path.split(".")
-        current_node = self.root
-        parent_node = None
-        for path_name in path_arr:
-            next_node = current_node.get_child_by_name(path_name)
-            if next_node is None:
-                return None
-            parent_node = current_node
-            current_node = next_node
-        return parent_node.remove_child(current_node)
-
-    def __str__(self):
-        "Return a string representation of the tree"
-        return self.root.__str__(0)
-
-

Methods

-
-
-def add_node_by_path(self, path, data=None) -
-
-

Add a node designated by the given path

-

Args

-
-
path : str
-
A string of names separated by a '.' that reaches -the desired node when followed
-
data
-
The data associated with the newly added node
-
-

Notes

-

If intermidiate nodes are not found while traversing the path, -they are created with data=None.

-
-Source code -
def add_node_by_path(self, path, data=None):
-    """Add a node designated by the given path
-
-    Args:
-        path (str): A string of names separated by a '.' that reaches\
-         the desired node when followed
-
-        data: The data associated with the newly added node
-
-    Notes:
-        If intermidiate nodes are not found while traversing the path,\
-        they are created with data=None.
-    """
-    path_arr = path.split(".")
-    current_node = self.root
-    for path_name in path_arr[:-1]:
-        if path_name == "":
-            raise EmptyNameError("Nodes with empty names are not allowed")
-        next_node = current_node.get_child_by_name(path_name)
-        if next_node is None:
-            next_node = TreeNode(path_name, current_node)
-            current_node.add_child(next_node)
-        current_node = next_node
-    new_node = TreeNode(path_arr[-1], current_node, data)
-    return current_node.add_child(new_node)
-
-
-
-def get_by_path(self, path) -
-
-

Retrieves a node designated by the given path

-

Args

-
-
path : str
-
A string of names separated by a '.' that reaches -the desired node when followed
-
data
-
The data associated with the newly added node
-
-

Returns

-
-
None if an intermidiate node is not found. -Else the searched node is returned
-
 
-
-
-Source code -
def get_by_path(self, path):
-    """Retrieves a node designated by the given path
-
-    Args:
-        path (str): A string of names separated by a '.' that reaches\
-         the desired node when followed
-
-        data: The data associated with the newly added node
-
-    Returns:
-        None if an intermidiate node is not found.\
-        Else the searched node is returned
-    """
-    path_arr = path.split(".")
-    current_node = self.root
-    for name in path_arr:
-        next_node = current_node.get_child_by_name(name)
-        if next_node is None:
-            return None
-        current_node = next_node
-    return current_node
-
-
-
-def remove_node(self, node) -
-
-

Remove a node from the tree.

-

Args

-
-
node : TreeNode
-
The node to be removed
-
-
-Source code -
def remove_node(self, node):
-    """Remove a node from the tree.
-
-    Args:
-        node (TreeNode): The node to be removed
-    """
-    if node == self.root:
-        raise RootRemoveError("Can't remove the root node")
-    node.parent.remove_child(node)
-    return node
-
-
-
-def remove_node_by_path(self, path) -
-
-

Remove a node designated by the given path

-

Args

-
-
path : str
-
A string of names separated by a '.' that reaches -the desired node when followed
-
-
-Source code -
def remove_node_by_path(self, path):
-    """Remove a node designated by the given path
-
-    Args:
-        path (str): A string of names separated by a '.' that reaches\
-         the desired node when followed
-    """
-    path_arr = path.split(".")
-    current_node = self.root
-    parent_node = None
-    for path_name in path_arr:
-        next_node = current_node.get_child_by_name(path_name)
-        if next_node is None:
-            return None
-        parent_node = current_node
-        current_node = next_node
-    return parent_node.remove_child(current_node)
-
-
-
-def search_by_data(self, data) -
-
-

Search the nodes in the tree with the given data

-

Args

-
-
func : function
-
A predicate the recieves a TreeNode
-
-

Returns

-
-
list of TreeNode: The nodes found
-
 
-
-
-Source code -
def search_by_data(self, data):
-    """Search the nodes in the tree with the given data
-
-    Args:
-        func (function): A predicate the recieves a TreeNode
-
-    Returns:
-        list of TreeNode: The nodes found
-    """
-    return self.root.search_by_data(data)
-
-
-
-def search_by_name(self, name) -
-
-

Search the nodes in the tree with the passed name

-

Args

-
-
func : function
-
A predicate the recieves a TreeNode
-
-

Returns

-
-
list of TreeNode: The nodes found
-
 
-
-
-Source code -
def search_by_name(self, name):
-    """Search the nodes in the tree with the passed name
-
-    Args:
-        func (function): A predicate the recieves a TreeNode
-
-    Returns:
-        list of TreeNode: The nodes found
-    """
-    return self.root.search_by_name(name)
-
-
-
-def search_custom(self, func) -
-
-

Search the nodes in the tree satisfying the given predicate

-

Args

-
-
func : function
-
A predicate the recieves a TreeNode
-
-

Returns

-
-
list of TreeNode: The nodes found
-
 
-
-
-Source code -
def search_custom(self, func):
-    """Search the nodes in the tree satisfying the given predicate
-
-    Args:
-        func (function): A predicate the recieves a TreeNode
-
-    Returns:
-        list of TreeNode: The nodes found
-    """
-    return self.root.search_custom(func)
-
-
-
-
-
-class TreeNode -(name, parent, data=None) -
-
-

name -(str) -: The name associated with the node -children (dict[str:TreeNode]): A mapping between names and child nodes -parent -(TreeNode or None) -: The parent TreeNode (None for the root) -data -: Data associated with the node

-
-Source code -
class TreeNode:
-    def __init__(self, name, parent, data=None):
-        """
-        name     (str)               : The name associated with the node
-        children (dict[str:TreeNode]): A mapping between names and child nodes
-        parent   (TreeNode or None)  : The parent TreeNode (None for the root)
-        data                         : Data associated with the node
-        """
-        self.name = name
-        self.parent = parent
-        self.data = data
-        self.children = {}
-
-    def add_child(self, node):
-        """Adds a new child
-
-        Args:
-            node (TreeNode): The node to be added
-
-        Returns:
-            TreeNode: The newly added node
-        """
-        child_name = node.name
-        if child_name in self.children:
-            raise NameExistsError("A child with the given name already exists")
-        self.children[child_name] = node
-        return node
-
-    def search_by_name(self, name):
-        """Search in the node's subtree for nodes with the given name
-
-        Args:
-            name (str): The name to be searched for
-
-        Returns:
-            list of TreeNode: The found nodes
-        """
-        return self.search_custom(lambda x: x.name == name)
-
-    def search_by_data(self, data):
-        """Search in the node's subtree for nodes with the given data
-
-        Args:
-            data: The data to be searched for
-
-        Returns:
-            list of TreeNode: The found nodes
-        """
-        return self.search_custom(lambda x: x.data == data)
-
-    def search_custom(self, func):
-        """Search the node's subtree the nodes satisfying the given predicate
-
-        Args:
-            func (function): A predicate the recieves a TreeNode
-
-        Returns:
-            list of TreeNode: The nodes found
-        """
-        result = []
-        for v in self.children.values():
-            result.extend(v.search_custom(func))
-
-        if self.name != "" and func(self):
-            result.append(self)
-        return result
-
-    def get_child_by_name(self, name):
-        """Get the child with the given name
-
-        Args:
-            name (str): The name of the child
-
-        Returns:
-            TreeNode: The reqiested child. None if it doesn't exist.
-        """
-        return self.children.get(name)
-
-    def remove_child(self, node):
-        """Remove the node from the children if it exists
-
-        Args:
-            node (TreeNode): The node to be deleted
-
-        Returns:
-            TreeNode: The deleted node
-        """
-        return self.remove_child_by_name(node.name)
-
-    def remove_child_by_name(self, name):
-        """Remove the node from the children
-
-        Args:
-            node (TreeNode): The node to be deleted
-
-        Returns:
-            TreeNode: The deleted node. None if it doesn't exist
-        """
-        if name in self.children:
-            node = self.children[name]
-            del self.children[name]
-            return node
-
-    def get_path(self):
-        """Retrieves the path of the node
-
-        Returns:
-            str: The path
-        """
-        if self.name == "":
-            return ""
-        parent_path = self.parent.get_path()
-        if parent_path == "":
-            return self.name
-        else:
-            return parent_path + "." + self.name
-
-    def __str__(self, indentation=0):
-        """Returns a string representing the node's subtree
-
-        Args:
-            indentation (int, optional): The level to which the representation\
-                                         will be indented. Defaults to 0.
-
-        Returns:
-            str: The tree representation
-        """
-        result = "\t" * indentation + self._string_repr() + "\n"
-        for v in self.children.values():
-            result += v.__str__(indentation + 1)
-        return result
-
-    def _string_repr(self):
-        """A helper function to return the node's name and data as a string
-
-        Returns:
-            str: The node's string representation
-        """
-        if self.name == "":
-            return "dummy_root"
-        else:
-            return self.name + str(self.data).replace("\n", "\\n")
-
-

Methods

-
-
-def add_child(self, node) -
-
-

Adds a new child

-

Args

-
-
node : TreeNode
-
The node to be added
-
-

Returns

-
-
TreeNode
-
The newly added node
-
-
-Source code -
def add_child(self, node):
-    """Adds a new child
-
-    Args:
-        node (TreeNode): The node to be added
-
-    Returns:
-        TreeNode: The newly added node
-    """
-    child_name = node.name
-    if child_name in self.children:
-        raise NameExistsError("A child with the given name already exists")
-    self.children[child_name] = node
-    return node
-
-
-
-def get_child_by_name(self, name) -
-
-

Get the child with the given name

-

Args

-
-
name : str
-
The name of the child
-
-

Returns

-
-
TreeNode
-
The reqiested child. None if it doesn't exist.
-
-
-Source code -
def get_child_by_name(self, name):
-    """Get the child with the given name
-
-    Args:
-        name (str): The name of the child
-
-    Returns:
-        TreeNode: The reqiested child. None if it doesn't exist.
-    """
-    return self.children.get(name)
-
-
-
-def get_path(self) -
-
-

Retrieves the path of the node

-

Returns

-
-
str
-
The path
-
-
-Source code -
def get_path(self):
-    """Retrieves the path of the node
-
-    Returns:
-        str: The path
-    """
-    if self.name == "":
-        return ""
-    parent_path = self.parent.get_path()
-    if parent_path == "":
-        return self.name
-    else:
-        return parent_path + "." + self.name
-
-
-
-def remove_child(self, node) -
-
-

Remove the node from the children if it exists

-

Args

-
-
node : TreeNode
-
The node to be deleted
-
-

Returns

-
-
TreeNode
-
The deleted node
-
-
-Source code -
def remove_child(self, node):
-    """Remove the node from the children if it exists
-
-    Args:
-        node (TreeNode): The node to be deleted
-
-    Returns:
-        TreeNode: The deleted node
-    """
-    return self.remove_child_by_name(node.name)
-
-
-
-def remove_child_by_name(self, name) -
-
-

Remove the node from the children

-

Args

-
-
node : TreeNode
-
The node to be deleted
-
-

Returns

-
-
TreeNode
-
The deleted node. None if it doesn't exist
-
-
-Source code -
def remove_child_by_name(self, name):
-    """Remove the node from the children
-
-    Args:
-        node (TreeNode): The node to be deleted
-
-    Returns:
-        TreeNode: The deleted node. None if it doesn't exist
-    """
-    if name in self.children:
-        node = self.children[name]
-        del self.children[name]
-        return node
-
-
-
-def search_by_data(self, data) -
-
-

Search in the node's subtree for nodes with the given data

-

Args

-
-
data
-
The data to be searched for
-
-

Returns

-
-
list of TreeNode: The found nodes
-
 
-
-
-Source code -
def search_by_data(self, data):
-    """Search in the node's subtree for nodes with the given data
-
-    Args:
-        data: The data to be searched for
-
-    Returns:
-        list of TreeNode: The found nodes
-    """
-    return self.search_custom(lambda x: x.data == data)
-
-
-
-def search_by_name(self, name) -
-
-

Search in the node's subtree for nodes with the given name

-

Args

-
-
name : str
-
The name to be searched for
-
-

Returns

-
-
list of TreeNode: The found nodes
-
 
-
-
-Source code -
def search_by_name(self, name):
-    """Search in the node's subtree for nodes with the given name
-
-    Args:
-        name (str): The name to be searched for
-
-    Returns:
-        list of TreeNode: The found nodes
-    """
-    return self.search_custom(lambda x: x.name == name)
-
-
-
-def search_custom(self, func) -
-
-

Search the node's subtree the nodes satisfying the given predicate

-

Args

-
-
func : function
-
A predicate the recieves a TreeNode
-
-

Returns

-
-
list of TreeNode: The nodes found
-
 
-
-
-Source code -
def search_custom(self, func):
-    """Search the node's subtree the nodes satisfying the given predicate
-
-    Args:
-        func (function): A predicate the recieves a TreeNode
-
-    Returns:
-        list of TreeNode: The nodes found
-    """
-    result = []
-    for v in self.children.values():
-        result.extend(v.search_custom(func))
-
-    if self.name != "" and func(self):
-        result.append(self)
-    return result
-
-
-
-
-
-
-
- -
- - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/entry_points/index.html b/docs/api/jumpscale/entry_points/index.html index 17a7e0e7e..ab9747db7 100644 --- a/docs/api/jumpscale/entry_points/index.html +++ b/docs/api/jumpscale/entry_points/index.html @@ -41,10 +41,6 @@

Sub-modules

``` ~> poetry run jsync …

-
jumpscale.entry_points.usershell
-
-
-
@@ -70,7 +66,6 @@

Index

  • jumpscale.entry_points.jsctl
  • jumpscale.entry_points.jsng
  • jumpscale.entry_points.jsync
  • -
  • jumpscale.entry_points.usershell
  • diff --git a/docs/api/jumpscale/entry_points/usershell.html b/docs/api/jumpscale/entry_points/usershell.html deleted file mode 100644 index 767d0895f..000000000 --- a/docs/api/jumpscale/entry_points/usershell.html +++ /dev/null @@ -1,828 +0,0 @@ - - - - - - -jumpscale.entry_points.usershell API documentation - - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.entry_points.usershell

    -
    -
    -
    - -Expand source code - -
    import os
    -import re
    -import time
    -import sys
    -import traceback
    -import argparse
    -import requests
    -
    -import inspect
    -import cgi
    -
    -from prompt_toolkit import PromptSession
    -from prompt_toolkit.completion import Completion
    -from prompt_toolkit.shortcuts import print_formatted_text
    -from prompt_toolkit.eventloop.async_generator import AsyncGeneratorItem
    -from prompt_toolkit.validation import Validator, ValidationError
    -from prompt_toolkit.styles import Style
    -from prompt_toolkit.formatted_text import HTML
    -from jumpscale import threesdk
    -from jumpscale.threesdk import settings
    -from jumpscale.core.exceptions.exceptions import JSException
    -from jumpscale.clients.docker.docker import DockerClient
    -from jumpscale.threesdk.threebot import ThreeBot, DEFAULT_IMAGE
    -from jumpscale.core.config import get_current_version
    -
    -
    -BASE_CONFIG_DIR = os.path.join(os.environ.get("HOME", "/root"), ".jsng")
    -HISTORY_FILENAME = os.path.join(BASE_CONFIG_DIR, "history.txt")
    -
    -DEFAULT_TOOLBAR_MSG = "Welcome to 3sdk enter info for help"
    -
    -style = Style.from_dict(
    -    {
    -        # User input (default text).
    -        "bottom-toolbar": "#ffffff bg:#333333",
    -        "default": "#aaaaaa",
    -        # Prompt.
    -    }
    -)
    -
    -
    -def get_binary_link():
    -    resp = requests.get("https://api.github.com/repos/threefoldtech/js-ng/releases/latest")
    -    resp = resp.json()
    -    # get versions
    -    download_link = ""
    -    version = resp["tag_name"]
    -    for platform in resp["assets"]:
    -        if sys.platform in platform["name"]:
    -            download_link = platform["browser_download_url"]
    -    return version, download_link
    -
    -
    -def update():
    -    print("checking for updates")
    -    latest_version, binary_link = get_binary_link()
    -    current_version = get_current_version()
    -    if latest_version != current_version:
    -        print(f"version: {latest_version} is available get it from {binary_link}")
    -        return
    -    docker_client = DockerClient()
    -    print("Checking for new docker image")
    -    docker_client.client.images.pull(f"{DEFAULT_IMAGE}:{latest_version}")
    -    print("Starting 3sdk containers")
    -    for container_name in os.listdir(os.path.expanduser("~/.config/jumpscale/containers")):
    -        ThreeBot.delete(container_name)
    -        ThreeBot.install(container_name)
    -
    -
    -def print_error(error):
    -    print_formatted_text(HTML("<ansired>{}</ansired>".format(cgi.html.escape(str(error)))))
    -
    -
    -def partition_line(line):
    -    def replacer(m):
    -        return m.group().replace(" ", "\0").strip("\"'")
    -
    -    result = re.sub(r"""(['"]).*?\1""", replacer, line)
    -    parts = []
    -    for part in result.split():
    -        parts.append(part.replace("\0", " "))
    -    return parts
    -
    -
    -def noexpert_error(error):
    -    reports_location = f"{os.environ.get('HOME', os.environ.get('USERPROFILE', ''))}/sandbox/reports"
    -    error_file_location = f"{reports_location}/jsngreport_{time.strftime('%d%H%M%S')}.log"
    -    if not os.path.exists(reports_location):
    -        os.makedirs(reports_location)
    -    with open(error_file_location, "w") as f:
    -        f.write(str(error))
    -    err_msg = f"""Something went wrong. Please contact support at https://support.grid.tf/
    -Error report file has been created on your machine in this location: {error_file_location}
    -        """
    -    return err_msg
    -
    -
    -class Shell(Validator):
    -    def __init__(self):
    -        self._prompt = PromptSession()
    -        self.mode = None
    -        self.toolbarmsg = DEFAULT_TOOLBAR_MSG
    -
    -    def get_completions_async(self, document, complete_event):
    -        text = document.current_line_before_cursor
    -        parts = partition_line(text)
    -        if not parts:
    -            root = None
    -            more = []
    -        else:
    -            root, more = parts[0], parts[1:]
    -        items = []
    -        if not root or not hasattr(threesdk, root):
    -            style = "bg:ansibrightblue"
    -            items += threesdk.__all__
    -            self.toolbarmsg = DEFAULT_TOOLBAR_MSG
    -        else:
    -            style = "bg:ansigreen"
    -            obj = getattr(threesdk, root)
    -            if not more or not hasattr(obj, more[0]):
    -                # complete object attributes
    -                self.toolbarmsg = threesdk._get_doc_line(obj.__doc__)
    -                for name, member in inspect.getmembers(obj, inspect.isroutine):
    -                    if not name.startswith("_"):
    -                        items.append(name)
    -                text = "" if not more else more[-1]
    -            else:
    -                # complete arguments
    -                func = getattr(obj, more[0])
    -                self.toolbarmsg = threesdk._get_doc_line(func.__doc__)
    -                style = "bg:ansired"
    -                for arg in inspect.getfullargspec(func).args:
    -                    field = arg + "="
    -                    if field in text:
    -                        continue
    -                    items.append(field)
    -                if len(more) > 1:
    -                    text = more[-1]
    -                else:
    -                    text = ""
    -
    -        for item in items:
    -            if not item:
    -                continue
    -            if isinstance(item, Completion):
    -                item.start_position = -len(text)
    -            else:
    -                item = Completion(item, -len(text))
    -            regex = ".*".join(text)
    -            item.style = style
    -            if not text or re.search(regex, item.text):
    -                yield AsyncGeneratorItem(item)
    -
    -    def bottom_toolbar(self):
    -        return [("class:bottom-toolbar", self.toolbarmsg)]
    -
    -    def validate(self, document):
    -        text = document.current_line_before_cursor
    -        if not text:
    -            return
    -        root, *more = text.split(" ")
    -        submodule = getattr(threesdk, root, None)
    -        if not submodule:
    -            raise ValidationError(message=f"No such subcommand {root}")
    -        if not more and callable(submodule):
    -            func = root
    -        elif more:
    -            func = getattr(submodule, more[0], None)
    -            if not func:
    -                raise ValidationError(message=f"{root} has no command called {more[0]}")
    -        else:
    -            raise ValidationError(message="Invalid command")
    -        # TODO: validate args
    -        return
    -
    -    def get_func_kwargs(self, cmd):
    -        parts = partition_line(cmd)
    -        root, extra = parts[0], parts[1:]
    -        module = getattr(threesdk, root)
    -        if inspect.isroutine(module):
    -            return module, self.get_kwargs(module, *extra)
    -        else:
    -            func = getattr(module, extra[0])
    -            return func, self.get_kwargs(func, *extra[1:])
    -
    -    def get_kwargs(self, func, *args):
    -        funcspec = inspect.getfullargspec(func)
    -        kwargs = {}
    -        for arg in args:
    -            key, val = arg.split("=", 1)
    -            isbool = funcspec.annotations.get(key) is bool
    -            if isbool:
    -                if val:
    -                    val = val.lower() in ["y", "yes", "1", "true"]
    -                else:
    -                    val = True
    -            kwargs[key] = val
    -        return kwargs
    -
    -    def execute(self, cmd):
    -        if not cmd.strip():
    -            return
    -        try:
    -            func, kwargs = self.get_func_kwargs(cmd)
    -            func(**kwargs)
    -        except JSException as e:
    -            if not settings.expert:
    -                print_error(str(e))
    -            else:
    -                print_error(traceback.format_exc())
    -        except Exception:
    -            if not settings.expert:
    -                print_error(noexpert_error(traceback.format_exc()))
    -            else:
    -                print_error(traceback.format_exc())
    -
    -    def make_prompt(self):
    -        root = ("class:default", "3sdk>")
    -        while True:
    -            try:
    -                result = self.prompt([root])
    -                self.execute(result)
    -            except (EOFError, KeyboardInterrupt):
    -                sys.exit(0)
    -
    -    def prompt(self, msg):
    -        return self._prompt.prompt(
    -            msg, completer=self, validator=self, style=style, bottom_toolbar=self.bottom_toolbar,
    -        )
    -
    -
    -def run():
    -    parser = argparse.ArgumentParser()
    -    parser.add_argument("--update", action="store_true", help="Update 3sdk")
    -    parser.add_argument("--expert", action="store_true", help="Run 3sdk in expert mode")
    -    args = parser.parse_args()
    -    settings.expert = args.expert
    -
    -    if args.update:
    -        update()
    -    else:
    -        shell = Shell()
    -        shell.make_prompt()
    -
    -
    -if __name__ == "__main__":
    -    run()
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    - -
    -
    -
    - -Expand source code - -
    def get_binary_link():
    -    resp = requests.get("https://api.github.com/repos/threefoldtech/js-ng/releases/latest")
    -    resp = resp.json()
    -    # get versions
    -    download_link = ""
    -    version = resp["tag_name"]
    -    for platform in resp["assets"]:
    -        if sys.platform in platform["name"]:
    -            download_link = platform["browser_download_url"]
    -    return version, download_link
    -
    -
    -
    -def noexpert_error(error) -
    -
    -
    -
    - -Expand source code - -
    def noexpert_error(error):
    -    reports_location = f"{os.environ.get('HOME', os.environ.get('USERPROFILE', ''))}/sandbox/reports"
    -    error_file_location = f"{reports_location}/jsngreport_{time.strftime('%d%H%M%S')}.log"
    -    if not os.path.exists(reports_location):
    -        os.makedirs(reports_location)
    -    with open(error_file_location, "w") as f:
    -        f.write(str(error))
    -    err_msg = f"""Something went wrong. Please contact support at https://support.grid.tf/
    -Error report file has been created on your machine in this location: {error_file_location}
    -        """
    -    return err_msg
    -
    -
    -
    -def partition_line(line) -
    -
    -
    -
    - -Expand source code - -
    def partition_line(line):
    -    def replacer(m):
    -        return m.group().replace(" ", "\0").strip("\"'")
    -
    -    result = re.sub(r"""(['"]).*?\1""", replacer, line)
    -    parts = []
    -    for part in result.split():
    -        parts.append(part.replace("\0", " "))
    -    return parts
    -
    -
    -
    -def print_error(error) -
    -
    -
    -
    - -Expand source code - -
    def print_error(error):
    -    print_formatted_text(HTML("<ansired>{}</ansired>".format(cgi.html.escape(str(error)))))
    -
    -
    -
    -def run() -
    -
    -
    -
    - -Expand source code - -
    def run():
    -    parser = argparse.ArgumentParser()
    -    parser.add_argument("--update", action="store_true", help="Update 3sdk")
    -    parser.add_argument("--expert", action="store_true", help="Run 3sdk in expert mode")
    -    args = parser.parse_args()
    -    settings.expert = args.expert
    -
    -    if args.update:
    -        update()
    -    else:
    -        shell = Shell()
    -        shell.make_prompt()
    -
    -
    -
    -def update() -
    -
    -
    -
    - -Expand source code - -
    def update():
    -    print("checking for updates")
    -    latest_version, binary_link = get_binary_link()
    -    current_version = get_current_version()
    -    if latest_version != current_version:
    -        print(f"version: {latest_version} is available get it from {binary_link}")
    -        return
    -    docker_client = DockerClient()
    -    print("Checking for new docker image")
    -    docker_client.client.images.pull(f"{DEFAULT_IMAGE}:{latest_version}")
    -    print("Starting 3sdk containers")
    -    for container_name in os.listdir(os.path.expanduser("~/.config/jumpscale/containers")):
    -        ThreeBot.delete(container_name)
    -        ThreeBot.install(container_name)
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Shell -
    -
    -

    Abstract base class for an input validator.

    -

    A validator is typically created in one of the following two ways:

    -
      -
    • Either by overriding this class and implementing the validate method.
    • -
    • Or by passing a callable to Validator.from_callable.
    • -
    -

    If the validation takes some time and needs to happen in a background -thread, this can be wrapped in a :class:.ThreadedValidator.

    -
    - -Expand source code - -
    class Shell(Validator):
    -    def __init__(self):
    -        self._prompt = PromptSession()
    -        self.mode = None
    -        self.toolbarmsg = DEFAULT_TOOLBAR_MSG
    -
    -    def get_completions_async(self, document, complete_event):
    -        text = document.current_line_before_cursor
    -        parts = partition_line(text)
    -        if not parts:
    -            root = None
    -            more = []
    -        else:
    -            root, more = parts[0], parts[1:]
    -        items = []
    -        if not root or not hasattr(threesdk, root):
    -            style = "bg:ansibrightblue"
    -            items += threesdk.__all__
    -            self.toolbarmsg = DEFAULT_TOOLBAR_MSG
    -        else:
    -            style = "bg:ansigreen"
    -            obj = getattr(threesdk, root)
    -            if not more or not hasattr(obj, more[0]):
    -                # complete object attributes
    -                self.toolbarmsg = threesdk._get_doc_line(obj.__doc__)
    -                for name, member in inspect.getmembers(obj, inspect.isroutine):
    -                    if not name.startswith("_"):
    -                        items.append(name)
    -                text = "" if not more else more[-1]
    -            else:
    -                # complete arguments
    -                func = getattr(obj, more[0])
    -                self.toolbarmsg = threesdk._get_doc_line(func.__doc__)
    -                style = "bg:ansired"
    -                for arg in inspect.getfullargspec(func).args:
    -                    field = arg + "="
    -                    if field in text:
    -                        continue
    -                    items.append(field)
    -                if len(more) > 1:
    -                    text = more[-1]
    -                else:
    -                    text = ""
    -
    -        for item in items:
    -            if not item:
    -                continue
    -            if isinstance(item, Completion):
    -                item.start_position = -len(text)
    -            else:
    -                item = Completion(item, -len(text))
    -            regex = ".*".join(text)
    -            item.style = style
    -            if not text or re.search(regex, item.text):
    -                yield AsyncGeneratorItem(item)
    -
    -    def bottom_toolbar(self):
    -        return [("class:bottom-toolbar", self.toolbarmsg)]
    -
    -    def validate(self, document):
    -        text = document.current_line_before_cursor
    -        if not text:
    -            return
    -        root, *more = text.split(" ")
    -        submodule = getattr(threesdk, root, None)
    -        if not submodule:
    -            raise ValidationError(message=f"No such subcommand {root}")
    -        if not more and callable(submodule):
    -            func = root
    -        elif more:
    -            func = getattr(submodule, more[0], None)
    -            if not func:
    -                raise ValidationError(message=f"{root} has no command called {more[0]}")
    -        else:
    -            raise ValidationError(message="Invalid command")
    -        # TODO: validate args
    -        return
    -
    -    def get_func_kwargs(self, cmd):
    -        parts = partition_line(cmd)
    -        root, extra = parts[0], parts[1:]
    -        module = getattr(threesdk, root)
    -        if inspect.isroutine(module):
    -            return module, self.get_kwargs(module, *extra)
    -        else:
    -            func = getattr(module, extra[0])
    -            return func, self.get_kwargs(func, *extra[1:])
    -
    -    def get_kwargs(self, func, *args):
    -        funcspec = inspect.getfullargspec(func)
    -        kwargs = {}
    -        for arg in args:
    -            key, val = arg.split("=", 1)
    -            isbool = funcspec.annotations.get(key) is bool
    -            if isbool:
    -                if val:
    -                    val = val.lower() in ["y", "yes", "1", "true"]
    -                else:
    -                    val = True
    -            kwargs[key] = val
    -        return kwargs
    -
    -    def execute(self, cmd):
    -        if not cmd.strip():
    -            return
    -        try:
    -            func, kwargs = self.get_func_kwargs(cmd)
    -            func(**kwargs)
    -        except JSException as e:
    -            if not settings.expert:
    -                print_error(str(e))
    -            else:
    -                print_error(traceback.format_exc())
    -        except Exception:
    -            if not settings.expert:
    -                print_error(noexpert_error(traceback.format_exc()))
    -            else:
    -                print_error(traceback.format_exc())
    -
    -    def make_prompt(self):
    -        root = ("class:default", "3sdk>")
    -        while True:
    -            try:
    -                result = self.prompt([root])
    -                self.execute(result)
    -            except (EOFError, KeyboardInterrupt):
    -                sys.exit(0)
    -
    -    def prompt(self, msg):
    -        return self._prompt.prompt(
    -            msg, completer=self, validator=self, style=style, bottom_toolbar=self.bottom_toolbar,
    -        )
    -
    -

    Ancestors

    -
      -
    • prompt_toolkit.validation.Validator
    • -
    -

    Methods

    -
    -
    -def bottom_toolbar(self) -
    -
    -
    -
    - -Expand source code - -
    def bottom_toolbar(self):
    -    return [("class:bottom-toolbar", self.toolbarmsg)]
    -
    -
    -
    -def execute(self, cmd) -
    -
    -
    -
    - -Expand source code - -
    def execute(self, cmd):
    -    if not cmd.strip():
    -        return
    -    try:
    -        func, kwargs = self.get_func_kwargs(cmd)
    -        func(**kwargs)
    -    except JSException as e:
    -        if not settings.expert:
    -            print_error(str(e))
    -        else:
    -            print_error(traceback.format_exc())
    -    except Exception:
    -        if not settings.expert:
    -            print_error(noexpert_error(traceback.format_exc()))
    -        else:
    -            print_error(traceback.format_exc())
    -
    -
    -
    -def get_completions_async(self, document, complete_event) -
    -
    -
    -
    - -Expand source code - -
    def get_completions_async(self, document, complete_event):
    -    text = document.current_line_before_cursor
    -    parts = partition_line(text)
    -    if not parts:
    -        root = None
    -        more = []
    -    else:
    -        root, more = parts[0], parts[1:]
    -    items = []
    -    if not root or not hasattr(threesdk, root):
    -        style = "bg:ansibrightblue"
    -        items += threesdk.__all__
    -        self.toolbarmsg = DEFAULT_TOOLBAR_MSG
    -    else:
    -        style = "bg:ansigreen"
    -        obj = getattr(threesdk, root)
    -        if not more or not hasattr(obj, more[0]):
    -            # complete object attributes
    -            self.toolbarmsg = threesdk._get_doc_line(obj.__doc__)
    -            for name, member in inspect.getmembers(obj, inspect.isroutine):
    -                if not name.startswith("_"):
    -                    items.append(name)
    -            text = "" if not more else more[-1]
    -        else:
    -            # complete arguments
    -            func = getattr(obj, more[0])
    -            self.toolbarmsg = threesdk._get_doc_line(func.__doc__)
    -            style = "bg:ansired"
    -            for arg in inspect.getfullargspec(func).args:
    -                field = arg + "="
    -                if field in text:
    -                    continue
    -                items.append(field)
    -            if len(more) > 1:
    -                text = more[-1]
    -            else:
    -                text = ""
    -
    -    for item in items:
    -        if not item:
    -            continue
    -        if isinstance(item, Completion):
    -            item.start_position = -len(text)
    -        else:
    -            item = Completion(item, -len(text))
    -        regex = ".*".join(text)
    -        item.style = style
    -        if not text or re.search(regex, item.text):
    -            yield AsyncGeneratorItem(item)
    -
    -
    -
    -def get_func_kwargs(self, cmd) -
    -
    -
    -
    - -Expand source code - -
    def get_func_kwargs(self, cmd):
    -    parts = partition_line(cmd)
    -    root, extra = parts[0], parts[1:]
    -    module = getattr(threesdk, root)
    -    if inspect.isroutine(module):
    -        return module, self.get_kwargs(module, *extra)
    -    else:
    -        func = getattr(module, extra[0])
    -        return func, self.get_kwargs(func, *extra[1:])
    -
    -
    -
    -def get_kwargs(self, func, *args) -
    -
    -
    -
    - -Expand source code - -
    def get_kwargs(self, func, *args):
    -    funcspec = inspect.getfullargspec(func)
    -    kwargs = {}
    -    for arg in args:
    -        key, val = arg.split("=", 1)
    -        isbool = funcspec.annotations.get(key) is bool
    -        if isbool:
    -            if val:
    -                val = val.lower() in ["y", "yes", "1", "true"]
    -            else:
    -                val = True
    -        kwargs[key] = val
    -    return kwargs
    -
    -
    -
    -def make_prompt(self) -
    -
    -
    -
    - -Expand source code - -
    def make_prompt(self):
    -    root = ("class:default", "3sdk>")
    -    while True:
    -        try:
    -            result = self.prompt([root])
    -            self.execute(result)
    -        except (EOFError, KeyboardInterrupt):
    -            sys.exit(0)
    -
    -
    -
    -def prompt(self, msg) -
    -
    -
    -
    - -Expand source code - -
    def prompt(self, msg):
    -    return self._prompt.prompt(
    -        msg, completer=self, validator=self, style=style, bottom_toolbar=self.bottom_toolbar,
    -    )
    -
    -
    -
    -def validate(self, document) -
    -
    -

    Validate the input. -If invalid, this should raise a :class:.ValidationError.

    -

    :param document: :class:~prompt_toolkit.document.Document instance.

    -
    - -Expand source code - -
    def validate(self, document):
    -    text = document.current_line_before_cursor
    -    if not text:
    -        return
    -    root, *more = text.split(" ")
    -    submodule = getattr(threesdk, root, None)
    -    if not submodule:
    -        raise ValidationError(message=f"No such subcommand {root}")
    -    if not more and callable(submodule):
    -        func = root
    -    elif more:
    -        func = getattr(submodule, more[0], None)
    -        if not func:
    -            raise ValidationError(message=f"{root} has no command called {more[0]}")
    -    else:
    -        raise ValidationError(message="Invalid command")
    -    # TODO: validate args
    -    return
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/api/jumpscale/god.html b/docs/api/jumpscale/god.html deleted file mode 100644 index 8df6eae9d..000000000 --- a/docs/api/jumpscale/god.html +++ /dev/null @@ -1,803 +0,0 @@ - - - - - - - - jumpscale.loader API documentation - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.loader

    -
    -
    -

    This module coverts the god object j and its loading process. - the idea is with hierarchy like this

    -
    project1/
    -         /rootnamespace (jumpscale)
    -            /subnamespace1
    -                ... pkg1
    -                ... pkg2
    -            /subnamespace2
    -                ... pkg1
    -                ... pkg2
    -project2/
    -         /rootnamespace (jumpscale)
    -            /subnamespace1
    -                ... pkg1
    -                ... pkg2
    -            /subnamespace2
    -                ... pkg1
    -                ... pkg2
    -
    -
      -
    • we get all the paths of the rootnamespace
    • -
    • we get all the subnamespaces
    • -
    • we get all the inner packages and import all of them (lazily) or load them eagerly but just - once.
    • -
    -

    real example:

    -
    js-ng
    -├── jumpscale   <- root namespace
    -│   ├── clients  <- subnamespace where people can register on
    -│   │   ├── base.py
    -│   │   ├── github   <- package in subnamespace
    -│   │   │   ├── github.py
    -│   │   │   └── __init__.py
    -│   │   └── gogs
    -│   │       ├── gogs.py
    -│   │       └── __init__.py
    -│   ├── core
    -│   │   ├── config.py
    -│   │   ├── exceptions.py
    -│   │   └── logging.py
    -│   ├── data
    -│   │   ├── idgenerator
    -│   │   │   ├── idgenerator.py
    -│   │   │   └── __init__.py
    -│   │   └── serializers
    -│   │       ├── __init__.py
    -│   │       └── serializers.py
    -│   ├── god.py
    -│   ├── sals
    -│   │   └── fs
    -│   │       ├── fs.py
    -│   │       └── __init__.py
    -│   └── tools
    -│       └── keygen
    -│           ├── __init__.py
    -│           └── keygen.py
    -├── README.md
    -└── tests
    -    └── test_loads_j.py
    -js-sdk
    -├── jumpscale
    -│   ├── clients
    -│   │   └── gitlab
    -│   │       ├── gitlab.py
    -│   │       └── __init__.py
    -│   ├── sals
    -│   │   └── zos
    -│   │       ├── __init__.py
    -│   │       └── zos.py
    -│   └── tools
    -├── README.md
    -└── tests
    -    └── test_success.py
    -
    -
    - Source code -
    """This module coverts the god object j and its loading process.
    -the idea is with hierarchy like this
    -```
    -project1/
    -         /rootnamespace (jumpscale)
    -            /subnamespace1
    -                ... pkg1
    -                ... pkg2
    -            /subnamespace2
    -                ... pkg1
    -                ... pkg2
    -project2/
    -         /rootnamespace (jumpscale)
    -            /subnamespace1
    -                ... pkg1
    -                ... pkg2
    -            /subnamespace2
    -                ... pkg1
    -                ... pkg2
    -```
    -- we get all the paths of the `rootnamespace`
    -- we get all the subnamespaces
    -- we get all the inner packages and import all of them (lazily) or load them eagerly but just once.
    -
    -
    -real example:
    -```
    -js-ng
    -├── jumpscale   <- root namespace
    -│   ├── clients  <- subnamespace where people can register on
    -│   │   ├── base.py
    -│   │   ├── github   <- package in subnamespace
    -│   │   │   ├── github.py
    -│   │   │   └── __init__.py
    -│   │   └── gogs
    -│   │       ├── gogs.py
    -│   │       └── __init__.py
    -│   ├── core
    -│   │   ├── config.py
    -│   │   ├── exceptions.py
    -│   │   └── logging.py
    -│   ├── data
    -│   │   ├── idgenerator
    -│   │   │   ├── idgenerator.py
    -│   │   │   └── __init__.py
    -│   │   └── serializers
    -│   │       ├── __init__.py
    -│   │       └── serializers.py
    -│   ├── god.py
    -│   ├── sals
    -│   │   └── fs
    -│   │       ├── fs.py
    -│   │       └── __init__.py
    -│   └── tools
    -│       └── keygen
    -│           ├── __init__.py
    -│           └── keygen.py
    -├── README.md
    -└── tests
    -    └── test_loads_j.py
    -js-sdk
    -├── jumpscale
    -│   ├── clients
    -│   │   └── gitlab
    -│   │       ├── gitlab.py
    -│   │       └── __init__.py
    -│   ├── sals
    -│   │   └── zos
    -│   │       ├── __init__.py
    -│   │       └── zos.py
    -│   └── tools
    -├── README.md
    -└── tests
    -    └── test_success.py
    -```
    -"""
    -
    -
    -import collections
    -import importlib
    -import importlib.util
    -from jumpscale.core.config import get_config
    -import os
    -import pkgutil
    -import sys
    -import traceback
    -from types import SimpleNamespace
    -
    -__all__ = ["j"]
    -
    -
    -class ExportedModule(SimpleNamespace):
    -    def __init__(self, m):
    -        super().__init__()
    -        self._m = m
    -        self._exportedas = None
    -        self._loaded = False
    -
    -    def _load(self):
    -        if not self._loaded:
    -            self._exportedas = self._m.export_module_as()
    -            self._loaded = True
    -
    -    def __dir__(self):
    -        self._load()
    -        return dir(self._exportedas)
    -
    -    def __getattr__(self, name):
    -        self._load()
    -        return getattr(self._exportedas, name)
    -
    -
    -class ExportAsSimpleNamespace(SimpleNamespace):
    -    def __getattr__(self, name):
    -        # print("getting attr: ", name)
    -        if name not in self.__dict__:
    -            raise AttributeError(f"Can't find attr {name}")
    -        attr = self.__dict__[name]
    -        if "export_module_as" in dir(attr):
    -            return attr.export_module_as()
    -        else:
    -            return attr
    -
    -
    -def namespaceify(mapping):
    -    if isinstance(mapping, collections.Mapping) and not isinstance(mapping, ExportAsSimpleNamespace):
    -        for key, value in mapping.items():
    -            mapping[key] = namespaceify(value)
    -        return ExportAsSimpleNamespace(**mapping)
    -    return mapping
    -
    -
    -def loadjsmodules():
    -    import jumpscale
    -
    -    loadeddict = {"jumpscale": {}}
    -    for jsnamespace in jumpscale.__path__:
    -        for root, dirs, _ in os.walk(jsnamespace):
    -            for d in dirs:
    -                if d == "__pycache__":
    -                    continue
    -                if os.path.basename(root) == "jumpscale":
    -                    continue
    -
    -                if os.path.dirname(root) != jsnamespace:
    -                    continue
    -                # print("root: {} d: {}".format(root, d))
    -                rootbase = os.path.basename(root)
    -                loadeddict["jumpscale"].setdefault(rootbase, {})
    -                pkgname = d
    -                if "noload" in pkgname or pkgname.startswith("."):
    -                    continue
    -                importedpkgstr = "jumpscale.{}.{}".format(rootbase, pkgname)
    -                __all__.append(importedpkgstr)
    -                # globals()[importedpkgstr] = lazy_import.lazy_module(importedpkgstr)
    -                try:
    -                    m = importlib.import_module(importedpkgstr)
    -                except Exception as e:
    -                    traceback.print_exception(*sys.exc_info())
    -                    print("[-] {} at {} ".format(e, importedpkgstr))
    -                    continue
    -                else:
    -                    if hasattr(m, "export_module_as"):
    -                        # print("rootbase: ", rootbase, importedpkgstr)
    -                        # print(m.export_module_as)
    -                        expmod = ExportedModule(m)
    -                        expmod.__doc__ = m.__doc__
    -                        loadeddict["jumpscale"][rootbase][pkgname] = expmod
    -                        # loadeddict[importedpkgstr] = m.export_module_as
    -                    else:
    -                        loadeddict["jumpscale"][rootbase][pkgname] = m
    -
    -    return namespaceify(loadeddict)
    -
    -
    -class J:
    -    """
    -        Here we simulate god object `j` by delegating the calls to suitable subnamespace
    -    """
    -
    -    def __init__(self):
    -        self.__loaded = False
    -
    -    def __dir__(self):
    -        self._load()
    -        return list(self.__loaded_simplenamespace.jumpscale.__dict__.keys()) + ["config", "exceptions", "logger"]
    -
    -    @property
    -    def logger(self):
    -        return self.__loaded_simplenamespace.jumpscale.core.logging
    -
    -    @property
    -    def application(self):
    -        return self.__loaded_simplenamespace.jumpscale.core.application
    -
    -    @property
    -    def config(self):
    -        return self.__loaded_simplenamespace.jumpscale.core.config
    -
    -    @property
    -    def exceptions(self):
    -        return self.__loaded_simplenamespace.jumpscale.core.exceptions
    -
    -    def reload(self):
    -        self.__loaded = False
    -        self.__loaded_simplenamespace = None
    -        self._load()
    -
    -    def _load(self):
    -        if not self.__loaded:
    -            # print("loading")
    -            # print("id :", id(self))
    -            self.__loaded_simplenamespace = namespaceify(loadjsmodules())
    -            self.__loaded = True
    -
    -    def __getattr__(self, name):
    -        self._load()
    -        return getattr(self.__loaded_simplenamespace.jumpscale, name)
    -
    -
    -j = J()
    -# jxmods = loadjsmodules()
    -j._load()
    -
    -
    -# register alerthandler as an error handler
    -alerts_config = get_config().get("alerts")
    -if alerts_config and alerts_config.get("enabled", True):
    -    j.tools.errorhandler.register_handler(
    -        handler=j.tools.alerthandler.alert_raise, level=alerts_config.get("level", 40)
    -    )
    -
    -# register global error hook
    -sys.excepthook = j.tools.errorhandler.excepthook
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - - diff --git a/docs/api/jumpscale/index.html b/docs/api/jumpscale/index.html index bbf6a37c3..c6238ffdd 100644 --- a/docs/api/jumpscale/index.html +++ b/docs/api/jumpscale/index.html @@ -58,10 +58,6 @@

    Sub-modules

    This module defines all of js-ng specific shell features …

    -
    jumpscale.threesdk
    -
    -
    -
    jumpscale.tools
    @@ -91,7 +87,6 @@

    Index

  • jumpscale.sals
  • jumpscale.servers
  • jumpscale.shell
  • -
  • jumpscale.threesdk
  • jumpscale.tools
  • diff --git a/docs/api/jumpscale/sals/fs/fs.html b/docs/api/jumpscale/sals/fs/fs.html deleted file mode 100644 index aa6245e01..000000000 --- a/docs/api/jumpscale/sals/fs/fs.html +++ /dev/null @@ -1,2503 +0,0 @@ - - - - - - -jumpscale.sals.fs.fs API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.sals.fs.fs

    -
    -
    -

    TODO docs for fs.

    -
    -Source code -
    """
    -#TODO docs for fs.
    -
    -"""
    -
    -import pathlib
    -import tempfile
    -import os
    -import shutil
    -import stat
    -from distutils import dir_util
    -from typing import List
    -
    -basename = os.path.basename
    -dirname = os.path.dirname
    -common_path = os.path.commonpath
    -common_prefix = os.path.commonprefix
    -norm_path = os.path.normpath
    -norm_case = os.path.normcase
    -get_access_time = os.path.getatime
    -get_modified_time = os.path.getmtime
    -get_creation_time = os.path.getctime
    -sep = os.path.sep
    -is_samefile = os.path.samefile
    -expandvars = os.path.expandvars
    -expanduser = os.path.expanduser
    -realpath = os.path.realpath
    -
    -
    -def home():
    -    return str(pathlib.Path.home())
    -
    -
    -def cwd():
    -    """Return current working directory.
    -
    -    Returns:
    -        str: current directory.
    -    """
    -    return str(pathlib.Path.cwd())
    -
    -
    -def is_dir(path: str) -> bool:
    -    """Checks if path is a dir
    -
    -    :param path: path to check
    -    :type path: str
    -    :return: True if is dir else False
    -    :rtype: bool
    -    """
    -    return pathlib.Path(path).is_dir()
    -
    -
    -def is_file(path: str) -> bool:
    -    """Checks if path is a file
    -
    -    Args:
    -        path (str): path to check if is file
    -
    -    Returns:
    -        bool: True if is file and False otherwise
    -    """
    -    return pathlib.Path(path).is_file()
    -
    -
    -def is_symlink(path: str) -> bool:
    -    """Checks if path symlink
    -
    -    Args:
    -        path (str): path to check if symlink
    -
    -    Returns:
    -        bool: True if symlink False otherwise
    -    """
    -    return pathlib.Path(path).is_symlink()
    -
    -
    -def is_absolute(path: str) -> bool:
    -    """Checks if path is absolute
    -
    -    Returns:
    -        bool: True if absolute
    -    """
    -    return pathlib.Path(path).is_absolute()
    -
    -
    -def is_mount(path: str) -> bool:
    -    """Checks if path is mount
    -
    -    Returns:
    -        bool: True if mount
    -    """
    -    return pathlib.Path(path).is_mount()
    -
    -
    -def is_ascii_file(path: str, checksize=4096) -> bool:
    -    """Checks if file `path` is ascii
    -
    -    Args:
    -        path (str): file path
    -        checksize (int, optional): checksize. Defaults to 4096.
    -
    -    Returns:
    -        bool: True if ascii file
    -    """
    -    # TODO: let's talk about checksize feature.
    -    try:
    -        with open(path, encoding="ascii") as f:
    -            f.read()
    -            return True
    -    except UnicodeDecodeError:
    -        return False
    -
    -
    -def is_empty_dir(path: str) -> bool:
    -    """Checks if path is emptry directory
    -
    -    Args:
    -        path (str): path to check if empty directory
    -
    -    Returns:
    -        bool: True if path is emptry directory
    -    """
    -
    -    try:
    -        g = pathlib.Path(path).iterdir()
    -        next(g)
    -    except StopIteration:
    -        # means we can't get next entry -> dir is empty.
    -        return True
    -    else:
    -        return False
    -
    -
    -is_binary_file = lambda path: not is_ascii_file(path)
    -
    -
    -def is_broken_link(path: str, clean=False) -> bool:
    -    """Checks if path is a broken symlink
    -
    -    Args:
    -        path (str): path to check
    -        clean (bool, optional): remove symlink if broken. Defaults to False.
    -
    -    Raises:
    -        NotImplementedError: [description]
    -
    -    Returns:
    -        bool: True if path is a broken symlink
    -    """
    -    raise NotImplementedError()
    -
    -
    -def stem(path: str) -> str:
    -    """returns the stem of a path (path without parent directory and without extension)
    -    e.g
    -        In [2]: t = j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl")
    -
    -        In [3]: t
    -        Out[3]: 'tmp-5383p1GOmMOOwvfi'
    -
    -    Args:
    -        path (str): path we want to get its stem
    -
    -    Returns:
    -        [type]: [description]
    -    """
    -    return pathlib.Path(path).stem
    -
    -
    -def mkdir(path: str, exist_ok=True):
    -    """Makes directory at path
    -
    -    Args:
    -        path (str): path to create dir at
    -        exist_ok (bool, optional): won't fail if directory exists. Defaults to True.
    -
    -    Returns:
    -        [type]: [description]
    -    """
    -    return pathlib.Path(path).mkdir(exist_ok=exist_ok)
    -
    -
    -def mkdirs(path: str, exist_ok=True):
    -    """Creates dir as well as all non exisitng parents in the path
    -
    -    Args:
    -        path (str): path to create dir at
    -        exist_ok (bool, optional): won't fail if directory exists. Defaults to True.
    -    """
    -    return os.makedirs(path, exist_ok=exist_ok)
    -
    -
    -def parent(path: str) -> str:
    -    """Get path's parent
    -
    -    Args:
    -        path (str): path to get its parent
    -
    -    Returns:
    -        str: parent path.
    -    """
    -    return str(pathlib.Path(path).parent)
    -
    -
    -def parents(path: str) -> List[str]:
    -    """Get parents list
    -
    -    e.g
    -    >>> j.sals.fs.parents("/tmp/home/ahmed/myfile.py")
    -    [PosixPath('/tmp/home/ahmed'),
    -    PosixPath('/tmp/home'),
    -    PosixPath('/tmp'),
    -    PosixPath('/')]
    -
    -    Args:
    -        path (str): path to get its parents
    -
    -    Returns:
    -        List[str]: list of parents
    -    """
    -
    -    return list([str(p) for p in pathlib.Path(path).parents])
    -
    -
    -def path_parts(path: str) -> List[str]:
    -    """Convert path to a list of parts
    -    e.g
    -     '/tmp/tmp-5383p1GOmMOOwvfi.tpl' ->  ('/', 'tmp', 'tmp-5383p1GOmMOOwvfi.tpl')
    -    Args:
    -        path (str): path to convert to parts
    -
    -    Returns:
    -        List[str]: path parts.
    -    """
    -    return pathlib.Path(path).parts
    -
    -
    -def exists(path: str) -> bool:
    -    """Checks if path exists
    -
    -    Args:
    -        path (str): path to check for existence
    -
    -    Returns:
    -        bool: True if exists
    -    """
    -    return pathlib.Path(path).exists()
    -
    -
    -def rename(path1: str, path2: str):
    -    """Rename path1 to path2
    -
    -    Args:
    -        path1 (str): source path
    -        path2 (str): dest path
    -
    -    """
    -    return pathlib.Path(path1).rename(path2)
    -
    -
    -def expanduser(path: str) -> str:
    -    """Expands the tilde `~` to username
    -    e.g
    -        j.sals.fs.expanduser("~/work") -> '/home/xmonader/work'
    -    Args:
    -        path (str): path with optionally `~`
    -
    -    Returns:
    -        str: path with tilde `~` resolved.
    -    """
    -    return str(pathlib.Path(path).expanduser())
    -
    -
    -def unlink(path: str):
    -    """unlink path
    -
    -    Args:
    -        path (str): path to unlink
    -
    -
    -    """
    -    return pathlib.Path(path).unlink()
    -
    -
    -def read_text(path: str) -> str:
    -    """read ascii content at `path`
    -
    -    Args:
    -        path (str): ascii file path
    -
    -    Returns:
    -        str: ascii content in path
    -    """
    -    return pathlib.Path(path).read_text()
    -
    -
    -read_ascii = read_file = read_text
    -
    -
    -def read_bytes(path: str) -> bytes:
    -    """read binary content at `path`
    -
    -    Args:
    -        path (str): binary file path
    -
    -    Returns:
    -        bytes: binary content in path
    -    """
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -read_binary = read_file_binary = read_bytes
    -
    -
    -def write_text(path: str, data: str, encoding=None):
    -    """write text `data` to path `path` with encoding
    -
    -    Args:
    -        path (str): path to write to
    -        data (str): ascii content
    -        encoding ([type], optional): encoding. Defaults to None.
    -
    -
    -    """
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -write_ascii = write_file = write_text
    -
    -
    -def write_bytes(path: str, data: bytes):
    -    """write binary `data` to path `path`
    -
    -    Args:
    -        path (str): path to write to
    -        data (bytes): binary content
    -
    -    """
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -write_binary = write_file_binary = write_bytes
    -
    -
    -def touch(path: str):
    -    """create file
    -
    -    Args:
    -        path (str): path to create file
    -
    -    """
    -    return pathlib.Path(path).touch()
    -
    -
    -def get_temp_filename(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) -> str:
    -    """Get temp filename
    -
    -    Args:
    -        mode (str, optional): [description]. Defaults to "w+b".
    -        buffering (int, optional): buffering. Defaults to -1.
    -        encoding ([type], optional): encoding . Defaults to None.
    -        newline ([type], optional):  Defaults to None.
    -        suffix ([type], optional): ending suffix. Defaults to None.
    -        prefix ([type], optional): prefix . Defaults to None.
    -        dir ([type], optional): where to create the file. Defaults to None.
    -
    -    Returns:
    -        [str]: temp filename
    -    """
    -    return tempfile.NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, dir).name
    -
    -
    -def get_temp_dirname(suffix=None, prefix=None, dir=None) -> str:
    -    """Get temp directory name
    -
    -    Args:
    -        suffix ([type], optional): ending suffix. Defaults to None.
    -        prefix ([type], optional): prefix . Defaults to None.
    -        dir ([type], optional): where to create the directory. Defaults to None.
    -
    -
    -    Returns:
    -        str: temp directory name.
    -    """
    -    return tempfile.TemporaryDirectory(suffix, prefix, dir).name
    -
    -
    -NamedTemporaryFile = tempfile.NamedTemporaryFile
    -TempraryDirectory = tempfile.TemporaryDirectory
    -mkdtemp = tempfile.mkdtemp
    -mkstemp = tempfile.mkstemp
    -get_temp_dir = tempfile.gettempdir
    -
    -
    -def parts_to_path(parts: List[str]) -> str:
    -    """Convert list of path parts into a path string
    -
    -    Args:
    -        parts (List[str]): path parts
    -
    -    Returns:
    -        str: joined path parts
    -    """
    -    path = pathlib.Path(parts[0])
    -    for p in parts[1:]:
    -        path = path.joinpath(p)
    -    return str(path)
    -
    -
    -def join_paths(*paths):
    -    return parts_to_path(paths)
    -
    -
    -def rm_emptry_dir(path: str):
    -    """Remove empty directory
    -
    -    Args:
    -        path (str): path to remove.
    -    """
    -    path = pathlib.Path(path)
    -    path.rmdir()
    -
    -
    -def rmtree(path: str):
    -    """Remove directory tree
    -    Args:
    -        path (str): path to remove
    -    """
    -    path = pathlib.Path(path)
    -    if path.is_file() or path.is_symlink():
    -        os.remove(path)
    -    elif path.is_dir():
    -        shutil.rmtree(path)
    -
    -
    -def copy_stat(src: str, dst: str, times=True, perms=True):
    -    """Copy stat of src to dst
    -
    -    Args:
    -        src (str): source path
    -        dst (str): destination
    -        times (bool, optional):  Defaults to True.
    -        perms (bool, optional): permissions Defaults to True.
    -    """
    -    st = os.stat(src)
    -    if hasattr(os, "utime"):
    -        os.utime(dst, (st.st_atime, st.st_mtime))
    -    if hasattr(os, "chmod"):
    -        m = stat.S_IMODE(st.st_mode)
    -        os.chmod(dst, m)
    -
    -
    -def copy_file(src: str, dst: str, times=False, perms=False):
    -    """Copy the file, optionally copying the permission bits (mode) and
    -        last access/modify time. If the destination file exists, it will be
    -        replaced. Raises OSError if the destination is a directory. If the
    -        platform does not have the ability to set the permission or times,
    -        ignore it.
    -        This is shutil.copyfile plus bits of shutil.copymode and
    -        shutil.copystat's implementation.
    -        shutil.copy and shutil.copy2 are not supported but are easy to do.
    -
    -    Args:
    -        src (str): source path
    -        dst (str): destination
    -
    -    """
    -    shutil.copyfile(src, dst)
    -    if times or perms:
    -        copy_stat(src, dst, times, perms)
    -
    -
    -def symlink(src: str, dst: str, overwrite=False):
    -    """Create a symbolic link.
    -
    -    Args:
    -        src (str): Source of link
    -        dst (str): Destination path of link
    -        overwrite (bool, optional): If link exists will delete it. Defaults to False.
    -    """
    -    if overwrite and exists(dst):
    -        os.unlink(dst)
    -
    -    os.symlink(src, dst)
    -
    -
    -copy_tree = dir_util.copy_tree
    -chdir = os.chdir
    -
    -
    -def change_dir(path: str) -> str:
    -    """Change current working directory to `path`
    -
    -    Args:
    -        path (str): path to switch current working directory to
    -
    -    Returns:
    -        str: new current working dir
    -    """
    -    os.chdir(path)
    -    return path
    -
    -
    -def chmod(path: str, mode):
    -    """change file mode for path to mode
    -
    -    Args:
    -        path (str): path
    -        mode (int): file mode
    -
    -    """
    -    return pathlib.Path(path).chmod(mode)
    -
    -
    -def lchmod(path: str, mode):
    -    """change file mode for path to mode (handles links too)
    -
    -    Args:
    -        path (str): path
    -        mode (int): file mode
    -
    -    """
    -    return pathlib.Path(path).lchmod(mode)
    -
    -
    -def stat(path: str):
    -    """Gets stat of path `path`
    -
    -    Args:
    -        path (str): path to get its stat
    -
    -    Returns:
    -        stat_result: returns stat struct.
    -    """
    -
    -    return pathlib.Path(path).stat()
    -
    -
    -def lstat(path: str):
    -    """Gets stat of path `path` (handles links)
    -
    -    Args:
    -        path (str): path to get its stat
    -
    -    Returns:
    -        stat_result: returns stat struct.
    -    """
    -
    -    return pathlib.Path(path).lstat()
    -
    -
    -def resolve(path: str) -> str:
    -    """resolve `.` and `..` in path
    -
    -    Args:
    -        path (str): path with optionally `.` and `..`
    -
    -    Returns:
    -        str: resolved path
    -    """
    -    return pathlib.Path(path).resolve()
    -
    -
    -def extension(path: str, include_dot=True):
    -    """Gets the extension of path
    -    '/home/ahmed/myfile.py' -> `.py` if include_dot else `py`
    -
    -    Args:
    -        path (str): [description]
    -        include_dot (bool, optional): controls whether to include the dot or not. Defaults to True.
    -
    -    Returns:
    -        str: extension
    -    """
    -    splitted = os.path.splitext(path)
    -    ext = ""
    -    if len(splitted) == 1:
    -        return ext
    -
    -    if include_dot:
    -        return splitted[1]
    -    else:
    -        return splitted[1].strip(".")
    -
    -
    -ext = extension
    -
    -
    -def chown():
    -    raise NotImplementedError()
    -
    -
    -def read_link(path):
    -    raise NotImplementedError()
    -
    -
    -def remove_links(path):
    -    raise NotImplementedError()
    -
    -
    -def change_filenames(from_, to, where):
    -    pass
    -
    -
    -def replace_words_in_files(from_, to, where):
    -    pass
    -
    -
    -move = shutil.move
    -
    -
    -def default_filter_fun(entry):
    -    return True
    -
    -
    -def walk(path: str, pat="*", filter_fun=default_filter_fun):
    -    """walk recursively on path
    -    e.g
    -        for el in walk('/tmp', filter_fun=j.sals.fs.is_file) : ..
    -        for el in walk('/tmp', filter_fun=j.sals.fs.is_dir) : ..
    -        for el in walk('/tmp', filter_fun= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        pat (str, optional): pattern to match against. Defaults to "*".
    -        filter_fun (Function, optional): filtering function. Defaults to default_filter_fun which accepts anything.
    -    """
    -    p = pathlib.Path(path)
    -    for entry in p.rglob(pat):
    -        # use rglob instead of glob("**/*")
    -        if filter_fun(entry):
    -            yield str(entry)
    -
    -
    -def walk_non_recursive(path: str, filter_fun=default_filter_fun):
    -    """walks non recursively on path
    -    e.g
    -        for el in walk('/tmp', filter=j.sals.fs.is_file) : ..
    -        for el in walk('/tmp', filter=j.sals.fs.is_dir) : ..
    -        for el in walk('/tmp', filter= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        pat (str, optional): pattern to match against. Defaults to "*".
    -        filter_fun (Function, optional): filtering function. Defaults to default_filter_fun which accepts anything.
    -    """
    -    p = pathlib.Path(path)
    -    for entry in p.iterdir():
    -        if filter_fun(entry):
    -            yield str(entry)
    -
    -
    -def walk_files(path: str, recursive=True):
    -    """
    -    walk over files in path and applies function `fun`
    -    e.g
    -
    -        for el in walk_files('/tmp') : ..
    -
    -    Args:
    -        path (str): path to walk over
    -        recursive (bool, optional): recursive or not. Defaults to True.
    -
    -
    -    """
    -
    -    if recursive:
    -        return walk(path, filter_fun=is_file)
    -    else:
    -        return walk_non_recursive(path, filter_fun=is_file)
    -
    -
    -def walk_dirs(path, recursive=True):
    -    """
    -        walk over directories in path and applies function `fun`
    -    e.g
    -
    -        for el in walk_dirs('/tmp') : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        recursive (bool, optional): recursive or not. Defaults to True.
    -
    -
    -    """
    -    if recursive:
    -        return walk(path, filter_fun=is_dir)
    -    else:
    -        return walk_non_recursive(path, filter_fun=is_dir)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def change_dir(path) -
    -
    -

    Change current working directory to path

    -

    Args

    -
    -
    path : str
    -
    path to switch current working directory to
    -
    -

    Returns

    -
    -
    str
    -
    new current working dir
    -
    -
    -Source code -
    def change_dir(path: str) -> str:
    -    """Change current working directory to `path`
    -
    -    Args:
    -        path (str): path to switch current working directory to
    -
    -    Returns:
    -        str: new current working dir
    -    """
    -    os.chdir(path)
    -    return path
    -
    -
    -
    -def change_filenames(from_, to, where) -
    -
    -
    -
    -Source code -
    def change_filenames(from_, to, where):
    -    pass
    -
    -
    -
    -def chmod(path, mode) -
    -
    -

    change file mode for path to mode

    -

    Args

    -
    -
    path : str
    -
    path
    -
    mode : int
    -
    file mode
    -
    -
    -Source code -
    def chmod(path: str, mode):
    -    """change file mode for path to mode
    -
    -    Args:
    -        path (str): path
    -        mode (int): file mode
    -
    -    """
    -    return pathlib.Path(path).chmod(mode)
    -
    -
    -
    -def chown() -
    -
    -
    -
    -Source code -
    def chown():
    -    raise NotImplementedError()
    -
    -
    -
    -def copy_file(src, dst, times=False, perms=False) -
    -
    -

    Copy the file, optionally copying the permission bits (mode) and -last access/modify time. If the destination file exists, it will be -replaced. Raises OSError if the destination is a directory. If the -platform does not have the ability to set the permission or times, -ignore it. -This is shutil.copyfile plus bits of shutil.copymode and -shutil.copystat's implementation. -shutil.copy and shutil.copy2 are not supported but are easy to do.

    -

    Args

    -
    -
    src : str
    -
    source path
    -
    dst : str
    -
    destination
    -
    -
    -Source code -
    def copy_file(src: str, dst: str, times=False, perms=False):
    -    """Copy the file, optionally copying the permission bits (mode) and
    -        last access/modify time. If the destination file exists, it will be
    -        replaced. Raises OSError if the destination is a directory. If the
    -        platform does not have the ability to set the permission or times,
    -        ignore it.
    -        This is shutil.copyfile plus bits of shutil.copymode and
    -        shutil.copystat's implementation.
    -        shutil.copy and shutil.copy2 are not supported but are easy to do.
    -
    -    Args:
    -        src (str): source path
    -        dst (str): destination
    -
    -    """
    -    shutil.copyfile(src, dst)
    -    if times or perms:
    -        copy_stat(src, dst, times, perms)
    -
    -
    -
    -def copy_stat(src, dst, times=True, perms=True) -
    -
    -

    Copy stat of src to dst

    -

    Args

    -
    -
    src : str
    -
    source path
    -
    dst : str
    -
    destination
    -
    times : bool, optional
    -
    Defaults to True.
    -
    perms : bool, optional
    -
    permissions Defaults to True.
    -
    -
    -Source code -
    def copy_stat(src: str, dst: str, times=True, perms=True):
    -    """Copy stat of src to dst
    -
    -    Args:
    -        src (str): source path
    -        dst (str): destination
    -        times (bool, optional):  Defaults to True.
    -        perms (bool, optional): permissions Defaults to True.
    -    """
    -    st = os.stat(src)
    -    if hasattr(os, "utime"):
    -        os.utime(dst, (st.st_atime, st.st_mtime))
    -    if hasattr(os, "chmod"):
    -        m = stat.S_IMODE(st.st_mode)
    -        os.chmod(dst, m)
    -
    -
    -
    -def cwd() -
    -
    -

    Return current working directory.

    -

    Returns

    -
    -
    str
    -
    current directory.
    -
    -
    -Source code -
    def cwd():
    -    """Return current working directory.
    -
    -    Returns:
    -        str: current directory.
    -    """
    -    return str(pathlib.Path.cwd())
    -
    -
    -
    -def default_filter_fun(entry) -
    -
    -
    -
    -Source code -
    def default_filter_fun(entry):
    -    return True
    -
    -
    -
    -def exists(path) -
    -
    -

    Checks if path exists

    -

    Args

    -
    -
    path : str
    -
    path to check for existence
    -
    -

    Returns

    -
    -
    bool
    -
    True if exists
    -
    -
    -Source code -
    def exists(path: str) -> bool:
    -    """Checks if path exists
    -
    -    Args:
    -        path (str): path to check for existence
    -
    -    Returns:
    -        bool: True if exists
    -    """
    -    return pathlib.Path(path).exists()
    -
    -
    -
    -def expanduser(path) -
    -
    -

    Expands the tilde ~ to username -e.g -j.sals.fs.expanduser("~/work") -> '/home/xmonader/work'

    -

    Args

    -
    -
    path : str
    -
    path with optionally ~
    -
    -

    Returns

    -
    -
    str
    -
    path with tilde ~ resolved.
    -
    -
    -Source code -
    def expanduser(path: str) -> str:
    -    """Expands the tilde `~` to username
    -    e.g
    -        j.sals.fs.expanduser("~/work") -> '/home/xmonader/work'
    -    Args:
    -        path (str): path with optionally `~`
    -
    -    Returns:
    -        str: path with tilde `~` resolved.
    -    """
    -    return str(pathlib.Path(path).expanduser())
    -
    -
    -
    -def ext(path, include_dot=True) -
    -
    -

    Gets the extension of path -'/home/ahmed/myfile.py' -> .py if include_dot else py

    -

    Args

    -
    -
    path : str
    -
    [description]
    -
    include_dot : bool, optional
    -
    controls whether to include the dot or not. Defaults to True.
    -
    -

    Returns

    -
    -
    str
    -
    extension
    -
    -
    -Source code -
    def extension(path: str, include_dot=True):
    -    """Gets the extension of path
    -    '/home/ahmed/myfile.py' -> `.py` if include_dot else `py`
    -
    -    Args:
    -        path (str): [description]
    -        include_dot (bool, optional): controls whether to include the dot or not. Defaults to True.
    -
    -    Returns:
    -        str: extension
    -    """
    -    splitted = os.path.splitext(path)
    -    ext = ""
    -    if len(splitted) == 1:
    -        return ext
    -
    -    if include_dot:
    -        return splitted[1]
    -    else:
    -        return splitted[1].strip(".")
    -
    -
    -
    -def extension(path, include_dot=True) -
    -
    -

    Gets the extension of path -'/home/ahmed/myfile.py' -> .py if include_dot else py

    -

    Args

    -
    -
    path : str
    -
    [description]
    -
    include_dot : bool, optional
    -
    controls whether to include the dot or not. Defaults to True.
    -
    -

    Returns

    -
    -
    str
    -
    extension
    -
    -
    -Source code -
    def extension(path: str, include_dot=True):
    -    """Gets the extension of path
    -    '/home/ahmed/myfile.py' -> `.py` if include_dot else `py`
    -
    -    Args:
    -        path (str): [description]
    -        include_dot (bool, optional): controls whether to include the dot or not. Defaults to True.
    -
    -    Returns:
    -        str: extension
    -    """
    -    splitted = os.path.splitext(path)
    -    ext = ""
    -    if len(splitted) == 1:
    -        return ext
    -
    -    if include_dot:
    -        return splitted[1]
    -    else:
    -        return splitted[1].strip(".")
    -
    -
    -
    -def get_temp_dirname(suffix=None, prefix=None, dir=None) -
    -
    -

    Get temp directory name

    -

    Args

    -
    -
    suffix : [type], optional
    -
    ending suffix. Defaults to None.
    -
    prefix : [type], optional
    -
    prefix . Defaults to None.
    -
    dir : [type], optional
    -
    where to create the directory. Defaults to None.
    -
    -

    Returns

    -
    -
    str
    -
    temp directory name.
    -
    -
    -Source code -
    def get_temp_dirname(suffix=None, prefix=None, dir=None) -> str:
    -    """Get temp directory name
    -
    -    Args:
    -        suffix ([type], optional): ending suffix. Defaults to None.
    -        prefix ([type], optional): prefix . Defaults to None.
    -        dir ([type], optional): where to create the directory. Defaults to None.
    -
    -
    -    Returns:
    -        str: temp directory name.
    -    """
    -    return tempfile.TemporaryDirectory(suffix, prefix, dir).name
    -
    -
    -
    -def get_temp_filename(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) -
    -
    -

    Get temp filename

    -

    Args

    -
    -
    mode : str, optional
    -
    [description]. Defaults to "w+b".
    -
    buffering : int, optional
    -
    buffering. Defaults to -1.
    -
    encoding : [type], optional
    -
    encoding . Defaults to None.
    -
    newline : [type], optional
    -
    Defaults to None.
    -
    suffix : [type], optional
    -
    ending suffix. Defaults to None.
    -
    prefix : [type], optional
    -
    prefix . Defaults to None.
    -
    dir : [type], optional
    -
    where to create the file. Defaults to None.
    -
    -

    Returns

    -

    [str]: temp filename

    -
    -Source code -
    def get_temp_filename(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) -> str:
    -    """Get temp filename
    -
    -    Args:
    -        mode (str, optional): [description]. Defaults to "w+b".
    -        buffering (int, optional): buffering. Defaults to -1.
    -        encoding ([type], optional): encoding . Defaults to None.
    -        newline ([type], optional):  Defaults to None.
    -        suffix ([type], optional): ending suffix. Defaults to None.
    -        prefix ([type], optional): prefix . Defaults to None.
    -        dir ([type], optional): where to create the file. Defaults to None.
    -
    -    Returns:
    -        [str]: temp filename
    -    """
    -    return tempfile.NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, dir).name
    -
    -
    -
    -def home() -
    -
    -
    -
    -Source code -
    def home():
    -    return str(pathlib.Path.home())
    -
    -
    -
    -def is_absolute(path) -
    -
    -

    Checks if path is absolute

    -

    Returns

    -
    -
    bool
    -
    True if absolute
    -
    -
    -Source code -
    def is_absolute(path: str) -> bool:
    -    """Checks if path is absolute
    -
    -    Returns:
    -        bool: True if absolute
    -    """
    -    return pathlib.Path(path).is_absolute()
    -
    -
    -
    -def is_ascii_file(path, checksize=4096) -
    -
    -

    Checks if file path is ascii

    -

    Args

    -
    -
    path : str
    -
    file path
    -
    checksize : int, optional
    -
    checksize. Defaults to 4096.
    -
    -

    Returns

    -
    -
    bool
    -
    True if ascii file
    -
    -
    -Source code -
    def is_ascii_file(path: str, checksize=4096) -> bool:
    -    """Checks if file `path` is ascii
    -
    -    Args:
    -        path (str): file path
    -        checksize (int, optional): checksize. Defaults to 4096.
    -
    -    Returns:
    -        bool: True if ascii file
    -    """
    -    # TODO: let's talk about checksize feature.
    -    try:
    -        with open(path, encoding="ascii") as f:
    -            f.read()
    -            return True
    -    except UnicodeDecodeError:
    -        return False
    -
    -
    -
    -def is_binary_file(path) -
    -
    -
    -
    -Source code -
    is_binary_file = lambda path: not is_ascii_file(path)
    -
    -
    - -
    -

    Checks if path is a broken symlink

    -

    Args

    -
    -
    path : str
    -
    path to check
    -
    clean : bool, optional
    -
    remove symlink if broken. Defaults to False.
    -
    -

    Raises

    -
    -
    NotImplementedError
    -
    [description]
    -
    -

    Returns

    -
    -
    bool
    -
    True if path is a broken symlink
    -
    -
    -Source code -
    def is_broken_link(path: str, clean=False) -> bool:
    -    """Checks if path is a broken symlink
    -
    -    Args:
    -        path (str): path to check
    -        clean (bool, optional): remove symlink if broken. Defaults to False.
    -
    -    Raises:
    -        NotImplementedError: [description]
    -
    -    Returns:
    -        bool: True if path is a broken symlink
    -    """
    -    raise NotImplementedError()
    -
    -
    -
    -def is_dir(path) -
    -
    -

    Checks if path is a dir

    -

    :param path: path to check -:type path: str -:return: True if is dir else False -:rtype: bool

    -
    -Source code -
    def is_dir(path: str) -> bool:
    -    """Checks if path is a dir
    -
    -    :param path: path to check
    -    :type path: str
    -    :return: True if is dir else False
    -    :rtype: bool
    -    """
    -    return pathlib.Path(path).is_dir()
    -
    -
    -
    -def is_empty_dir(path) -
    -
    -

    Checks if path is emptry directory

    -

    Args

    -
    -
    path : str
    -
    path to check if empty directory
    -
    -

    Returns

    -
    -
    bool
    -
    True if path is emptry directory
    -
    -
    -Source code -
    def is_empty_dir(path: str) -> bool:
    -    """Checks if path is emptry directory
    -
    -    Args:
    -        path (str): path to check if empty directory
    -
    -    Returns:
    -        bool: True if path is emptry directory
    -    """
    -
    -    try:
    -        g = pathlib.Path(path).iterdir()
    -        next(g)
    -    except StopIteration:
    -        # means we can't get next entry -> dir is empty.
    -        return True
    -    else:
    -        return False
    -
    -
    -
    -def is_file(path) -
    -
    -

    Checks if path is a file

    -

    Args

    -
    -
    path : str
    -
    path to check if is file
    -
    -

    Returns

    -
    -
    bool
    -
    True if is file and False otherwise
    -
    -
    -Source code -
    def is_file(path: str) -> bool:
    -    """Checks if path is a file
    -
    -    Args:
    -        path (str): path to check if is file
    -
    -    Returns:
    -        bool: True if is file and False otherwise
    -    """
    -    return pathlib.Path(path).is_file()
    -
    -
    -
    -def is_mount(path) -
    -
    -

    Checks if path is mount

    -

    Returns

    -
    -
    bool
    -
    True if mount
    -
    -
    -Source code -
    def is_mount(path: str) -> bool:
    -    """Checks if path is mount
    -
    -    Returns:
    -        bool: True if mount
    -    """
    -    return pathlib.Path(path).is_mount()
    -
    -
    - -
    -

    Checks if path symlink

    -

    Args

    -
    -
    path : str
    -
    path to check if symlink
    -
    -

    Returns

    -
    -
    bool
    -
    True if symlink False otherwise
    -
    -
    -Source code -
    def is_symlink(path: str) -> bool:
    -    """Checks if path symlink
    -
    -    Args:
    -        path (str): path to check if symlink
    -
    -    Returns:
    -        bool: True if symlink False otherwise
    -    """
    -    return pathlib.Path(path).is_symlink()
    -
    -
    -
    -def join_paths(*paths) -
    -
    -
    -
    -Source code -
    def join_paths(*paths):
    -    return parts_to_path(paths)
    -
    -
    -
    -def lchmod(path, mode) -
    -
    -

    change file mode for path to mode (handles links too)

    -

    Args

    -
    -
    path : str
    -
    path
    -
    mode : int
    -
    file mode
    -
    -
    -Source code -
    def lchmod(path: str, mode):
    -    """change file mode for path to mode (handles links too)
    -
    -    Args:
    -        path (str): path
    -        mode (int): file mode
    -
    -    """
    -    return pathlib.Path(path).lchmod(mode)
    -
    -
    -
    -def lstat(path) -
    -
    -

    Gets stat of path path (handles links)

    -

    Args

    -
    -
    path : str
    -
    path to get its stat
    -
    -

    Returns

    -
    -
    stat_result
    -
    returns stat struct.
    -
    -
    -Source code -
    def lstat(path: str):
    -    """Gets stat of path `path` (handles links)
    -
    -    Args:
    -        path (str): path to get its stat
    -
    -    Returns:
    -        stat_result: returns stat struct.
    -    """
    -
    -    return pathlib.Path(path).lstat()
    -
    -
    -
    -def mkdir(path, exist_ok=True) -
    -
    -

    Makes directory at path

    -

    Args

    -
    -
    path : str
    -
    path to create dir at
    -
    exist_ok : bool, optional
    -
    won't fail if directory exists. Defaults to True.
    -
    -

    Returns

    -
    -Source code -
    def mkdir(path: str, exist_ok=True):
    -    """Makes directory at path
    -
    -    Args:
    -        path (str): path to create dir at
    -        exist_ok (bool, optional): won't fail if directory exists. Defaults to True.
    -
    -    Returns:
    -        [type]: [description]
    -    """
    -    return pathlib.Path(path).mkdir(exist_ok=exist_ok)
    -
    -
    -
    -def mkdirs(path, exist_ok=True) -
    -
    -

    Creates dir as well as all non exisitng parents in the path

    -

    Args

    -
    -
    path : str
    -
    path to create dir at
    -
    exist_ok : bool, optional
    -
    won't fail if directory exists. Defaults to True.
    -
    -
    -Source code -
    def mkdirs(path: str, exist_ok=True):
    -    """Creates dir as well as all non exisitng parents in the path
    -
    -    Args:
    -        path (str): path to create dir at
    -        exist_ok (bool, optional): won't fail if directory exists. Defaults to True.
    -    """
    -    return os.makedirs(path, exist_ok=exist_ok)
    -
    -
    -
    -def parent(path) -
    -
    -

    Get path's parent

    -

    Args

    -
    -
    path : str
    -
    path to get its parent
    -
    -

    Returns

    -
    -
    str
    -
    parent path.
    -
    -
    -Source code -
    def parent(path: str) -> str:
    -    """Get path's parent
    -
    -    Args:
    -        path (str): path to get its parent
    -
    -    Returns:
    -        str: parent path.
    -    """
    -    return str(pathlib.Path(path).parent)
    -
    -
    -
    -def parents(path) -
    -
    -

    Get parents list

    -

    e.g

    -
    >>> j.sals.fs.parents("/tmp/home/ahmed/myfile.py")
    -[PosixPath('/tmp/home/ahmed'),
    -
    -

    PosixPath('/tmp/home'), -PosixPath('/tmp'), -PosixPath('/')]

    -

    Args

    -
    -
    path : str
    -
    path to get its parents
    -
    -

    Returns

    -
    -
    List[str]: list of parents()
    -
     
    -
    -
    -Source code -
    def parents(path: str) -> List[str]:
    -    """Get parents list
    -
    -    e.g
    -    >>> j.sals.fs.parents("/tmp/home/ahmed/myfile.py")
    -    [PosixPath('/tmp/home/ahmed'),
    -    PosixPath('/tmp/home'),
    -    PosixPath('/tmp'),
    -    PosixPath('/')]
    -
    -    Args:
    -        path (str): path to get its parents
    -
    -    Returns:
    -        List[str]: list of parents
    -    """
    -
    -    return list([str(p) for p in pathlib.Path(path).parents])
    -
    -
    -
    -def parts_to_path(parts) -
    -
    -

    Convert list of path parts into a path string

    -

    Args

    -
    -
    parts : List[str]
    -
    path parts
    -
    -

    Returns

    -
    -
    str
    -
    joined path parts
    -
    -
    -Source code -
    def parts_to_path(parts: List[str]) -> str:
    -    """Convert list of path parts into a path string
    -
    -    Args:
    -        parts (List[str]): path parts
    -
    -    Returns:
    -        str: joined path parts
    -    """
    -    path = pathlib.Path(parts[0])
    -    for p in parts[1:]:
    -        path = path.joinpath(p)
    -    return str(path)
    -
    -
    -
    -def path_parts(path) -
    -
    -

    Convert path to a list of parts -e.g -'/tmp/tmp-5383p1GOmMOOwvfi.tpl' -> -('/', 'tmp', 'tmp-5383p1GOmMOOwvfi.tpl')

    -

    Args

    -
    -
    path : str
    -
    path to convert to parts
    -
    -

    Returns

    -

    List[str]: path parts.

    -
    -Source code -
    def path_parts(path: str) -> List[str]:
    -    """Convert path to a list of parts
    -    e.g
    -     '/tmp/tmp-5383p1GOmMOOwvfi.tpl' ->  ('/', 'tmp', 'tmp-5383p1GOmMOOwvfi.tpl')
    -    Args:
    -        path (str): path to convert to parts
    -
    -    Returns:
    -        List[str]: path parts.
    -    """
    -    return pathlib.Path(path).parts
    -
    -
    -
    -def read_ascii(path) -
    -
    -

    read ascii content at path

    -

    Args

    -
    -
    path : str
    -
    ascii file path
    -
    -

    Returns

    -
    -
    str
    -
    ascii content in path
    -
    -
    -Source code -
    def read_text(path: str) -> str:
    -    """read ascii content at `path`
    -
    -    Args:
    -        path (str): ascii file path
    -
    -    Returns:
    -        str: ascii content in path
    -    """
    -    return pathlib.Path(path).read_text()
    -
    -
    -
    -def read_binary(path) -
    -
    -

    read binary content at path

    -

    Args

    -
    -
    path : str
    -
    binary file path
    -
    -

    Returns

    -
    -
    bytes
    -
    binary content in path
    -
    -
    -Source code -
    def read_bytes(path: str) -> bytes:
    -    """read binary content at `path`
    -
    -    Args:
    -        path (str): binary file path
    -
    -    Returns:
    -        bytes: binary content in path
    -    """
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -
    -def read_bytes(path) -
    -
    -

    read binary content at path

    -

    Args

    -
    -
    path : str
    -
    binary file path
    -
    -

    Returns

    -
    -
    bytes
    -
    binary content in path
    -
    -
    -Source code -
    def read_bytes(path: str) -> bytes:
    -    """read binary content at `path`
    -
    -    Args:
    -        path (str): binary file path
    -
    -    Returns:
    -        bytes: binary content in path
    -    """
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -
    -def read_file(path) -
    -
    -

    read ascii content at path

    -

    Args

    -
    -
    path : str
    -
    ascii file path
    -
    -

    Returns

    -
    -
    str
    -
    ascii content in path
    -
    -
    -Source code -
    def read_text(path: str) -> str:
    -    """read ascii content at `path`
    -
    -    Args:
    -        path (str): ascii file path
    -
    -    Returns:
    -        str: ascii content in path
    -    """
    -    return pathlib.Path(path).read_text()
    -
    -
    -
    -def read_file_binary(path) -
    -
    -

    read binary content at path

    -

    Args

    -
    -
    path : str
    -
    binary file path
    -
    -

    Returns

    -
    -
    bytes
    -
    binary content in path
    -
    -
    -Source code -
    def read_bytes(path: str) -> bytes:
    -    """read binary content at `path`
    -
    -    Args:
    -        path (str): binary file path
    -
    -    Returns:
    -        bytes: binary content in path
    -    """
    -    return pathlib.Path(path).read_bytes()
    -
    -
    - -
    -
    -
    -Source code -
    def read_link(path):
    -    raise NotImplementedError()
    -
    -
    -
    -def read_text(path) -
    -
    -

    read ascii content at path

    -

    Args

    -
    -
    path : str
    -
    ascii file path
    -
    -

    Returns

    -
    -
    str
    -
    ascii content in path
    -
    -
    -Source code -
    def read_text(path: str) -> str:
    -    """read ascii content at `path`
    -
    -    Args:
    -        path (str): ascii file path
    -
    -    Returns:
    -        str: ascii content in path
    -    """
    -    return pathlib.Path(path).read_text()
    -
    -
    - -
    -
    -
    -Source code -
    def remove_links(path):
    -    raise NotImplementedError()
    -
    -
    -
    -def rename(path1, path2) -
    -
    -

    Rename path1 to path2

    -

    Args

    -
    -
    path1 : str
    -
    source path
    -
    path2 : str
    -
    dest path
    -
    -
    -Source code -
    def rename(path1: str, path2: str):
    -    """Rename path1 to path2
    -
    -    Args:
    -        path1 (str): source path
    -        path2 (str): dest path
    -
    -    """
    -    return pathlib.Path(path1).rename(path2)
    -
    -
    -
    -def replace_words_in_files(from_, to, where) -
    -
    -
    -
    -Source code -
    def replace_words_in_files(from_, to, where):
    -    pass
    -
    -
    -
    -def resolve(path) -
    -
    -

    resolve . and .. in path

    -

    Args

    -
    -
    path : str
    -
    path with optionally . and ..
    -
    -

    Returns

    -
    -
    str
    -
    resolved path
    -
    -
    -Source code -
    def resolve(path: str) -> str:
    -    """resolve `.` and `..` in path
    -
    -    Args:
    -        path (str): path with optionally `.` and `..`
    -
    -    Returns:
    -        str: resolved path
    -    """
    -    return pathlib.Path(path).resolve()
    -
    -
    -
    -def rm_emptry_dir(path) -
    -
    -

    Remove empty directory

    -

    Args

    -
    -
    path : str
    -
    path to remove.
    -
    -
    -Source code -
    def rm_emptry_dir(path: str):
    -    """Remove empty directory
    -
    -    Args:
    -        path (str): path to remove.
    -    """
    -    path = pathlib.Path(path)
    -    path.rmdir()
    -
    -
    -
    -def rmtree(path) -
    -
    -

    Remove directory tree

    -

    Args

    -
    -
    path : str
    -
    path to remove
    -
    -
    -Source code -
    def rmtree(path: str):
    -    """Remove directory tree
    -    Args:
    -        path (str): path to remove
    -    """
    -    path = pathlib.Path(path)
    -    if path.is_file() or path.is_symlink():
    -        os.remove(path)
    -    elif path.is_dir():
    -        shutil.rmtree(path)
    -
    -
    -
    -def stat(path) -
    -
    -

    Gets stat of path path

    -

    Args

    -
    -
    path : str
    -
    path to get its stat
    -
    -

    Returns

    -
    -
    stat_result
    -
    returns stat struct.
    -
    -
    -Source code -
    def stat(path: str):
    -    """Gets stat of path `path`
    -
    -    Args:
    -        path (str): path to get its stat
    -
    -    Returns:
    -        stat_result: returns stat struct.
    -    """
    -
    -    return pathlib.Path(path).stat()
    -
    -
    -
    -def stem(path) -
    -
    -

    returns the stem of a path (path without parent directory and without extension) -e.g -In [2]: t = j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl")

    -
    In [3]: t
    -Out[3]: 'tmp-5383p1GOmMOOwvfi'
    -
    -

    Args

    -
    -
    path : str
    -
    path we want to get its stem
    -
    -

    Returns

    -
    -Source code -
    def stem(path: str) -> str:
    -    """returns the stem of a path (path without parent directory and without extension)
    -    e.g
    -        In [2]: t = j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl")
    -
    -        In [3]: t
    -        Out[3]: 'tmp-5383p1GOmMOOwvfi'
    -
    -    Args:
    -        path (str): path we want to get its stem
    -
    -    Returns:
    -        [type]: [description]
    -    """
    -    return pathlib.Path(path).stem
    -
    -
    - -
    -

    Create a symbolic link.

    -

    Args

    -
    -
    src : str
    -
    Source of link
    -
    dst : str
    -
    Destination path of link
    -
    overwrite : bool, optional
    -
    If link exists will delete it. Defaults to False.
    -
    -
    -Source code -
    def symlink(src: str, dst: str, overwrite=False):
    -    """Create a symbolic link.
    -
    -    Args:
    -        src (str): Source of link
    -        dst (str): Destination path of link
    -        overwrite (bool, optional): If link exists will delete it. Defaults to False.
    -    """
    -    if overwrite and exists(dst):
    -        os.unlink(dst)
    -
    -    os.symlink(src, dst)
    -
    -
    -
    -def touch(path) -
    -
    -

    create file

    -

    Args

    -
    -
    path : str
    -
    path to create file
    -
    -
    -Source code -
    def touch(path: str):
    -    """create file
    -
    -    Args:
    -        path (str): path to create file
    -
    -    """
    -    return pathlib.Path(path).touch()
    -
    -
    - -
    -

    unlink path

    -

    Args

    -
    -
    path : str
    -
    path to unlink
    -
    -
    -Source code -
    def unlink(path: str):
    -    """unlink path
    -
    -    Args:
    -        path (str): path to unlink
    -
    -
    -    """
    -    return pathlib.Path(path).unlink()
    -
    -
    -
    -def walk(path, pat='*', filter_fun=<function default_filter_fun>) -
    -
    -

    walk recursively on path -e.g -for el in walk('/tmp', filter_fun=j.sals.fs.is_file) : .. -for el in walk('/tmp', filter_fun=j.sals.fs.is_dir) : .. -for el in walk('/tmp', filter_fun= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..

    -

    Args

    -
    -
    path : str
    -
    path to walk over
    -
    pat : str, optional
    -
    pattern to match against. Defaults to "*".
    -
    filter_fun : Function, optional
    -
    filtering function. Defaults to default_filter_fun which accepts anything.
    -
    -
    -Source code -
    def walk(path: str, pat="*", filter_fun=default_filter_fun):
    -    """walk recursively on path
    -    e.g
    -        for el in walk('/tmp', filter_fun=j.sals.fs.is_file) : ..
    -        for el in walk('/tmp', filter_fun=j.sals.fs.is_dir) : ..
    -        for el in walk('/tmp', filter_fun= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        pat (str, optional): pattern to match against. Defaults to "*".
    -        filter_fun (Function, optional): filtering function. Defaults to default_filter_fun which accepts anything.
    -    """
    -    p = pathlib.Path(path)
    -    for entry in p.rglob(pat):
    -        # use rglob instead of glob("**/*")
    -        if filter_fun(entry):
    -            yield str(entry)
    -
    -
    -
    -def walk_dirs(path, recursive=True) -
    -
    -

    walk over directories in path and applies function fun -e.g

    -
    for el in walk_dirs('/tmp') : ..
    -
    -

    Args

    -
    -
    path : str
    -
    path to walk over
    -
    recursive : bool, optional
    -
    recursive or not. Defaults to True.
    -
    -
    -Source code -
    def walk_dirs(path, recursive=True):
    -    """
    -        walk over directories in path and applies function `fun`
    -    e.g
    -
    -        for el in walk_dirs('/tmp') : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        recursive (bool, optional): recursive or not. Defaults to True.
    -
    -
    -    """
    -    if recursive:
    -        return walk(path, filter_fun=is_dir)
    -    else:
    -        return walk_non_recursive(path, filter_fun=is_dir)
    -
    -
    -
    -def walk_files(path, recursive=True) -
    -
    -

    walk over files in path and applies function fun -e.g

    -
    for el in walk_files('/tmp') : ..
    -
    -

    Args

    -
    -
    path : str
    -
    path to walk over
    -
    recursive : bool, optional
    -
    recursive or not. Defaults to True.
    -
    -
    -Source code -
    def walk_files(path: str, recursive=True):
    -    """
    -    walk over files in path and applies function `fun`
    -    e.g
    -
    -        for el in walk_files('/tmp') : ..
    -
    -    Args:
    -        path (str): path to walk over
    -        recursive (bool, optional): recursive or not. Defaults to True.
    -
    -
    -    """
    -
    -    if recursive:
    -        return walk(path, filter_fun=is_file)
    -    else:
    -        return walk_non_recursive(path, filter_fun=is_file)
    -
    -
    -
    -def walk_non_recursive(path, filter_fun=<function default_filter_fun>) -
    -
    -

    walks non recursively on path -e.g -for el in walk('/tmp', filter=j.sals.fs.is_file) : .. -for el in walk('/tmp', filter=j.sals.fs.is_dir) : .. -for el in walk('/tmp', filter= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..

    -

    Args

    -
    -
    path : str
    -
    path to walk over
    -
    pat : str, optional
    -
    pattern to match against. Defaults to "*".
    -
    filter_fun : Function, optional
    -
    filtering function. Defaults to default_filter_fun which accepts anything.
    -
    -
    -Source code -
    def walk_non_recursive(path: str, filter_fun=default_filter_fun):
    -    """walks non recursively on path
    -    e.g
    -        for el in walk('/tmp', filter=j.sals.fs.is_file) : ..
    -        for el in walk('/tmp', filter=j.sals.fs.is_dir) : ..
    -        for el in walk('/tmp', filter= lambda x: len(x)>4 and (j.sals.fs.is_file(x) or j.sals.fs.is_dir(x)) ) : ..
    -
    -
    -    Args:
    -        path (str): path to walk over
    -        pat (str, optional): pattern to match against. Defaults to "*".
    -        filter_fun (Function, optional): filtering function. Defaults to default_filter_fun which accepts anything.
    -    """
    -    p = pathlib.Path(path)
    -    for entry in p.iterdir():
    -        if filter_fun(entry):
    -            yield str(entry)
    -
    -
    -
    -def write_ascii(path, data, encoding=None) -
    -
    -

    write text data to path path with encoding

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : str
    -
    ascii content
    -
    encoding : [type], optional
    -
    encoding. Defaults to None.
    -
    -
    -Source code -
    def write_text(path: str, data: str, encoding=None):
    -    """write text `data` to path `path` with encoding
    -
    -    Args:
    -        path (str): path to write to
    -        data (str): ascii content
    -        encoding ([type], optional): encoding. Defaults to None.
    -
    -
    -    """
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -def write_binary(path, data) -
    -
    -

    write binary data to path path

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : bytes
    -
    binary content
    -
    -
    -Source code -
    def write_bytes(path: str, data: bytes):
    -    """write binary `data` to path `path`
    -
    -    Args:
    -        path (str): path to write to
    -        data (bytes): binary content
    -
    -    """
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_bytes(path, data) -
    -
    -

    write binary data to path path

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : bytes
    -
    binary content
    -
    -
    -Source code -
    def write_bytes(path: str, data: bytes):
    -    """write binary `data` to path `path`
    -
    -    Args:
    -        path (str): path to write to
    -        data (bytes): binary content
    -
    -    """
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_file(path, data, encoding=None) -
    -
    -

    write text data to path path with encoding

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : str
    -
    ascii content
    -
    encoding : [type], optional
    -
    encoding. Defaults to None.
    -
    -
    -Source code -
    def write_text(path: str, data: str, encoding=None):
    -    """write text `data` to path `path` with encoding
    -
    -    Args:
    -        path (str): path to write to
    -        data (str): ascii content
    -        encoding ([type], optional): encoding. Defaults to None.
    -
    -
    -    """
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -def write_file_binary(path, data) -
    -
    -

    write binary data to path path

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : bytes
    -
    binary content
    -
    -
    -Source code -
    def write_bytes(path: str, data: bytes):
    -    """write binary `data` to path `path`
    -
    -    Args:
    -        path (str): path to write to
    -        data (bytes): binary content
    -
    -    """
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_text(path, data, encoding=None) -
    -
    -

    write text data to path path with encoding

    -

    Args

    -
    -
    path : str
    -
    path to write to
    -
    data : str
    -
    ascii content
    -
    encoding : [type], optional
    -
    encoding. Defaults to None.
    -
    -
    -Source code -
    def write_text(path: str, data: str, encoding=None):
    -    """write text `data` to path `path` with encoding
    -
    -    Args:
    -        path (str): path to write to
    -        data (str): ascii content
    -        encoding ([type], optional): encoding. Defaults to None.
    -
    -
    -    """
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/sals/fs/fs2.html b/docs/api/jumpscale/sals/fs/fs2.html deleted file mode 100644 index dc307ae5c..000000000 --- a/docs/api/jumpscale/sals/fs/fs2.html +++ /dev/null @@ -1,1030 +0,0 @@ - - - - - - -jumpscale.sals.fs.fs2 API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.sals.fs.fs2

    -
    -
    -
    -Source code -
    import pathlib
    -import tempfile
    -import os
    -import shutil
    -import stat
    -from distutils import dir_util
    -
    -def home():
    -    return str(pathlib.Path.home())
    -
    -
    -def cwd():
    -    return str(pathlib.Path.cwd())
    -
    -
    -basename = os.path.basename
    -dirname = os.path.dirname
    -common_path = os.path.commonpath
    -common_prefix = os.path.commonprefix
    -norm_path = os.path.normpath
    -norm_case = os.path.normcase
    -get_access_time = os.path.getatime
    -get_modified_time = os.path.getmtime
    -get_creation_time = os.path.getctime
    -sep = os.path.sep
    -is_samefile = os.path.samefile
    -expandvars = os.path.expandvars
    -expanduser = os.path.expanduser
    -
    -def is_dir(path):
    -    return pathlib.Path(path).is_dir()
    -
    -def is_file(path):
    -    return pathlib.Path(path).is_file()
    -
    -
    -def is_symlink(path):
    -    return pathlib.Path(path).is_symlink()
    -
    -
    -def is_absolute(path):
    -    return pathlib.Path(path).is_absolute()
    -
    -
    -def is_mount(path):
    -    return pathlib.Path(path).is_mount()
    -
    -
    -def is_ascii_file(filename, checksize=4096):
    -    # TODO: let's talk about checksize feature.
    -    try:
    -        with open(filename, encoding="ascii") as f:
    -            f.read()
    -            return True
    -    except UnicodeDecodeError:
    -        return False
    -
    -
    -def is_empty_dir(path):
    -    try:
    -        g = pathlib.Path(path).iterdir()
    -        next(g)
    -    except StopIteration:
    -        # means we can't get next entry -> dir is empty.
    -        return True
    -    else:
    -        return False
    -
    -
    -is_binary_file = lambda path: not is_ascii_file(path)
    -
    -
    -def is_broken_link(path, clean=False):
    -    raise NotImplementedError()
    -
    -
    -def stem(path):
    -    return pathlib.Path(path).stem
    -
    -
    -def mkdir(path, exist_ok=True):
    -    return pathlib.Path(path).mkdir(exist_ok=exist_ok)
    -
    -
    -def parent(path):
    -    return pathlib.Path(path).parent
    -
    -
    -def parents(path):
    -    """
    -    [PosixPath('/tmp/home/ahmed'),
    -    PosixPath('/tmp/home'),
    -    PosixPath('/tmp'),
    -    PosixPath('/')]
    -    """
    -    return list(pathlib.Path(path).parnets)
    -
    -
    -def path_parts(path):
    -    return pathlib.Path(path).parts
    -
    -
    -def exists(path):
    -    return pathlib.Path(path).exists()
    -
    -
    -def rename(path1, path2):
    -    return pathlib.Path(path1).rename(path2)
    -
    -
    -def expanduser(path):
    -    return pathlib.Path(path).expanduser()
    -
    -
    -def unlink(path):
    -    return pathlib.Path(path).unlink()
    -
    -
    -def read_text(path):
    -    return pathlib.Path(path).read_text()
    -
    -
    -read_ascii = read_file = read_text
    -
    -
    -def read_bytes(path):
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -read_binary = read_file_binary = read_bytes
    -
    -
    -def write_text(path, data, encoding=None):
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -write_ascii = write_file = write_text
    -
    -
    -def write_bytes(path, data):
    -    return pathlib.Path(path).write_bytes(data)
    -
    -write_binary = write_file_binary = write_bytes
    -
    -def touch(path):
    -    return pathlib.Path(path).touch()
    -
    -
    -def get_temp_filename(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None):
    -    return tempfile.NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, dir).name
    -
    -
    -def get_temp_dirname(suffix=None, prefix=None, dir=None):
    -    return tempfile.TemporaryDirectory(suffix, prefix, dir).name
    -
    -
    -NamedTemporaryFile = tempfile.NamedTemporaryFile
    -TempraryDirectory = tempfile.TemporaryDirectory
    -mkdtemp = tempfile.mkdtemp
    -mkstemp = tempfile.mkstemp
    -get_temp_dir = tempfile.gettempdir
    -
    -def parts_to_path(parts):
    -    path = pathlib.Path(parts[0])
    -    for p in parts[1:]:
    -        path.joinpath(p)
    -
    -def rm_emptry_dir(path):
    -    path = pathlib.Path(path)
    -    path.rmdir()
    -
    -
    -def rmtree(path):
    -    path = pathlib.Path(path)
    -    if path.is_file() or path.is_link():
    -        os.remove(path)
    -    elif path.is_dir():
    -        shutil.rmtree(path)
    -    if not parents:
    -        return
    -    p = path.parent
    -    while p:
    -        try:
    -            os.rmdir(p)
    -        except os.error:
    -            break
    -        p = p.parent
    -
    -
    -def copy_stat(src, dst, times=True, perms=True):
    -    st = os.stat(src)
    -    if hasattr(os, 'utime'):
    -        os.utime(dst, (st.st_atime, st.st_mtime))
    -    if hasattr(os, 'chmod'):
    -        m = stat.S_IMODE(st.st_mode)
    -        os.chmod(dst, m)
    -
    -def copy_file(src, dst, times=False, perms=False):
    -    """Copy the file, optionally copying the permission bits (mode) and
    -        last access/modify time. If the destination file exists, it will be
    -        replaced. Raises OSError if the destination is a directory. If the
    -        platform does not have the ability to set the permission or times,
    -        ignore it.
    -        This is shutil.copyfile plus bits of shutil.copymode and
    -        shutil.copystat's implementation.
    -        shutil.copy and shutil.copy2 are not supported but are easy to do.
    -    """
    -    shutil.copyfile(src, dst)
    -    if times or perms:
    -        copy_stat(src, dst, times, perms)
    -
    -def copy_stat(src, dst, times=True, perms=True):
    -    st = os.stat(src)
    -    if hasattr(os, 'utime'):
    -        os.utime(dst, (st.st_atime, st.st_mtime))
    -    if hasattr(os, 'chmod'):
    -        m = stat.S_IMODE(st.st_mode)
    -        os.chmod(dst, m)
    -
    -copy_tree = dir_util.copy_tree
    -chdir = os.chdir
    -
    -def change_dir(to):
    -    os.chdir(path)
    -    return cwd()
    -
    -
    -def chmod(path, mode):
    -    return pathlib.Path(path).chmod(mode)
    -
    -def lchmod(path, mode):
    -    return pathlib.Path(path).lchmod(mode)
    -
    -
    -def stat(path):
    -    return pathlib.Path(path).stat()
    -
    -
    -def lstat(path):
    -    return pathlib.Path(path).lstat()
    -
    -
    -def resolve(path):
    -    return pathlib.Path(path).resolve()
    -
    -
    -def extension(path, include_dot=True):
    -    splitted = os.path.splitext(path)
    -    ext = ""
    -    if len(splitted) == 1:
    -        return ext
    -
    -    if include_dot:
    -        return splitted[1]
    -    else:
    -        return splitted[1].strip(".")
    -
    -def chown():
    -    raise NotImplementedError()
    -
    -def read_link(path):
    -    raise NotImplementedError()
    -
    -def remove_links(path):
    -    raise NotImplementedError()
    -
    -
    -def change_filenames(from_, to, where):
    -    pass
    -
    -def replace_words_in_files(from_, to, where):
    -    pass
    -
    -move = shutil.move
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def change_dir(to) -
    -
    -
    -
    -Source code -
    def change_dir(to):
    -    os.chdir(path)
    -    return cwd()
    -
    -
    -
    -def change_filenames(from_, to, where) -
    -
    -
    -
    -Source code -
    def change_filenames(from_, to, where):
    -    pass
    -
    -
    -
    -def chmod(path, mode) -
    -
    -
    -
    -Source code -
    def chmod(path, mode):
    -    return pathlib.Path(path).chmod(mode)
    -
    -
    -
    -def chown() -
    -
    -
    -
    -Source code -
    def chown():
    -    raise NotImplementedError()
    -
    -
    -
    -def copy_file(src, dst, times=False, perms=False) -
    -
    -

    Copy the file, optionally copying the permission bits (mode) and -last access/modify time. If the destination file exists, it will be -replaced. Raises OSError if the destination is a directory. If the -platform does not have the ability to set the permission or times, -ignore it. -This is shutil.copyfile plus bits of shutil.copymode and -shutil.copystat's implementation. -shutil.copy and shutil.copy2 are not supported but are easy to do.

    -
    -Source code -
    def copy_file(src, dst, times=False, perms=False):
    -    """Copy the file, optionally copying the permission bits (mode) and
    -        last access/modify time. If the destination file exists, it will be
    -        replaced. Raises OSError if the destination is a directory. If the
    -        platform does not have the ability to set the permission or times,
    -        ignore it.
    -        This is shutil.copyfile plus bits of shutil.copymode and
    -        shutil.copystat's implementation.
    -        shutil.copy and shutil.copy2 are not supported but are easy to do.
    -    """
    -    shutil.copyfile(src, dst)
    -    if times or perms:
    -        copy_stat(src, dst, times, perms)
    -
    -
    -
    -def copy_stat(src, dst, times=True, perms=True) -
    -
    -
    -
    -Source code -
    def copy_stat(src, dst, times=True, perms=True):
    -    st = os.stat(src)
    -    if hasattr(os, 'utime'):
    -        os.utime(dst, (st.st_atime, st.st_mtime))
    -    if hasattr(os, 'chmod'):
    -        m = stat.S_IMODE(st.st_mode)
    -        os.chmod(dst, m)
    -
    -
    -
    -def cwd() -
    -
    -
    -
    -Source code -
    def cwd():
    -    return str(pathlib.Path.cwd())
    -
    -
    -
    -def exists(path) -
    -
    -
    -
    -Source code -
    def exists(path):
    -    return pathlib.Path(path).exists()
    -
    -
    -
    -def expanduser(path) -
    -
    -
    -
    -Source code -
    def expanduser(path):
    -    return pathlib.Path(path).expanduser()
    -
    -
    -
    -def extension(path, include_dot=True) -
    -
    -
    -
    -Source code -
    def extension(path, include_dot=True):
    -    splitted = os.path.splitext(path)
    -    ext = ""
    -    if len(splitted) == 1:
    -        return ext
    -
    -    if include_dot:
    -        return splitted[1]
    -    else:
    -        return splitted[1].strip(".")
    -
    -
    -
    -def get_temp_dirname(suffix=None, prefix=None, dir=None) -
    -
    -
    -
    -Source code -
    def get_temp_dirname(suffix=None, prefix=None, dir=None):
    -    return tempfile.TemporaryDirectory(suffix, prefix, dir).name
    -
    -
    -
    -def get_temp_filename(mode='w+b', buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None) -
    -
    -
    -
    -Source code -
    def get_temp_filename(mode="w+b", buffering=-1, encoding=None, newline=None, suffix=None, prefix=None, dir=None):
    -    return tempfile.NamedTemporaryFile(mode, buffering, encoding, newline, suffix, prefix, dir).name
    -
    -
    -
    -def home() -
    -
    -
    -
    -Source code -
    def home():
    -    return str(pathlib.Path.home())
    -
    -
    -
    -def is_absolute(path) -
    -
    -
    -
    -Source code -
    def is_absolute(path):
    -    return pathlib.Path(path).is_absolute()
    -
    -
    -
    -def is_ascii_file(filename, checksize=4096) -
    -
    -
    -
    -Source code -
    def is_ascii_file(filename, checksize=4096):
    -    # TODO: let's talk about checksize feature.
    -    try:
    -        with open(filename, encoding="ascii") as f:
    -            f.read()
    -            return True
    -    except UnicodeDecodeError:
    -        return False
    -
    -
    -
    -def is_binary_file(path) -
    -
    -
    -
    -Source code -
    is_binary_file = lambda path: not is_ascii_file(path)
    -
    -
    - -
    -
    -
    -Source code -
    def is_broken_link(path, clean=False):
    -    raise NotImplementedError()
    -
    -
    -
    -def is_dir(path) -
    -
    -
    -
    -Source code -
    def is_dir(path):
    -    return pathlib.Path(path).is_dir()
    -
    -
    -
    -def is_empty_dir(path) -
    -
    -
    -
    -Source code -
    def is_empty_dir(path):
    -    try:
    -        g = pathlib.Path(path).iterdir()
    -        next(g)
    -    except StopIteration:
    -        # means we can't get next entry -> dir is empty.
    -        return True
    -    else:
    -        return False
    -
    -
    -
    -def is_file(path) -
    -
    -
    -
    -Source code -
    def is_file(path):
    -    return pathlib.Path(path).is_file()
    -
    -
    -
    -def is_mount(path) -
    -
    -
    -
    -Source code -
    def is_mount(path):
    -    return pathlib.Path(path).is_mount()
    -
    -
    - -
    -
    -
    -Source code -
    def is_symlink(path):
    -    return pathlib.Path(path).is_symlink()
    -
    -
    -
    -def lchmod(path, mode) -
    -
    -
    -
    -Source code -
    def lchmod(path, mode):
    -    return pathlib.Path(path).lchmod(mode)
    -
    -
    -
    -def lstat(path) -
    -
    -
    -
    -Source code -
    def lstat(path):
    -    return pathlib.Path(path).lstat()
    -
    -
    -
    -def mkdir(path, exist_ok=True) -
    -
    -
    -
    -Source code -
    def mkdir(path, exist_ok=True):
    -    return pathlib.Path(path).mkdir(exist_ok=exist_ok)
    -
    -
    -
    -def parent(path) -
    -
    -
    -
    -Source code -
    def parent(path):
    -    return pathlib.Path(path).parent
    -
    -
    -
    -def parents(path) -
    -
    -

    [PosixPath('/tmp/home/ahmed'), -PosixPath('/tmp/home'), -PosixPath('/tmp'), -PosixPath('/')]

    -
    -Source code -
    def parents(path):
    -    """
    -    [PosixPath('/tmp/home/ahmed'),
    -    PosixPath('/tmp/home'),
    -    PosixPath('/tmp'),
    -    PosixPath('/')]
    -    """
    -    return list(pathlib.Path(path).parnets)
    -
    -
    -
    -def parts_to_path(parts) -
    -
    -
    -
    -Source code -
    def parts_to_path(parts):
    -    path = pathlib.Path(parts[0])
    -    for p in parts[1:]:
    -        path.joinpath(p)
    -
    -
    -
    -def path_parts(path) -
    -
    -
    -
    -Source code -
    def path_parts(path):
    -    return pathlib.Path(path).parts
    -
    -
    -
    -def read_ascii(path) -
    -
    -
    -
    -Source code -
    def read_text(path):
    -    return pathlib.Path(path).read_text()
    -
    -
    -
    -def read_binary(path) -
    -
    -
    -
    -Source code -
    def read_bytes(path):
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -
    -def read_bytes(path) -
    -
    -
    -
    -Source code -
    def read_bytes(path):
    -    return pathlib.Path(path).read_bytes()
    -
    -
    -
    -def read_file(path) -
    -
    -
    -
    -Source code -
    def read_text(path):
    -    return pathlib.Path(path).read_text()
    -
    -
    -
    -def read_file_binary(path) -
    -
    -
    -
    -Source code -
    def read_bytes(path):
    -    return pathlib.Path(path).read_bytes()
    -
    -
    - -
    -
    -
    -Source code -
    def read_link(path):
    -    raise NotImplementedError()
    -
    -
    -
    -def read_text(path) -
    -
    -
    -
    -Source code -
    def read_text(path):
    -    return pathlib.Path(path).read_text()
    -
    -
    - -
    -
    -
    -Source code -
    def remove_links(path):
    -    raise NotImplementedError()
    -
    -
    -
    -def rename(path1, path2) -
    -
    -
    -
    -Source code -
    def rename(path1, path2):
    -    return pathlib.Path(path1).rename(path2)
    -
    -
    -
    -def replace_words_in_files(from_, to, where) -
    -
    -
    -
    -Source code -
    def replace_words_in_files(from_, to, where):
    -    pass
    -
    -
    -
    -def resolve(path) -
    -
    -
    -
    -Source code -
    def resolve(path):
    -    return pathlib.Path(path).resolve()
    -
    -
    -
    -def rm_emptry_dir(path) -
    -
    -
    -
    -Source code -
    def rm_emptry_dir(path):
    -    path = pathlib.Path(path)
    -    path.rmdir()
    -
    -
    -
    -def rmtree(path) -
    -
    -
    -
    -Source code -
    def rmtree(path):
    -    path = pathlib.Path(path)
    -    if path.is_file() or path.is_link():
    -        os.remove(path)
    -    elif path.is_dir():
    -        shutil.rmtree(path)
    -    if not parents:
    -        return
    -    p = path.parent
    -    while p:
    -        try:
    -            os.rmdir(p)
    -        except os.error:
    -            break
    -        p = p.parent
    -
    -
    -
    -def stat(path) -
    -
    -
    -
    -Source code -
    def stat(path):
    -    return pathlib.Path(path).stat()
    -
    -
    -
    -def stem(path) -
    -
    -
    -
    -Source code -
    def stem(path):
    -    return pathlib.Path(path).stem
    -
    -
    -
    -def touch(path) -
    -
    -
    -
    -Source code -
    def touch(path):
    -    return pathlib.Path(path).touch()
    -
    -
    - -
    -
    -
    -Source code -
    def unlink(path):
    -    return pathlib.Path(path).unlink()
    -
    -
    -
    -def write_ascii(path, data, encoding=None) -
    -
    -
    -
    -Source code -
    def write_text(path, data, encoding=None):
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -def write_binary(path, data) -
    -
    -
    -
    -Source code -
    def write_bytes(path, data):
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_bytes(path, data) -
    -
    -
    -
    -Source code -
    def write_bytes(path, data):
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_file(path, data, encoding=None) -
    -
    -
    -
    -Source code -
    def write_text(path, data, encoding=None):
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -def write_file_binary(path, data) -
    -
    -
    -
    -Source code -
    def write_bytes(path, data):
    -    return pathlib.Path(path).write_bytes(data)
    -
    -
    -
    -def write_text(path, data, encoding=None) -
    -
    -
    -
    -Source code -
    def write_text(path, data, encoding=None):
    -    return pathlib.Path(path).write_text(data, encoding)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/sals/hostsfile/hostsfile.html b/docs/api/jumpscale/sals/hostsfile/hostsfile.html deleted file mode 100644 index f802177b8..000000000 --- a/docs/api/jumpscale/sals/hostsfile/hostsfile.html +++ /dev/null @@ -1,363 +0,0 @@ - - - - - - -jumpscale.sals.hostsfile.hostsfile API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.sals.hostsfile.hostsfile

    -
    -
    -
    -Source code -
    import re
    -
    -
    -class HostsFile:
    -    def __init__(self, hosts_file_path):
    -        self.path = hosts_file_path
    -        self.content = self._parse()
    -
    -    def _parse(self):
    -        with open(self.path, "r") as file:
    -            content_text = file.read()
    -        content_lines = content_text.splitlines()
    -        ip_lines = []
    -        regex = r"""\d+\.\d+\.\d+\.\d+"""
    -        for line in content_lines:
    -            if re.search(regex, line):
    -                ip_lines.append(line)
    -        content_dict = {}
    -        for line in ip_lines:
    -            key, value = line.split("\t")[0], line.split("\t")[1]
    -            content_dict[key] = value
    -        return content_dict
    -
    -    def write(self):
    -        """
    -        write the changes into the file.
    -        """
    -        content_text = ""
    -        for key, value in self.content.items():
    -            content_text += f"\n{key}\t{value}"
    -        with open(self.path, "w") as file:
    -            file.write(content_text)
    -
    -    def remove(self, ip):
    -        """
    -        remove the ip and its hostname from hosts file
    -        Args:
    -            ip (str) : the ip address
    -        """
    -        del self.content[ip]
    -
    -    def add(self, ip, domain):
    -        """
    -        add new entry to the hosts file
    -        Args:
    -            ip (str) : the ip address
    -            domain (str) : the host name
    -        """
    -        self.content[ip] = domain
    -
    -    def set_hostname(self, ip, domain):
    -        """
    -        update the hostname for ip
    -        Args:
    -            ip (str) : the ip address
    -            domain (str) : the host name           
    -        """
    -        self.content[ip] = domain
    -
    -    def exists(self, ip):
    -        """
    -        check for the existence of the ip in hosts file.
    -        Args:
    -            ip (str) : the ip address
    -        Return:
    -            boolen expression
    -        """
    -        return ip in self.content
    -
    -    def get_hostname(self, ip):
    -        """
    -        get the hostname for ip
    -        Args:
    -            ip (str) : the ip address
    -        Returns:
    -            the hostname for the ip address
    -        """
    -        return self.content[ip]
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class HostsFile -(hosts_file_path) -
    -
    -
    -
    -Source code -
    class HostsFile:
    -    def __init__(self, hosts_file_path):
    -        self.path = hosts_file_path
    -        self.content = self._parse()
    -
    -    def _parse(self):
    -        with open(self.path, "r") as file:
    -            content_text = file.read()
    -        content_lines = content_text.splitlines()
    -        ip_lines = []
    -        regex = r"""\d+\.\d+\.\d+\.\d+"""
    -        for line in content_lines:
    -            if re.search(regex, line):
    -                ip_lines.append(line)
    -        content_dict = {}
    -        for line in ip_lines:
    -            key, value = line.split("\t")[0], line.split("\t")[1]
    -            content_dict[key] = value
    -        return content_dict
    -
    -    def write(self):
    -        """
    -        write the changes into the file.
    -        """
    -        content_text = ""
    -        for key, value in self.content.items():
    -            content_text += f"\n{key}\t{value}"
    -        with open(self.path, "w") as file:
    -            file.write(content_text)
    -
    -    def remove(self, ip):
    -        """
    -        remove the ip and its hostname from hosts file
    -        Args:
    -            ip (str) : the ip address
    -        """
    -        del self.content[ip]
    -
    -    def add(self, ip, domain):
    -        """
    -        add new entry to the hosts file
    -        Args:
    -            ip (str) : the ip address
    -            domain (str) : the host name
    -        """
    -        self.content[ip] = domain
    -
    -    def set_hostname(self, ip, domain):
    -        """
    -        update the hostname for ip
    -        Args:
    -            ip (str) : the ip address
    -            domain (str) : the host name           
    -        """
    -        self.content[ip] = domain
    -
    -    def exists(self, ip):
    -        """
    -        check for the existence of the ip in hosts file.
    -        Args:
    -            ip (str) : the ip address
    -        Return:
    -            boolen expression
    -        """
    -        return ip in self.content
    -
    -    def get_hostname(self, ip):
    -        """
    -        get the hostname for ip
    -        Args:
    -            ip (str) : the ip address
    -        Returns:
    -            the hostname for the ip address
    -        """
    -        return self.content[ip]
    -
    -

    Methods

    -
    -
    -def add(self, ip, domain) -
    -
    -

    add new entry to the hosts file

    -

    Args

    -

    ip (str) : the ip address -domain (str) : the host name

    -
    -Source code -
    def add(self, ip, domain):
    -    """
    -    add new entry to the hosts file
    -    Args:
    -        ip (str) : the ip address
    -        domain (str) : the host name
    -    """
    -    self.content[ip] = domain
    -
    -
    -
    -def exists(self, ip) -
    -
    -

    check for the existence of the ip in hosts file.

    -

    Args

    -

    ip (str) : the ip address

    -

    Return

    -

    boolen expression

    -
    -Source code -
    def exists(self, ip):
    -    """
    -    check for the existence of the ip in hosts file.
    -    Args:
    -        ip (str) : the ip address
    -    Return:
    -        boolen expression
    -    """
    -    return ip in self.content
    -
    -
    -
    -def get_hostname(self, ip) -
    -
    -

    get the hostname for ip

    -

    Args

    -

    ip (str) : the ip address

    -

    Returns

    -
    -
    the hostname for the ip address
    -
     
    -
    -
    -Source code -
    def get_hostname(self, ip):
    -    """
    -    get the hostname for ip
    -    Args:
    -        ip (str) : the ip address
    -    Returns:
    -        the hostname for the ip address
    -    """
    -    return self.content[ip]
    -
    -
    -
    -def remove(self, ip) -
    -
    -

    remove the ip and its hostname from hosts file

    -

    Args

    -

    ip (str) : the ip address

    -
    -Source code -
    def remove(self, ip):
    -    """
    -    remove the ip and its hostname from hosts file
    -    Args:
    -        ip (str) : the ip address
    -    """
    -    del self.content[ip]
    -
    -
    -
    -def set_hostname(self, ip, domain) -
    -
    -

    update the hostname for ip

    -

    Args

    -

    ip (str) : the ip address -domain (str) : the host name

    -
    -Source code -
    def set_hostname(self, ip, domain):
    -    """
    -    update the hostname for ip
    -    Args:
    -        ip (str) : the ip address
    -        domain (str) : the host name           
    -    """
    -    self.content[ip] = domain
    -
    -
    -
    -def write(self) -
    -
    -

    write the changes into the file.

    -
    -Source code -
    def write(self):
    -    """
    -    write the changes into the file.
    -    """
    -    content_text = ""
    -    for key, value in self.content.items():
    -        content_text += f"\n{key}\t{value}"
    -    with open(self.path, "w") as file:
    -        file.write(content_text)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/sals/process/process.html b/docs/api/jumpscale/sals/process/process.html deleted file mode 100644 index 721e4327b..000000000 --- a/docs/api/jumpscale/sals/process/process.html +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - -jumpscale.sals.process.process API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.sals.process.process

    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/baseactor.html b/docs/api/jumpscale/servers/gedis/baseactor.html deleted file mode 100644 index 7bce6c2a5..000000000 --- a/docs/api/jumpscale/servers/gedis/baseactor.html +++ /dev/null @@ -1,333 +0,0 @@ - - - - - - -jumpscale.servers.gedis.baseactor API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis.baseactor

    -
    -
    -
    -Source code -
    import inspect
    -import sys
    -from functools import wraps
    -from jumpscale.loader import j
    -
    -
    -def actor_method(func):
    -    @wraps(func)
    -    def wrapper(*args, **kwargs):
    -        # verify args and kwargs types
    -        signature = inspect.signature(func)
    -        try:
    -            bound = signature.bind(*args, **kwargs)
    -        except TypeError as e:
    -            raise j.exceptions.Value(str(e))
    -
    -        for name, value in bound.arguments.items():
    -            annotation = signature.parameters[name].annotation
    -            if annotation not in (None, inspect._empty) and not isinstance(value, annotation):
    -                raise j.exceptions.Value(
    -                    f"parameter ({name}) supposed to be of type ({annotation.__name__}), but found ({type(value).__name__})"
    -                )
    -
    -        # call method
    -        result = func(*bound.args, **bound.kwargs)
    -        # verify result type
    -        return_type = signature.return_annotation
    -        if return_type is inspect._empty or return_type is None:
    -            return_type = type(None)
    -
    -        if not isinstance(result, return_type):
    -            raise j.exceptions.Value(f"method is supposed to return ({return_type}), but it returned ({type(result)})")
    -
    -        return result
    -
    -    return wrapper
    -
    -
    -class BaseActor:
    -    def __init__(self):
    -        self.path = None
    -
    -    @actor_method
    -    def info(self) -> dict:
    -        info = {}
    -        info["path"] = self.path
    -        info["methods"] = {}
    -
    -        methods = inspect.getmembers(self, predicate=inspect.ismethod)
    -        for name, attr in methods:
    -            if name.startswith("_"):
    -                continue
    -
    -            signature = inspect.signature(attr)
    -            info["methods"][name] = {}
    -            info["methods"][name]["args"] = []
    -            info["methods"][name]["doc"] = attr.__doc__ or ""
    -
    -            for parameter_name, parameter in signature.parameters.items():
    -                info["methods"][name]["args"].append((parameter_name, parameter.annotation.__name__))
    -
    -        return info
    -
    -    def __validate_actor__(self):
    -        def validate_annotation(annotation, annotated):
    -            if annotation is None or annotation is inspect._empty:
    -                return
    -
    -            if not (inspect.isclass(annotation) and annotation.__class__ == type):
    -                raise ValueError("annotation must be a class type")
    -
    -            if annotation not in (str, int, float, list, tuple, dict, bool):
    -                if annotation.__module__ == "builtins":
    -                    raise ValueError(f"unsupported type ({annotation.__name__})")
    -
    -                for method in ["to_dict", "from_dict"]:
    -                    if method not in dir(annotation):
    -                        raise ValueError(
    -                            f"type ({annotation.__name__}) which annotate {annotated} doesn't have {method} method"
    -                        )
    -
    -        result = {"valid": True, "errors": {}}
    -        methods = inspect.getmembers(self, predicate=inspect.ismethod)
    -        for method_name, method_callable in methods:
    -            if method_name.startswith("_"):
    -                continue
    -
    -            result["errors"][method_name] = []
    -            signature = inspect.signature(method_callable)
    -            try:
    -                validate_annotation(signature.return_annotation, "return")
    -            except ValueError as e:
    -                result["errors"][method_name].append(str(e))
    -
    -            for name, parameter in signature.parameters.items():
    -                try:
    -                    validate_annotation(parameter.annotation, f"parameter ({name})")
    -                except ValueError as e:
    -                    result["errors"][method_name].append(str(e))
    -
    -        if any(result["errors"].values()):
    -            result["valid"] = False
    -
    -        return result
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def actor_method(func) -
    -
    -
    -
    -Source code -
    def actor_method(func):
    -    @wraps(func)
    -    def wrapper(*args, **kwargs):
    -        # verify args and kwargs types
    -        signature = inspect.signature(func)
    -        try:
    -            bound = signature.bind(*args, **kwargs)
    -        except TypeError as e:
    -            raise j.exceptions.Value(str(e))
    -
    -        for name, value in bound.arguments.items():
    -            annotation = signature.parameters[name].annotation
    -            if annotation not in (None, inspect._empty) and not isinstance(value, annotation):
    -                raise j.exceptions.Value(
    -                    f"parameter ({name}) supposed to be of type ({annotation.__name__}), but found ({type(value).__name__})"
    -                )
    -
    -        # call method
    -        result = func(*bound.args, **bound.kwargs)
    -        # verify result type
    -        return_type = signature.return_annotation
    -        if return_type is inspect._empty or return_type is None:
    -            return_type = type(None)
    -
    -        if not isinstance(result, return_type):
    -            raise j.exceptions.Value(f"method is supposed to return ({return_type}), but it returned ({type(result)})")
    -
    -        return result
    -
    -    return wrapper
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class BaseActor -
    -
    -
    -
    -Source code -
    class BaseActor:
    -    def __init__(self):
    -        self.path = None
    -
    -    @actor_method
    -    def info(self) -> dict:
    -        info = {}
    -        info["path"] = self.path
    -        info["methods"] = {}
    -
    -        methods = inspect.getmembers(self, predicate=inspect.ismethod)
    -        for name, attr in methods:
    -            if name.startswith("_"):
    -                continue
    -
    -            signature = inspect.signature(attr)
    -            info["methods"][name] = {}
    -            info["methods"][name]["args"] = []
    -            info["methods"][name]["doc"] = attr.__doc__ or ""
    -
    -            for parameter_name, parameter in signature.parameters.items():
    -                info["methods"][name]["args"].append((parameter_name, parameter.annotation.__name__))
    -
    -        return info
    -
    -    def __validate_actor__(self):
    -        def validate_annotation(annotation, annotated):
    -            if annotation is None or annotation is inspect._empty:
    -                return
    -
    -            if not (inspect.isclass(annotation) and annotation.__class__ == type):
    -                raise ValueError("annotation must be a class type")
    -
    -            if annotation not in (str, int, float, list, tuple, dict, bool):
    -                if annotation.__module__ == "builtins":
    -                    raise ValueError(f"unsupported type ({annotation.__name__})")
    -
    -                for method in ["to_dict", "from_dict"]:
    -                    if method not in dir(annotation):
    -                        raise ValueError(
    -                            f"type ({annotation.__name__}) which annotate {annotated} doesn't have {method} method"
    -                        )
    -
    -        result = {"valid": True, "errors": {}}
    -        methods = inspect.getmembers(self, predicate=inspect.ismethod)
    -        for method_name, method_callable in methods:
    -            if method_name.startswith("_"):
    -                continue
    -
    -            result["errors"][method_name] = []
    -            signature = inspect.signature(method_callable)
    -            try:
    -                validate_annotation(signature.return_annotation, "return")
    -            except ValueError as e:
    -                result["errors"][method_name].append(str(e))
    -
    -            for name, parameter in signature.parameters.items():
    -                try:
    -                    validate_annotation(parameter.annotation, f"parameter ({name})")
    -                except ValueError as e:
    -                    result["errors"][method_name].append(str(e))
    -
    -        if any(result["errors"].values()):
    -            result["valid"] = False
    -
    -        return result
    -
    -

    Subclasses

    - -

    Methods

    -
    -
    -def info(self) -
    -
    -
    -
    -Source code -
    @actor_method
    -def info(self) -> dict:
    -    info = {}
    -    info["path"] = self.path
    -    info["methods"] = {}
    -
    -    methods = inspect.getmembers(self, predicate=inspect.ismethod)
    -    for name, attr in methods:
    -        if name.startswith("_"):
    -            continue
    -
    -        signature = inspect.signature(attr)
    -        info["methods"][name] = {}
    -        info["methods"][name]["args"] = []
    -        info["methods"][name]["doc"] = attr.__doc__ or ""
    -
    -        for parameter_name, parameter in signature.parameters.items():
    -            info["methods"][name]["args"].append((parameter_name, parameter.annotation.__name__))
    -
    -    return info
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/example_actor.html b/docs/api/jumpscale/servers/gedis/example_actor.html deleted file mode 100644 index efd9ebefc..000000000 --- a/docs/api/jumpscale/servers/gedis/example_actor.html +++ /dev/null @@ -1,475 +0,0 @@ - - - - - - -jumpscale.servers.gedis.example_actor API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis.example_actor

    -
    -
    -
    -Source code -
    from jumpscale.servers.gedis.baseactor import BaseActor, actor_method
    -from typing import Sequence
    -from jumpscale.loader import j
    -import inspect, sys
    -
    -
    -class TestObject:
    -    def __init__(self):
    -        self.attr = None
    -
    -    def to_dict(self):
    -        return self.__dict__
    -
    -    def from_dict(self, ddict):
    -        self.__dict__ = ddict
    -
    -
    -class Example(BaseActor):
    -    @actor_method
    -    def add_two_ints(self, x: int, y: int) -> int:
    -        """Adds two ints
    -
    -        Arguments:
    -            x {int} -- first int
    -            y {int} -- second int
    -
    -        Returns:
    -            int -- the sum of the two ints
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def concate_two_strings(self, x: str, y: str) -> str:
    -        """Concate two strings
    -
    -        Arguments:
    -            x {str} -- first string
    -            y {str} -- second string
    -
    -        Returns:
    -            str -- the concate of the two strings
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def modify_object(self, myobj: list, new_value: int) -> list:
    -        """Modify atrribute attr of the given object
    -
    -        Arguments:
    -            myobj {TestObject} -- the object to be modified
    -
    -        Returns:
    -            TestObject -- modified object
    -        """
    -        for i in range(len(myobj)):
    -            myobj[i].attr = new_value * (i + 1)
    -        return myobj
    -
    -
    -Actor = Example
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Actor -
    -
    -
    -
    -Source code -
    class Example(BaseActor):
    -    @actor_method
    -    def add_two_ints(self, x: int, y: int) -> int:
    -        """Adds two ints
    -
    -        Arguments:
    -            x {int} -- first int
    -            y {int} -- second int
    -
    -        Returns:
    -            int -- the sum of the two ints
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def concate_two_strings(self, x: str, y: str) -> str:
    -        """Concate two strings
    -
    -        Arguments:
    -            x {str} -- first string
    -            y {str} -- second string
    -
    -        Returns:
    -            str -- the concate of the two strings
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def modify_object(self, myobj: list, new_value: int) -> list:
    -        """Modify atrribute attr of the given object
    -
    -        Arguments:
    -            myobj {TestObject} -- the object to be modified
    -
    -        Returns:
    -            TestObject -- modified object
    -        """
    -        for i in range(len(myobj)):
    -            myobj[i].attr = new_value * (i + 1)
    -        return myobj
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def add_two_ints(self, x, y) -
    -
    -

    Adds two ints

    -

    Arguments

    -

    x {int} – first int -y {int} – second int

    -

    Returns

    -
    -
    intthe sum of the two ints
    -
     
    -
    -
    -Source code -
    @actor_method
    -def add_two_ints(self, x: int, y: int) -> int:
    -    """Adds two ints
    -
    -    Arguments:
    -        x {int} -- first int
    -        y {int} -- second int
    -
    -    Returns:
    -        int -- the sum of the two ints
    -    """
    -    return x + y
    -
    -
    -
    -def concate_two_strings(self, x, y) -
    -
    -

    Concate two strings

    -

    Arguments

    -

    x {str} – first string -y {str} – second string

    -

    Returns

    -
    -
    strthe concate of the two strings
    -
     
    -
    -
    -Source code -
    @actor_method
    -def concate_two_strings(self, x: str, y: str) -> str:
    -    """Concate two strings
    -
    -    Arguments:
    -        x {str} -- first string
    -        y {str} -- second string
    -
    -    Returns:
    -        str -- the concate of the two strings
    -    """
    -    return x + y
    -
    -
    -
    -def modify_object(self, myobj, new_value) -
    -
    -

    Modify atrribute attr of the given object

    -

    Arguments

    -

    myobj {TestObject} – the object to be modified

    -

    Returns

    -
    -
    TestObjectmodified object
    -
     
    -
    -
    -Source code -
    @actor_method
    -def modify_object(self, myobj: list, new_value: int) -> list:
    -    """Modify atrribute attr of the given object
    -
    -    Arguments:
    -        myobj {TestObject} -- the object to be modified
    -
    -    Returns:
    -        TestObject -- modified object
    -    """
    -    for i in range(len(myobj)):
    -        myobj[i].attr = new_value * (i + 1)
    -    return myobj
    -
    -
    -
    -
    -
    -class Example -
    -
    -
    -
    -Source code -
    class Example(BaseActor):
    -    @actor_method
    -    def add_two_ints(self, x: int, y: int) -> int:
    -        """Adds two ints
    -
    -        Arguments:
    -            x {int} -- first int
    -            y {int} -- second int
    -
    -        Returns:
    -            int -- the sum of the two ints
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def concate_two_strings(self, x: str, y: str) -> str:
    -        """Concate two strings
    -
    -        Arguments:
    -            x {str} -- first string
    -            y {str} -- second string
    -
    -        Returns:
    -            str -- the concate of the two strings
    -        """
    -        return x + y
    -
    -    @actor_method
    -    def modify_object(self, myobj: list, new_value: int) -> list:
    -        """Modify atrribute attr of the given object
    -
    -        Arguments:
    -            myobj {TestObject} -- the object to be modified
    -
    -        Returns:
    -            TestObject -- modified object
    -        """
    -        for i in range(len(myobj)):
    -            myobj[i].attr = new_value * (i + 1)
    -        return myobj
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def add_two_ints(self, x, y) -
    -
    -

    Adds two ints

    -

    Arguments

    -

    x {int} – first int -y {int} – second int

    -

    Returns

    -
    -
    intthe sum of the two ints
    -
     
    -
    -
    -Source code -
    @actor_method
    -def add_two_ints(self, x: int, y: int) -> int:
    -    """Adds two ints
    -
    -    Arguments:
    -        x {int} -- first int
    -        y {int} -- second int
    -
    -    Returns:
    -        int -- the sum of the two ints
    -    """
    -    return x + y
    -
    -
    -
    -def concate_two_strings(self, x, y) -
    -
    -

    Concate two strings

    -

    Arguments

    -

    x {str} – first string -y {str} – second string

    -

    Returns

    -
    -
    strthe concate of the two strings
    -
     
    -
    -
    -Source code -
    @actor_method
    -def concate_two_strings(self, x: str, y: str) -> str:
    -    """Concate two strings
    -
    -    Arguments:
    -        x {str} -- first string
    -        y {str} -- second string
    -
    -    Returns:
    -        str -- the concate of the two strings
    -    """
    -    return x + y
    -
    -
    -
    -def modify_object(self, myobj, new_value) -
    -
    -

    Modify atrribute attr of the given object

    -

    Arguments

    -

    myobj {TestObject} – the object to be modified

    -

    Returns

    -
    -
    TestObjectmodified object
    -
     
    -
    -
    -Source code -
    @actor_method
    -def modify_object(self, myobj: list, new_value: int) -> list:
    -    """Modify atrribute attr of the given object
    -
    -    Arguments:
    -        myobj {TestObject} -- the object to be modified
    -
    -    Returns:
    -        TestObject -- modified object
    -    """
    -    for i in range(len(myobj)):
    -        myobj[i].attr = new_value * (i + 1)
    -    return myobj
    -
    -
    -
    -
    -
    -class TestObject -
    -
    -
    -
    -Source code -
    class TestObject:
    -    def __init__(self):
    -        self.attr = None
    -
    -    def to_dict(self):
    -        return self.__dict__
    -
    -    def from_dict(self, ddict):
    -        self.__dict__ = ddict
    -
    -

    Methods

    -
    -
    -def from_dict(self, ddict) -
    -
    -
    -
    -Source code -
    def from_dict(self, ddict):
    -    self.__dict__ = ddict
    -
    -
    -
    -def to_dict(self) -
    -
    -
    -
    -Source code -
    def to_dict(self):
    -    return self.__dict__
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/example_greeter.html b/docs/api/jumpscale/servers/gedis/example_greeter.html deleted file mode 100644 index 94c0cd506..000000000 --- a/docs/api/jumpscale/servers/gedis/example_greeter.html +++ /dev/null @@ -1,257 +0,0 @@ - - - - - - -jumpscale.servers.gedis.example_greeter API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis.example_greeter

    -
    -
    -
    -Source code -
    from jumpscale.servers.gedis.baseactor import BaseActor
    -
    -
    -class Greeter(BaseActor):
    -    def hi(self):
    -        """returns hello world
    -        """
    -        return "hello world"
    -
    -    def ping(self):
    -        """
    -        
    -        """
    -        return "pong no?"
    -
    -    def add2(self, a, b):
    -        """Add two args
    -        
    -        """
    -        print("A {} B {} ".format(a, b))
    -        return a + b
    -
    -
    -Actor = Greeter
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Actor -(*args, **kwargs) -
    -
    -
    -
    -Source code -
    class Greeter(BaseActor):
    -    def hi(self):
    -        """returns hello world
    -        """
    -        return "hello world"
    -
    -    def ping(self):
    -        """
    -        
    -        """
    -        return "pong no?"
    -
    -    def add2(self, a, b):
    -        """Add two args
    -        
    -        """
    -        print("A {} B {} ".format(a, b))
    -        return a + b
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def add2(self, a, b) -
    -
    -

    Add two args

    -
    -Source code -
    def add2(self, a, b):
    -    """Add two args
    -    
    -    """
    -    print("A {} B {} ".format(a, b))
    -    return a + b
    -
    -
    -
    -def hi(self) -
    -
    -

    returns hello world

    -
    -Source code -
    def hi(self):
    -    """returns hello world
    -    """
    -    return "hello world"
    -
    -
    -
    -def ping(self) -
    -
    -
    -
    -Source code -
    def ping(self):
    -    """
    -    
    -    """
    -    return "pong no?"
    -
    -
    -
    -
    -
    -class Greeter -(*args, **kwargs) -
    -
    -
    -
    -Source code -
    class Greeter(BaseActor):
    -    def hi(self):
    -        """returns hello world
    -        """
    -        return "hello world"
    -
    -    def ping(self):
    -        """
    -        
    -        """
    -        return "pong no?"
    -
    -    def add2(self, a, b):
    -        """Add two args
    -        
    -        """
    -        print("A {} B {} ".format(a, b))
    -        return a + b
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def add2(self, a, b) -
    -
    -

    Add two args

    -
    -Source code -
    def add2(self, a, b):
    -    """Add two args
    -    
    -    """
    -    print("A {} B {} ".format(a, b))
    -    return a + b
    -
    -
    -
    -def hi(self) -
    -
    -

    returns hello world

    -
    -Source code -
    def hi(self):
    -    """returns hello world
    -    """
    -    return "hello world"
    -
    -
    -
    -def ping(self) -
    -
    -
    -
    -Source code -
    def ping(self):
    -    """
    -    
    -    """
    -    return "pong no?"
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/index.html b/docs/api/jumpscale/servers/gedis/index.html deleted file mode 100644 index e159684dd..000000000 --- a/docs/api/jumpscale/servers/gedis/index.html +++ /dev/null @@ -1,210 +0,0 @@ - - - - - - -jumpscale.servers.gedis API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis

    -
    -
    -

    Gedis server package provides all code needed to have an RPC server using redis protocol for messaging

    -

    Create Gedis instance

    -
    t = j.servers.gedis.get("test")
    -
    -

    this will create Gedis instance with name test running on -default port 16000

    -
    t = j.servers.gedis.new("test",port=1500)
    -
    -

    This will create Gedis instance with name test running on port 1500

    -

    Start Gedis server

    -
    t.start()
    -
    -

    Stop Gedis server

    -
    t.stop()
    -
    -

    ~> -redis-cli -p 16000 greeter hi -actor greeter isn't loaded -~> -redis-cli -p 16000 system register_actor greeter /home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py -(integer) -1 -~> -redis-cli -p 16000 greeter hi -hello world -~> -redis-cli -p 16000 greeter add2 jo deboeck -"jodeboeck" -~> -fuser -k 16000/tcp

    -

    16000/tcp: -29331 -~> -redis-cli -p 16000 greeter hi -actor greeter isn't loaded -~> -redis-cli -p 16000 system register_actor greeter /home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py -(integer) -1 -~> -redis-cli -p 16000 greeter hi -hello world -~> -redis-cli -p 16000 greeter ping

    -

    pong no? -~> -redis-cli -p 16000 greeter add2 reem khamis -"reemkhamis" -```

    -
    -Source code -
    """Gedis server package provides all code needed to have an RPC server using redis protocol for messaging
    -
    -### Create Gedis instance
    -```
    -t = j.servers.gedis.get("test")
    -```
    -this will create Gedis instance with name test running on  default port 16000
    -```
    -t = j.servers.gedis.new("test",port=1500)
    -```
    -This will create Gedis instance with name test running on port 1500
    -### Start Gedis server
    -```
    -t.start()
    -```
    -### Stop Gedis server
    -```
    -t.stop()
    -```
    -
    -~>  redis-cli -p 16000 greeter hi
    -actor greeter isn't loaded
    - ~>  redis-cli -p 16000 system register_actor greeter /home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py
    -(integer) -1
    - ~>  redis-cli -p 16000 greeter hi
    - hello world
    - ~>  redis-cli -p 16000 greeter add2 jo deboeck
    - "jodeboeck"
    - ~>  fuser -k 16000/tcp
    -
    -16000/tcp:           29331
    - ~>  redis-cli -p 16000 greeter hi
    - actor greeter isn't loaded
    - ~>  redis-cli -p 16000 system register_actor greeter /home/ahmed/wspace/threefoldtech/js-ng/jumpscale/servers/gedis/example_greeter.py
    -(integer) -1
    - ~>  redis-cli -p 16000 greeter hi
    - hello world
    - ~>  redis-cli -p 16000 greeter ping
    -
    -pong no?
    - ~>  redis-cli -p 16000 greeter add2 reem khamis
    -"reemkhamis"
    -```
    -"""
    -from jumpscale.core.base import StoredFactory
    -
    -
    -def export_module_as():
    -    from .server import GedisServer
    -    from jumpscale.loader import j
    -
    -    j.logger.register("gedis")
    -    return StoredFactory(GedisServer)
    -
    -
    -
    -

    Sub-modules

    -
    -
    jumpscale.servers.gedis.baseactor
    -
    -
    -
    -
    jumpscale.servers.gedis.example_actor
    -
    -
    -
    -
    jumpscale.servers.gedis.server
    -
    -
    -
    -
    jumpscale.servers.gedis.systemactor
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def export_module_as() -
    -
    -
    -
    -Source code -
    def export_module_as():
    -    from .server import GedisServer
    -    from jumpscale.loader import j
    -
    -    j.logger.register("gedis")
    -    return StoredFactory(GedisServer)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/server.html b/docs/api/jumpscale/servers/gedis/server.html deleted file mode 100644 index 463bc4e7e..000000000 --- a/docs/api/jumpscale/servers/gedis/server.html +++ /dev/null @@ -1,1068 +0,0 @@ - - - - - - -jumpscale.servers.gedis.server API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis.server

    -
    -
    -
    -Source code -
    import inspect
    -import json
    -import sys
    -import os
    -from redis import Redis
    -from enum import Enum
    -from functools import partial
    -from io import BytesIO
    -from signal import SIGKILL, SIGTERM
    -import json
    -import gevent
    -from gevent.pool import Pool
    -from gevent import time
    -from gevent.server import StreamServer
    -from jumpscale.core.base import Base, fields
    -from jumpscale.loader import j
    -from redis.connection import DefaultParser, Encoder
    -from redis.exceptions import ConnectionError
    -from .baseactor import BaseActor
    -from .systemactor import CoreActor, SystemActor
    -
    -
    -def serialize(obj):
    -    if not isinstance(obj, (str, int, float, list, tuple, dict, bool)):
    -        module = inspect.getmodule(obj).__file__[:-3]
    -        return dict(__serialized__=True, module=module, type=obj.__class__.__name__, data=obj.to_dict())
    -    return obj
    -
    -
    -def deserialize(obj):
    -    if isinstance(obj, dict) and obj.get("__serialized__"):
    -        module = sys.modules[obj["module"]]
    -        object_instance = getattr(module, obj["type"])()
    -        object_instance.from_dict(obj["data"])
    -        return object_instance
    -    return obj
    -
    -
    -class GedisErrorTypes(Enum):
    -    NOT_FOUND = 0
    -    BAD_REQUEST = 1
    -    ACTOR_ERROR = 3
    -    INTERNAL_SERVER_ERROR = 4
    -    PERMISSION_ERROR = 5
    -
    -
    -EXCEPTIONS_MAP = {
    -    j.exceptions.Value: GedisErrorTypes.BAD_REQUEST.value,
    -    j.exceptions.NotFound: GedisErrorTypes.NOT_FOUND.value,
    -    j.exceptions.Permission: GedisErrorTypes.PERMISSION_ERROR.value,
    -}
    -
    -
    -class RedisConnectionAdapter:
    -    def __init__(self, sock):
    -        self.socket = sock
    -        self._sock = sock
    -        self.socket_timeout = 600
    -        self.socket_connect_timeout = 600
    -        self.socket_keepalive = True
    -        self.retry_on_timeout = True
    -        self.socket_keepalive_options = {}
    -        self.encoder = Encoder("utf", "strict", False)
    -
    -
    -class ResponseEncoder:
    -    def __init__(self, socket):
    -        self.socket = socket
    -        self.buffer = BytesIO()
    -
    -    def encode(self, value):
    -        """Respond with data."""
    -        if value is None:
    -            self._write_buffer("$-1\r\n")
    -        elif isinstance(value, int):
    -            self._write_buffer(":{}\r\n".format(value))
    -        elif isinstance(value, bool):
    -            self._write_buffer(":{}\r\n".format(1 if value else 0))
    -        elif isinstance(value, str):
    -            if "\n" in value:
    -                self._bulk(value)
    -            else:
    -                self._write_buffer("+{}\r\n".format(value))
    -        elif isinstance(value, bytes):
    -            self._bulkbytes(value)
    -        elif isinstance(value, list):
    -            if value and value[0] == "*REDIS*":
    -                value = value[1:]
    -            self._array(value)
    -        elif hasattr(value, "__repr__"):
    -            self._bulk(value.__repr__())
    -        else:
    -            value = j.data.serializers.json.dumps(value, encoding="utf-8")
    -            self.encode(value)
    -
    -        self._send()
    -
    -    def status(self, msg="OK"):
    -        """Send a status."""
    -        self._write_buffer("+{}\r\n".format(msg))
    -        self._send()
    -
    -    def error(self, msg):
    -        """Send an error."""
    -        # print("###:%s" % msg)
    -        self._write_buffer("-ERR {}\r\n".format(msg))
    -        self._send()
    -
    -    def _bulk(self, value):
    -        """Send part of a multiline reply."""
    -        data = ["$", str(len(value)), "\r\n", value, "\r\n"]
    -        self._write_buffer("".join(data))
    -
    -    def _array(self, value):
    -        """send an array."""
    -        self._write_buffer("*{}\r\n".format(len(value)))
    -        for item in value:
    -            self.encode(item)
    -
    -    def _bulkbytes(self, value):
    -        data = [b"$", str(len(value)).encode(), b"\r\n", value, b"\r\n"]
    -        self._write_buffer(b"".join(data))
    -
    -    def _write_buffer(self, data):
    -        if isinstance(data, str):
    -            data = data.encode()
    -
    -        self.buffer.write(data)
    -
    -    def _send(self):
    -        self.socket.sendall(self.buffer.getvalue())
    -        self.buffer = BytesIO()  # seems faster then truncating
    -
    -
    -SERIALIZABLE_TYPES = (str, int, float, list, tuple, dict, bool)
    -RESERVED_ACTOR_NAMES = ("core", "system")
    -
    -
    -class GedisServer(Base):
    -    host = fields.String(default="127.0.0.1")
    -    port = fields.Integer(default=16000)
    -    enable_system_actor = fields.Boolean(default=True)
    -    run_async = fields.Boolean(default=True)
    -    _actors = fields.Typed(dict, default={})
    -
    -    def __init__(self, *args, **kwargs):
    -        super().__init__(*args, **kwargs)
    -        self._core_actor = CoreActor()
    -        self._system_actor = SystemActor()
    -        self._loaded_actors = {"core": self._core_actor}
    -
    -    @property
    -    def actors(self):
    -        """Lists saved actors
    -
    -        Returns:
    -            list -- List of saved actors
    -        """
    -        return self._actors
    -
    -    def actor_add(self, actor_name: str, actor_path: str):
    -        """Adds an actor to the server
    -
    -        Arguments:
    -            actor_name {str} -- Actor name
    -            actor_path {str} -- Actor absolute path
    -
    -        Raises:
    -            j.exceptions.Value: raises if actor name is matched one of the reserved actor names
    -            j.exceptions.Value: raises if actor name is not a valid identifier
    -        """
    -        if actor_name in RESERVED_ACTOR_NAMES:
    -            raise j.exceptions.Value("Invalid actor name")
    -
    -        if not actor_name.isidentifier():
    -            raise j.exceptions.Value(f"Actor name should be a valid identifier")
    -
    -        self._actors[actor_name] = actor_path
    -
    -    def actor_delete(self, actor_name: str):
    -        """Removes an actor from the server
    -
    -        Arguments:
    -            actor_name {str} -- Actor name
    -        """
    -        self._actors.pop(actor_name, None)
    -
    -    def start(self):
    -        """Starts the server
    -        """
    -        # handle signals
    -        for signal_type in (SIGTERM, SIGKILL):
    -            gevent.signal(signal_type, self.stop)
    -
    -        # register system actor if enabled
    -        if self.enable_system_actor:
    -            self._register_actor("system", self._system_actor)
    -
    -        self._core_actor.set_server(self)
    -        self._system_actor.set_server(self)
    -
    -        # register saved actors
    -        for actor_name, actor_path in self._actors.items():
    -            self._system_actor.register_actor(actor_name, actor_path)
    -
    -        # start the server
    -        self._server = StreamServer((self.host, self.port), self._on_connection, spawn=Pool())
    -        self._server.reuse_addr = True
    -        self._server.start()
    -
    -        j.logger.info(f"Gedis server is started at {self.host}:{self.port}...")
    -
    -    def stop(self):
    -        """Stops the server
    -        """
    -        j.logger.info("Shutting down...")
    -        self._server.stop()
    -
    -    def _register_actor(self, actor_name: str, actor_module: BaseActor):
    -        self._loaded_actors[actor_name] = actor_module
    -
    -    def _unregister_actor(self, actor_name: str):
    -        self._loaded_actors.pop(actor_name, None)
    -
    -    def _execute(self, method, args, kwargs):
    -        response = {}
    -        try:
    -            response["result"] = method(*args, **kwargs)
    -
    -        except Exception as e:
    -            j.logger.exception(f"error while executing {method}", exception=e)
    -
    -            response["error"] = str(e)
    -            response["error_type"] = EXCEPTIONS_MAP.get(e.__class__, GedisErrorTypes.ACTOR_ERROR.value)
    -
    -        return response
    -
    -    def _on_connection(self, socket, address):
    -        j.logger.info("New connection from {}", address)
    -        parser = DefaultParser(65536)
    -        connection = RedisConnectionAdapter(socket)
    -        try:
    -            encoder = ResponseEncoder(socket)
    -            parser.on_connect(connection)
    -
    -            while True:
    -                response = dict(success=True, result=None, error=None, error_type=None, is_async=False, task_id=None)
    -                try:
    -                    request = parser.read_response()
    -
    -                    if len(request) < 2:
    -                        response["error"] = "invalid request"
    -                        response["error_type"] = GedisErrorTypes.BAD_REQUEST.value
    -
    -                    else:
    -                        actor_name = request.pop(0).decode()
    -                        method_name = request.pop(0).decode()
    -                        actor_object = self._loaded_actors.get(actor_name)
    -
    -                        if not actor_object:
    -                            response["error"] = "actor not found"
    -                            response["error_type"] = GedisErrorTypes.NOT_FOUND.value
    -
    -                        elif not hasattr(actor_object, method_name):
    -                            response["error"] = "method not found"
    -                            response["error_type"] = GedisErrorTypes.NOT_FOUND.value
    -
    -                        else:
    -                            j.logger.info(
    -                                "Executing method {} from actor {} to client {}", method_name, actor_name, address
    -                            )
    -
    -                            if request:
    -                                args, kwargs = json.loads(request.pop(0), object_hook=deserialize)
    -                            else:
    -                                args, kwargs = (), {}
    -
    -                            method = getattr(actor_object, method_name)
    -                            result = self._execute(method, args, kwargs)
    -                            response.update(result)
    -
    -                except ConnectionError:
    -                    j.logger.info("Client {} closed the connection", address)
    -
    -                except Exception as exception:
    -                    j.logger.exception("internal error", exception=exception)
    -                    response["error"] = "internal server error"
    -                    response["error_type"] = GedisErrorTypes.INTERNAL_SERVER_ERROR.value
    -
    -                response["success"] = response["error"] is None
    -                encoder.encode(json.dumps(response, default=serialize))
    -
    -            parser.on_disconnect()
    -
    -        except BrokenPipeError:
    -            pass
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def deserialize(obj) -
    -
    -
    -
    -Source code -
    def deserialize(obj):
    -    if isinstance(obj, dict) and obj.get("__serialized__"):
    -        module = sys.modules[obj["module"]]
    -        object_instance = getattr(module, obj["type"])()
    -        object_instance.from_dict(obj["data"])
    -        return object_instance
    -    return obj
    -
    -
    -
    -def serialize(obj) -
    -
    -
    -
    -Source code -
    def serialize(obj):
    -    if not isinstance(obj, (str, int, float, list, tuple, dict, bool)):
    -        module = inspect.getmodule(obj).__file__[:-3]
    -        return dict(__serialized__=True, module=module, type=obj.__class__.__name__, data=obj.to_dict())
    -    return obj
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class GedisErrorTypes -(*args, **kwargs) -
    -
    -

    An enumeration.

    -
    -Source code -
    class GedisErrorTypes(Enum):
    -    NOT_FOUND = 0
    -    BAD_REQUEST = 1
    -    ACTOR_ERROR = 3
    -    INTERNAL_SERVER_ERROR = 4
    -    PERMISSION_ERROR = 5
    -
    -

    Ancestors

    -
      -
    • enum.Enum
    • -
    -

    Class variables

    -
    -
    var ACTOR_ERROR
    -
    -
    -
    -
    var BAD_REQUEST
    -
    -
    -
    -
    var INTERNAL_SERVER_ERROR
    -
    -
    -
    -
    var NOT_FOUND
    -
    -
    -
    -
    var PERMISSION_ERROR
    -
    -
    -
    -
    -
    -
    -class GedisServer -(*args, **kwargs) -
    -
    -

    A simple attribute-based namespace.

    -

    SimpleNamespace(**kwargs)

    -

    base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

    -

    any instance can have an optional name and a parent.

    -
    class Person(Base):
    -    name = fields.String()
    -    age = fields.Float()
    -
    -p = Person(name="ahmed", age="19")
    -print(p.name, p.age)
    -
    -

    Args

    -
    -
    parent_ : Base, optional
    -
    parent instance. Defaults to None.
    -
    instance_name_ : str, optional
    -
    instance name. Defaults to None.
    -
    **values
    -
    any given field values to initiate the instance with
    -
    -
    -Source code -
    class GedisServer(Base):
    -    host = fields.String(default="127.0.0.1")
    -    port = fields.Integer(default=16000)
    -    enable_system_actor = fields.Boolean(default=True)
    -    run_async = fields.Boolean(default=True)
    -    _actors = fields.Typed(dict, default={})
    -
    -    def __init__(self, *args, **kwargs):
    -        super().__init__(*args, **kwargs)
    -        self._core_actor = CoreActor()
    -        self._system_actor = SystemActor()
    -        self._loaded_actors = {"core": self._core_actor}
    -
    -    @property
    -    def actors(self):
    -        """Lists saved actors
    -
    -        Returns:
    -            list -- List of saved actors
    -        """
    -        return self._actors
    -
    -    def actor_add(self, actor_name: str, actor_path: str):
    -        """Adds an actor to the server
    -
    -        Arguments:
    -            actor_name {str} -- Actor name
    -            actor_path {str} -- Actor absolute path
    -
    -        Raises:
    -            j.exceptions.Value: raises if actor name is matched one of the reserved actor names
    -            j.exceptions.Value: raises if actor name is not a valid identifier
    -        """
    -        if actor_name in RESERVED_ACTOR_NAMES:
    -            raise j.exceptions.Value("Invalid actor name")
    -
    -        if not actor_name.isidentifier():
    -            raise j.exceptions.Value(f"Actor name should be a valid identifier")
    -
    -        self._actors[actor_name] = actor_path
    -
    -    def actor_delete(self, actor_name: str):
    -        """Removes an actor from the server
    -
    -        Arguments:
    -            actor_name {str} -- Actor name
    -        """
    -        self._actors.pop(actor_name, None)
    -
    -    def start(self):
    -        """Starts the server
    -        """
    -        # handle signals
    -        for signal_type in (SIGTERM, SIGKILL):
    -            gevent.signal(signal_type, self.stop)
    -
    -        # register system actor if enabled
    -        if self.enable_system_actor:
    -            self._register_actor("system", self._system_actor)
    -
    -        self._core_actor.set_server(self)
    -        self._system_actor.set_server(self)
    -
    -        # register saved actors
    -        for actor_name, actor_path in self._actors.items():
    -            self._system_actor.register_actor(actor_name, actor_path)
    -
    -        # start the server
    -        self._server = StreamServer((self.host, self.port), self._on_connection, spawn=Pool())
    -        self._server.reuse_addr = True
    -        self._server.start()
    -
    -        j.logger.info(f"Gedis server is started at {self.host}:{self.port}...")
    -
    -    def stop(self):
    -        """Stops the server
    -        """
    -        j.logger.info("Shutting down...")
    -        self._server.stop()
    -
    -    def _register_actor(self, actor_name: str, actor_module: BaseActor):
    -        self._loaded_actors[actor_name] = actor_module
    -
    -    def _unregister_actor(self, actor_name: str):
    -        self._loaded_actors.pop(actor_name, None)
    -
    -    def _execute(self, method, args, kwargs):
    -        response = {}
    -        try:
    -            response["result"] = method(*args, **kwargs)
    -
    -        except Exception as e:
    -            j.logger.exception(f"error while executing {method}", exception=e)
    -
    -            response["error"] = str(e)
    -            response["error_type"] = EXCEPTIONS_MAP.get(e.__class__, GedisErrorTypes.ACTOR_ERROR.value)
    -
    -        return response
    -
    -    def _on_connection(self, socket, address):
    -        j.logger.info("New connection from {}", address)
    -        parser = DefaultParser(65536)
    -        connection = RedisConnectionAdapter(socket)
    -        try:
    -            encoder = ResponseEncoder(socket)
    -            parser.on_connect(connection)
    -
    -            while True:
    -                response = dict(success=True, result=None, error=None, error_type=None, is_async=False, task_id=None)
    -                try:
    -                    request = parser.read_response()
    -
    -                    if len(request) < 2:
    -                        response["error"] = "invalid request"
    -                        response["error_type"] = GedisErrorTypes.BAD_REQUEST.value
    -
    -                    else:
    -                        actor_name = request.pop(0).decode()
    -                        method_name = request.pop(0).decode()
    -                        actor_object = self._loaded_actors.get(actor_name)
    -
    -                        if not actor_object:
    -                            response["error"] = "actor not found"
    -                            response["error_type"] = GedisErrorTypes.NOT_FOUND.value
    -
    -                        elif not hasattr(actor_object, method_name):
    -                            response["error"] = "method not found"
    -                            response["error_type"] = GedisErrorTypes.NOT_FOUND.value
    -
    -                        else:
    -                            j.logger.info(
    -                                "Executing method {} from actor {} to client {}", method_name, actor_name, address
    -                            )
    -
    -                            if request:
    -                                args, kwargs = json.loads(request.pop(0), object_hook=deserialize)
    -                            else:
    -                                args, kwargs = (), {}
    -
    -                            method = getattr(actor_object, method_name)
    -                            result = self._execute(method, args, kwargs)
    -                            response.update(result)
    -
    -                except ConnectionError:
    -                    j.logger.info("Client {} closed the connection", address)
    -
    -                except Exception as exception:
    -                    j.logger.exception("internal error", exception=exception)
    -                    response["error"] = "internal server error"
    -                    response["error_type"] = GedisErrorTypes.INTERNAL_SERVER_ERROR.value
    -
    -                response["success"] = response["error"] is None
    -                encoder.encode(json.dumps(response, default=serialize))
    -
    -            parser.on_disconnect()
    -
    -        except BrokenPipeError:
    -            pass
    -
    -

    Ancestors

    -
      -
    • Base
    • -
    • types.SimpleNamespace
    • -
    -

    Instance variables

    -
    -
    var actors
    -
    -

    Lists saved actors

    -

    Returns

    -
    -
    listList of saved actors
    -
     
    -
    -
    -Source code -
    @property
    -def actors(self):
    -    """Lists saved actors
    -
    -    Returns:
    -        list -- List of saved actors
    -    """
    -    return self._actors
    -
    -
    -
    var enable_system_actor
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    var host
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    var port
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    var run_async
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    -

    Methods

    -
    -
    -def actor_add(self, actor_name, actor_path) -
    -
    -

    Adds an actor to the server

    -

    Arguments

    -

    actor_name {str} – Actor name -actor_path {str} – Actor absolute path

    -

    Raises

    -
    -
    j.exceptions.Value: raises if actor name is matched one of the reserved actor names
    -
     
    -
    j.exceptions.Value: raises if actor name is not a valid identifier
    -
     
    -
    -
    -Source code -
    def actor_add(self, actor_name: str, actor_path: str):
    -    """Adds an actor to the server
    -
    -    Arguments:
    -        actor_name {str} -- Actor name
    -        actor_path {str} -- Actor absolute path
    -
    -    Raises:
    -        j.exceptions.Value: raises if actor name is matched one of the reserved actor names
    -        j.exceptions.Value: raises if actor name is not a valid identifier
    -    """
    -    if actor_name in RESERVED_ACTOR_NAMES:
    -        raise j.exceptions.Value("Invalid actor name")
    -
    -    if not actor_name.isidentifier():
    -        raise j.exceptions.Value(f"Actor name should be a valid identifier")
    -
    -    self._actors[actor_name] = actor_path
    -
    -
    -
    -def actor_delete(self, actor_name) -
    -
    -

    Removes an actor from the server

    -

    Arguments

    -

    actor_name {str} – Actor name

    -
    -Source code -
    def actor_delete(self, actor_name: str):
    -    """Removes an actor from the server
    -
    -    Arguments:
    -        actor_name {str} -- Actor name
    -    """
    -    self._actors.pop(actor_name, None)
    -
    -
    -
    -def start(self) -
    -
    -

    Starts the server

    -
    -Source code -
    def start(self):
    -    """Starts the server
    -    """
    -    # handle signals
    -    for signal_type in (SIGTERM, SIGKILL):
    -        gevent.signal(signal_type, self.stop)
    -
    -    # register system actor if enabled
    -    if self.enable_system_actor:
    -        self._register_actor("system", self._system_actor)
    -
    -    self._core_actor.set_server(self)
    -    self._system_actor.set_server(self)
    -
    -    # register saved actors
    -    for actor_name, actor_path in self._actors.items():
    -        self._system_actor.register_actor(actor_name, actor_path)
    -
    -    # start the server
    -    self._server = StreamServer((self.host, self.port), self._on_connection, spawn=Pool())
    -    self._server.reuse_addr = True
    -    self._server.start()
    -
    -    j.logger.info(f"Gedis server is started at {self.host}:{self.port}...")
    -
    -
    -
    -def stop(self) -
    -
    -

    Stops the server

    -
    -Source code -
    def stop(self):
    -    """Stops the server
    -    """
    -    j.logger.info("Shutting down...")
    -    self._server.stop()
    -
    -
    -
    -

    Inherited members

    - -
    -
    -class RedisConnectionAdapter -(sock) -
    -
    -
    -
    -Source code -
    class RedisConnectionAdapter:
    -    def __init__(self, sock):
    -        self.socket = sock
    -        self._sock = sock
    -        self.socket_timeout = 600
    -        self.socket_connect_timeout = 600
    -        self.socket_keepalive = True
    -        self.retry_on_timeout = True
    -        self.socket_keepalive_options = {}
    -        self.encoder = Encoder("utf", "strict", False)
    -
    -
    -
    -class ResponseEncoder -(socket) -
    -
    -
    -
    -Source code -
    class ResponseEncoder:
    -    def __init__(self, socket):
    -        self.socket = socket
    -        self.buffer = BytesIO()
    -
    -    def encode(self, value):
    -        """Respond with data."""
    -        if value is None:
    -            self._write_buffer("$-1\r\n")
    -        elif isinstance(value, int):
    -            self._write_buffer(":{}\r\n".format(value))
    -        elif isinstance(value, bool):
    -            self._write_buffer(":{}\r\n".format(1 if value else 0))
    -        elif isinstance(value, str):
    -            if "\n" in value:
    -                self._bulk(value)
    -            else:
    -                self._write_buffer("+{}\r\n".format(value))
    -        elif isinstance(value, bytes):
    -            self._bulkbytes(value)
    -        elif isinstance(value, list):
    -            if value and value[0] == "*REDIS*":
    -                value = value[1:]
    -            self._array(value)
    -        elif hasattr(value, "__repr__"):
    -            self._bulk(value.__repr__())
    -        else:
    -            value = j.data.serializers.json.dumps(value, encoding="utf-8")
    -            self.encode(value)
    -
    -        self._send()
    -
    -    def status(self, msg="OK"):
    -        """Send a status."""
    -        self._write_buffer("+{}\r\n".format(msg))
    -        self._send()
    -
    -    def error(self, msg):
    -        """Send an error."""
    -        # print("###:%s" % msg)
    -        self._write_buffer("-ERR {}\r\n".format(msg))
    -        self._send()
    -
    -    def _bulk(self, value):
    -        """Send part of a multiline reply."""
    -        data = ["$", str(len(value)), "\r\n", value, "\r\n"]
    -        self._write_buffer("".join(data))
    -
    -    def _array(self, value):
    -        """send an array."""
    -        self._write_buffer("*{}\r\n".format(len(value)))
    -        for item in value:
    -            self.encode(item)
    -
    -    def _bulkbytes(self, value):
    -        data = [b"$", str(len(value)).encode(), b"\r\n", value, b"\r\n"]
    -        self._write_buffer(b"".join(data))
    -
    -    def _write_buffer(self, data):
    -        if isinstance(data, str):
    -            data = data.encode()
    -
    -        self.buffer.write(data)
    -
    -    def _send(self):
    -        self.socket.sendall(self.buffer.getvalue())
    -        self.buffer = BytesIO()  # seems faster then truncating
    -
    -

    Methods

    -
    -
    -def encode(self, value) -
    -
    -

    Respond with data.

    -
    -Source code -
    def encode(self, value):
    -    """Respond with data."""
    -    if value is None:
    -        self._write_buffer("$-1\r\n")
    -    elif isinstance(value, int):
    -        self._write_buffer(":{}\r\n".format(value))
    -    elif isinstance(value, bool):
    -        self._write_buffer(":{}\r\n".format(1 if value else 0))
    -    elif isinstance(value, str):
    -        if "\n" in value:
    -            self._bulk(value)
    -        else:
    -            self._write_buffer("+{}\r\n".format(value))
    -    elif isinstance(value, bytes):
    -        self._bulkbytes(value)
    -    elif isinstance(value, list):
    -        if value and value[0] == "*REDIS*":
    -            value = value[1:]
    -        self._array(value)
    -    elif hasattr(value, "__repr__"):
    -        self._bulk(value.__repr__())
    -    else:
    -        value = j.data.serializers.json.dumps(value, encoding="utf-8")
    -        self.encode(value)
    -
    -    self._send()
    -
    -
    -
    -def error(self, msg) -
    -
    -

    Send an error.

    -
    -Source code -
    def error(self, msg):
    -    """Send an error."""
    -    # print("###:%s" % msg)
    -    self._write_buffer("-ERR {}\r\n".format(msg))
    -    self._send()
    -
    -
    -
    -def status(self, msg='OK') -
    -
    -

    Send a status.

    -
    -Source code -
    def status(self, msg="OK"):
    -    """Send a status."""
    -    self._write_buffer("+{}\r\n".format(msg))
    -    self._send()
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis/systemactor.html b/docs/api/jumpscale/servers/gedis/systemactor.html deleted file mode 100644 index cc7ac84b0..000000000 --- a/docs/api/jumpscale/servers/gedis/systemactor.html +++ /dev/null @@ -1,382 +0,0 @@ - - - - - - -jumpscale.servers.gedis.systemactor API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis.systemactor

    -
    -
    -
    -Source code -
    import os
    -import sys
    -import json
    -import inspect
    -from jumpscale.loader import j
    -from jumpscale.servers.gedis.baseactor import BaseActor, actor_method
    -
    -
    -class CoreActor(BaseActor):
    -    def __init__(self):
    -        super().__init__()
    -        self._server = None
    -        self.path = __file__
    -
    -    def set_server(self, server):
    -        self._server = server
    -
    -    @actor_method
    -    def list_actors(self) -> list:
    -        """List available actors
    -
    -        Returns:
    -            list -- list of available actors
    -        """
    -        return list(self._server._loaded_actors.keys())
    -
    -
    -class SystemActor(BaseActor):
    -    def __init__(self):
    -        super().__init__()
    -        self._server = None
    -        self.path = __file__
    -
    -    def set_server(self, server):
    -        self._server = server
    -
    -    @actor_method
    -    def register_actor(self, actor_name: str, actor_path: str, force_reload: bool = False) -> bool:
    -        """
    -        Register new actor
    -
    -        Args:
    -            actor_name (str): actor name within gedis server.
    -            actor_path (str): actor path on gedis server machine.
    -            force_reload (bool, optional): reload the module if set. Defaults to False.
    -
    -        Raises:
    -            j.exceptions.Validation: in case the actor is not valid
    -
    -        Returns:
    -            bool: True if registered
    -        """
    -        module = j.tools.codeloader.load_python_module(actor_path, force_reload=force_reload)
    -        actor = module.Actor()
    -        actor.path = actor_path
    -        result = actor.__validate_actor__()
    -
    -        if not result["valid"]:
    -            raise j.exceptions.Validation(
    -                "Actor {} is not valid, check the following errors {}".format(actor_name, result["errors"])
    -            )
    -
    -        self._server._register_actor(actor_name, actor)
    -        return True
    -
    -    @actor_method
    -    def unregister_actor(self, actor_name: str) -> bool:
    -        """Register actor
    -
    -        Arguments:
    -            actor_name {str} -- actor name
    -
    -        Returns:
    -            bool -- True if actors is unregistered
    -        """
    -        self._server._unregister_actor(actor_name)
    -        return True
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class CoreActor -
    -
    -
    -
    -Source code -
    class CoreActor(BaseActor):
    -    def __init__(self):
    -        super().__init__()
    -        self._server = None
    -        self.path = __file__
    -
    -    def set_server(self, server):
    -        self._server = server
    -
    -    @actor_method
    -    def list_actors(self) -> list:
    -        """List available actors
    -
    -        Returns:
    -            list -- list of available actors
    -        """
    -        return list(self._server._loaded_actors.keys())
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def list_actors(self) -
    -
    -

    List available actors

    -

    Returns

    -
    -
    listlist of available actors
    -
     
    -
    -
    -Source code -
    @actor_method
    -def list_actors(self) -> list:
    -    """List available actors
    -
    -    Returns:
    -        list -- list of available actors
    -    """
    -    return list(self._server._loaded_actors.keys())
    -
    -
    -
    -def set_server(self, server) -
    -
    -
    -
    -Source code -
    def set_server(self, server):
    -    self._server = server
    -
    -
    -
    -
    -
    -class SystemActor -
    -
    -
    -
    -Source code -
    class SystemActor(BaseActor):
    -    def __init__(self):
    -        super().__init__()
    -        self._server = None
    -        self.path = __file__
    -
    -    def set_server(self, server):
    -        self._server = server
    -
    -    @actor_method
    -    def register_actor(self, actor_name: str, actor_path: str, force_reload: bool = False) -> bool:
    -        """
    -        Register new actor
    -
    -        Args:
    -            actor_name (str): actor name within gedis server.
    -            actor_path (str): actor path on gedis server machine.
    -            force_reload (bool, optional): reload the module if set. Defaults to False.
    -
    -        Raises:
    -            j.exceptions.Validation: in case the actor is not valid
    -
    -        Returns:
    -            bool: True if registered
    -        """
    -        module = j.tools.codeloader.load_python_module(actor_path, force_reload=force_reload)
    -        actor = module.Actor()
    -        actor.path = actor_path
    -        result = actor.__validate_actor__()
    -
    -        if not result["valid"]:
    -            raise j.exceptions.Validation(
    -                "Actor {} is not valid, check the following errors {}".format(actor_name, result["errors"])
    -            )
    -
    -        self._server._register_actor(actor_name, actor)
    -        return True
    -
    -    @actor_method
    -    def unregister_actor(self, actor_name: str) -> bool:
    -        """Register actor
    -
    -        Arguments:
    -            actor_name {str} -- actor name
    -
    -        Returns:
    -            bool -- True if actors is unregistered
    -        """
    -        self._server._unregister_actor(actor_name)
    -        return True
    -
    -

    Ancestors

    - -

    Methods

    -
    -
    -def register_actor(self, actor_name, actor_path, force_reload=False) -
    -
    -

    Register new actor

    -

    Args

    -
    -
    actor_name : str
    -
    actor name within gedis server.
    -
    actor_path : str
    -
    actor path on gedis server machine.
    -
    force_reload : bool, optional
    -
    reload the module if set. Defaults to False.
    -
    -

    Raises

    -
    -
    j.exceptions.Validation: in case the actor is not valid
    -
     
    -
    -

    Returns

    -
    -
    bool
    -
    True if registered
    -
    -
    -Source code -
    @actor_method
    -def register_actor(self, actor_name: str, actor_path: str, force_reload: bool = False) -> bool:
    -    """
    -    Register new actor
    -
    -    Args:
    -        actor_name (str): actor name within gedis server.
    -        actor_path (str): actor path on gedis server machine.
    -        force_reload (bool, optional): reload the module if set. Defaults to False.
    -
    -    Raises:
    -        j.exceptions.Validation: in case the actor is not valid
    -
    -    Returns:
    -        bool: True if registered
    -    """
    -    module = j.tools.codeloader.load_python_module(actor_path, force_reload=force_reload)
    -    actor = module.Actor()
    -    actor.path = actor_path
    -    result = actor.__validate_actor__()
    -
    -    if not result["valid"]:
    -        raise j.exceptions.Validation(
    -            "Actor {} is not valid, check the following errors {}".format(actor_name, result["errors"])
    -        )
    -
    -    self._server._register_actor(actor_name, actor)
    -    return True
    -
    -
    -
    -def set_server(self, server) -
    -
    -
    -
    -Source code -
    def set_server(self, server):
    -    self._server = server
    -
    -
    -
    -def unregister_actor(self, actor_name) -
    -
    -

    Register actor

    -

    Arguments

    -

    actor_name {str} – actor name

    -

    Returns

    -
    -
    boolTrue if actors is unregistered
    -
     
    -
    -
    -Source code -
    @actor_method
    -def unregister_actor(self, actor_name: str) -> bool:
    -    """Register actor
    -
    -    Arguments:
    -        actor_name {str} -- actor name
    -
    -    Returns:
    -        bool -- True if actors is unregistered
    -    """
    -    self._server._unregister_actor(actor_name)
    -    return True
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/servers/gedis_http/index.html b/docs/api/jumpscale/servers/gedis_http/index.html deleted file mode 100644 index fc9d499ff..000000000 --- a/docs/api/jumpscale/servers/gedis_http/index.html +++ /dev/null @@ -1,485 +0,0 @@ - - - - - - -jumpscale.servers.gedis_http API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.servers.gedis_http

    -
    -
    -
    -Source code -
    import json
    -from jumpscale.core.base import Base, fields
    -from jumpscale.loader import j
    -from gevent.pool import Pool
    -from bottle import Bottle, abort, request, response
    -from jumpscale.servers.gedis.server import GedisErrorTypes
    -from gevent.pywsgi import WSGIServer
    -from jumpscale.core.base import StoredFactory
    -
    -
    -class GedisHTTPServer(Base):
    -    host = fields.String(default="127.0.0.1")
    -    port = fields.Integer(default=8000)
    -    allow_cors = fields.Boolean(default=True)
    -
    -    def __init__(self, *args, **kwargs):
    -        super().__init__(*args, **kwargs)
    -        self._app = Bottle()
    -        self._client = None
    -        http_methods = ["GET", "POST"]
    -        if self.allow_cors:
    -            http_methods.extend(["OPTIONS", "PUT", "DELETE"])
    -        self._app.route("/<package>/<actor>/<method>", http_methods, self.enable_cors(self.handler, self.allow_cors))
    -
    -    @property
    -    def client(self):
    -        if self._client is None:
    -            self._client = j.clients.gedis.get(self.instance_name)
    -            self._client.disable_deserialization = True
    -        return self._client
    -
    -    def make_response(self, code, content):
    -        response.status = code
    -        response.content_type = "application/json"
    -        return json.dumps(content)
    -
    -    def enable_cors(self, fn, allow_cors=True):
    -        def _enable_cors(*args, **kwargs):
    -            # set CORS headers
    -            response.headers["Access-Control-Allow-Origin"] = "*"
    -            response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS, DELETE"
    -            response.headers[
    -                "Access-Control-Allow-Headers"
    -            ] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
    -
    -            if request.method != "OPTIONS":
    -                # actual request; reply with the actual response
    -                return fn(*args, **kwargs)
    -
    -        if allow_cors:
    -            return _enable_cors
    -        else:
    -            return fn
    -
    -    def handler(self, package, actor, method):
    -        actors = self.client.actors
    -
    -        actor = getattr(actors, f"{package}_{actor}", None)
    -        if not actor:
    -            return self.make_response(400, {"error": "actor not found"})
    -
    -        method = getattr(actor, method, None)
    -        if not method:
    -            return self.make_response(400, {"error": "method not found"})
    -
    -        kwargs = request.json or dict()
    -        response = method(**kwargs)
    -
    -        if not response.success:
    -            if response.error_type == GedisErrorTypes.NOT_FOUND:
    -                return self.make_response(404, {"error": response.error})
    -
    -            elif response.error_type == GedisErrorTypes.BAD_REQUEST:
    -                return self.make_response(400, {"error": response.error})
    -
    -            elif response.error_type == GedisErrorTypes.PERMISSION_ERROR:
    -                return self.make_response(403, {"error": response.error})
    -
    -            else:
    -                return self.make_response(500, {"error": response.error})
    -
    -        return self.make_response(200, response.result)
    -
    -    @property
    -    def gevent_server(self):
    -        return WSGIServer((self.host, self.port), self._app, spawn=Pool())
    -
    -
    -def export_module_as():
    -    return StoredFactory(GedisHTTPServer)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def export_module_as() -
    -
    -
    -
    -Source code -
    def export_module_as():
    -    return StoredFactory(GedisHTTPServer)
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class GedisHTTPServer -(*args, **kwargs) -
    -
    -

    A simple attribute-based namespace.

    -

    SimpleNamespace(**kwargs)

    -

    base class implementation for any class with fields which supports getting/setting raw data for any instance fields.

    -

    any instance can have an optional name and a parent.

    -
    class Person(Base):
    -    name = fields.String()
    -    age = fields.Float()
    -
    -p = Person(name="ahmed", age="19")
    -print(p.name, p.age)
    -
    -

    Args

    -
    -
    parent_ : Base, optional
    -
    parent instance. Defaults to None.
    -
    instance_name_ : str, optional
    -
    instance name. Defaults to None.
    -
    **values
    -
    any given field values to initiate the instance with
    -
    -
    -Source code -
    class GedisHTTPServer(Base):
    -    host = fields.String(default="127.0.0.1")
    -    port = fields.Integer(default=8000)
    -    allow_cors = fields.Boolean(default=True)
    -
    -    def __init__(self, *args, **kwargs):
    -        super().__init__(*args, **kwargs)
    -        self._app = Bottle()
    -        self._client = None
    -        http_methods = ["GET", "POST"]
    -        if self.allow_cors:
    -            http_methods.extend(["OPTIONS", "PUT", "DELETE"])
    -        self._app.route("/<package>/<actor>/<method>", http_methods, self.enable_cors(self.handler, self.allow_cors))
    -
    -    @property
    -    def client(self):
    -        if self._client is None:
    -            self._client = j.clients.gedis.get(self.instance_name)
    -            self._client.disable_deserialization = True
    -        return self._client
    -
    -    def make_response(self, code, content):
    -        response.status = code
    -        response.content_type = "application/json"
    -        return json.dumps(content)
    -
    -    def enable_cors(self, fn, allow_cors=True):
    -        def _enable_cors(*args, **kwargs):
    -            # set CORS headers
    -            response.headers["Access-Control-Allow-Origin"] = "*"
    -            response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS, DELETE"
    -            response.headers[
    -                "Access-Control-Allow-Headers"
    -            ] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
    -
    -            if request.method != "OPTIONS":
    -                # actual request; reply with the actual response
    -                return fn(*args, **kwargs)
    -
    -        if allow_cors:
    -            return _enable_cors
    -        else:
    -            return fn
    -
    -    def handler(self, package, actor, method):
    -        actors = self.client.actors
    -
    -        actor = getattr(actors, f"{package}_{actor}", None)
    -        if not actor:
    -            return self.make_response(400, {"error": "actor not found"})
    -
    -        method = getattr(actor, method, None)
    -        if not method:
    -            return self.make_response(400, {"error": "method not found"})
    -
    -        kwargs = request.json or dict()
    -        response = method(**kwargs)
    -
    -        if not response.success:
    -            if response.error_type == GedisErrorTypes.NOT_FOUND:
    -                return self.make_response(404, {"error": response.error})
    -
    -            elif response.error_type == GedisErrorTypes.BAD_REQUEST:
    -                return self.make_response(400, {"error": response.error})
    -
    -            elif response.error_type == GedisErrorTypes.PERMISSION_ERROR:
    -                return self.make_response(403, {"error": response.error})
    -
    -            else:
    -                return self.make_response(500, {"error": response.error})
    -
    -        return self.make_response(200, response.result)
    -
    -    @property
    -    def gevent_server(self):
    -        return WSGIServer((self.host, self.port), self._app, spawn=Pool())
    -
    -

    Ancestors

    -
      -
    • Base
    • -
    • types.SimpleNamespace
    • -
    -

    Instance variables

    -
    -
    var allow_cors
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    var client
    -
    -
    -
    -Source code -
    @property
    -def client(self):
    -    if self._client is None:
    -        self._client = j.clients.gedis.get(self.instance_name)
    -        self._client.disable_deserialization = True
    -    return self._client
    -
    -
    -
    var gevent_server
    -
    -
    -
    -Source code -
    @property
    -def gevent_server(self):
    -    return WSGIServer((self.host, self.port), self._app, spawn=Pool())
    -
    -
    -
    var host
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    var port
    -
    -

    getter method this property

    -

    will call _get_value, which would if the value is already defined -and will get the default value if not

    -

    Returns

    -
    -
    any
    -
    the field value
    -
    -
    -Source code -
    def getter(self):
    -    """
    -    getter method this property
    -
    -    will call `_get_value`, which would if the value is already defined
    -    and will get the default value if not
    -
    -    Returns:
    -        any: the field value
    -    """
    -    return self._get_value(name, field)
    -
    -
    -
    -

    Methods

    -
    -
    -def enable_cors(self, fn, allow_cors=True) -
    -
    -
    -
    -Source code -
    def enable_cors(self, fn, allow_cors=True):
    -    def _enable_cors(*args, **kwargs):
    -        # set CORS headers
    -        response.headers["Access-Control-Allow-Origin"] = "*"
    -        response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS, DELETE"
    -        response.headers[
    -            "Access-Control-Allow-Headers"
    -        ] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
    -
    -        if request.method != "OPTIONS":
    -            # actual request; reply with the actual response
    -            return fn(*args, **kwargs)
    -
    -    if allow_cors:
    -        return _enable_cors
    -    else:
    -        return fn
    -
    -
    -
    -def handler(self, package, actor, method) -
    -
    -
    -
    -Source code -
    def handler(self, package, actor, method):
    -    actors = self.client.actors
    -
    -    actor = getattr(actors, f"{package}_{actor}", None)
    -    if not actor:
    -        return self.make_response(400, {"error": "actor not found"})
    -
    -    method = getattr(actor, method, None)
    -    if not method:
    -        return self.make_response(400, {"error": "method not found"})
    -
    -    kwargs = request.json or dict()
    -    response = method(**kwargs)
    -
    -    if not response.success:
    -        if response.error_type == GedisErrorTypes.NOT_FOUND:
    -            return self.make_response(404, {"error": response.error})
    -
    -        elif response.error_type == GedisErrorTypes.BAD_REQUEST:
    -            return self.make_response(400, {"error": response.error})
    -
    -        elif response.error_type == GedisErrorTypes.PERMISSION_ERROR:
    -            return self.make_response(403, {"error": response.error})
    -
    -        else:
    -            return self.make_response(500, {"error": response.error})
    -
    -    return self.make_response(200, response.result)
    -
    -
    -
    -def make_response(self, code, content) -
    -
    -
    -
    -Source code -
    def make_response(self, code, content):
    -    response.status = code
    -    response.content_type = "application/json"
    -    return json.dumps(content)
    -
    -
    -
    -

    Inherited members

    - -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/threesdk/container.html b/docs/api/jumpscale/threesdk/container.html deleted file mode 100644 index 510eccd9a..000000000 --- a/docs/api/jumpscale/threesdk/container.html +++ /dev/null @@ -1,385 +0,0 @@ - - - - - - -jumpscale.threesdk.container API documentation - - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.threesdk.container

    -
    -
    -
    - -Expand source code - -
    from jumpscale.clients.docker.docker import DockerClient
    -from jumpscale.core.dirs.dirs import Dirs
    -from jumpscale.core.exceptions import Value
    -from jumpscale.core.executors.local import execute
    -
    -docker_client = DockerClient()
    -
    -
    -class Container:
    -    """Container management
    -    """
    -
    -    @staticmethod
    -    def install(name, image, development: bool = False, volumes=None):
    -        """Creates a container
    -
    -        Args:
    -            name (str): name of the container
    -            image (str): container image.
    -            development (bool, optional): if true will mount codedir. Defaults to False.
    -            volumes (dict, optional): paths to be mounted
    -
    -        Raises:
    -            Value: Container with specified name already exists
    -        """
    -        if docker_client.exists(name):
    -            raise Value("Container with specified name already exists")
    -
    -        volumes = volumes or {}
    -        if development:
    -            volumes = {Dirs.CODEDIR: {"bind": "/sandbox/code", "mode": "rw"}}
    -
    -        print(f"Creating container {name}")
    -        return docker_client.run(name, image, entrypoint="/sbin/my_init", volumes=volumes, detach=True)
    -
    -    @staticmethod
    -    def start(name):
    -        """Starts an existing container
    -
    -        Args:
    -            name (str): name of the container
    -        """
    -        if not docker_client.exists(name):
    -            raise Value("Container with specified name doesn't exist")
    -        docker_client.start(name)
    -
    -    @staticmethod
    -    def exec(name, cmd):
    -        """Execute command in container
    -
    -        Args:
    -            name (str): name of the container
    -            cmd (str or list): command to execute
    -        """
    -        basecmd = ["docker", "exec", "-it", name]
    -        if isinstance(cmd, str):
    -            basecmd.append(cmd)
    -        else:
    -            basecmd += cmd
    -        execute(basecmd, pty=True)
    -
    -    @staticmethod
    -    def stop(name):
    -        """Stops an existing container
    -
    -        Args:
    -            name (str): name of the container
    -        """
    -        if not docker_client.exists(name):
    -            raise Value("Container with specified name doesn't exist")
    -        docker_client.stop(name)
    -
    -    @staticmethod
    -    def delete(name):
    -        Container.stop(name)
    -        docker_client.delete(name)
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Container -
    -
    -

    Container management

    -
    - -Expand source code - -
    class Container:
    -    """Container management
    -    """
    -
    -    @staticmethod
    -    def install(name, image, development: bool = False, volumes=None):
    -        """Creates a container
    -
    -        Args:
    -            name (str): name of the container
    -            image (str): container image.
    -            development (bool, optional): if true will mount codedir. Defaults to False.
    -            volumes (dict, optional): paths to be mounted
    -
    -        Raises:
    -            Value: Container with specified name already exists
    -        """
    -        if docker_client.exists(name):
    -            raise Value("Container with specified name already exists")
    -
    -        volumes = volumes or {}
    -        if development:
    -            volumes = {Dirs.CODEDIR: {"bind": "/sandbox/code", "mode": "rw"}}
    -
    -        print(f"Creating container {name}")
    -        return docker_client.run(name, image, entrypoint="/sbin/my_init", volumes=volumes, detach=True)
    -
    -    @staticmethod
    -    def start(name):
    -        """Starts an existing container
    -
    -        Args:
    -            name (str): name of the container
    -        """
    -        if not docker_client.exists(name):
    -            raise Value("Container with specified name doesn't exist")
    -        docker_client.start(name)
    -
    -    @staticmethod
    -    def exec(name, cmd):
    -        """Execute command in container
    -
    -        Args:
    -            name (str): name of the container
    -            cmd (str or list): command to execute
    -        """
    -        basecmd = ["docker", "exec", "-it", name]
    -        if isinstance(cmd, str):
    -            basecmd.append(cmd)
    -        else:
    -            basecmd += cmd
    -        execute(basecmd, pty=True)
    -
    -    @staticmethod
    -    def stop(name):
    -        """Stops an existing container
    -
    -        Args:
    -            name (str): name of the container
    -        """
    -        if not docker_client.exists(name):
    -            raise Value("Container with specified name doesn't exist")
    -        docker_client.stop(name)
    -
    -    @staticmethod
    -    def delete(name):
    -        Container.stop(name)
    -        docker_client.delete(name)
    -
    -

    Subclasses

    -
      -
    • jumpscale.threesdk.threebot.ThreeBot
    • -
    -

    Static methods

    -
    -
    -def delete(name) -
    -
    -
    -
    - -Expand source code - -
    @staticmethod
    -def delete(name):
    -    Container.stop(name)
    -    docker_client.delete(name)
    -
    -
    -
    -def exec(name, cmd) -
    -
    -

    Execute command in container

    -

    Args

    -
    -
    name : str
    -
    name of the container
    -
    cmd : str or list
    -
    command to execute
    -
    -
    - -Expand source code - -
    @staticmethod
    -def exec(name, cmd):
    -    """Execute command in container
    -
    -    Args:
    -        name (str): name of the container
    -        cmd (str or list): command to execute
    -    """
    -    basecmd = ["docker", "exec", "-it", name]
    -    if isinstance(cmd, str):
    -        basecmd.append(cmd)
    -    else:
    -        basecmd += cmd
    -    execute(basecmd, pty=True)
    -
    -
    -
    -def install(name, image, development: bool = False, volumes=None) -
    -
    -

    Creates a container

    -

    Args

    -
    -
    name : str
    -
    name of the container
    -
    image : str
    -
    container image.
    -
    development : bool, optional
    -
    if true will mount codedir. Defaults to False.
    -
    volumes : dict, optional
    -
    paths to be mounted
    -
    -

    Raises

    -
    -
    Value
    -
    Container with specified name already exists
    -
    -
    - -Expand source code - -
    @staticmethod
    -def install(name, image, development: bool = False, volumes=None):
    -    """Creates a container
    -
    -    Args:
    -        name (str): name of the container
    -        image (str): container image.
    -        development (bool, optional): if true will mount codedir. Defaults to False.
    -        volumes (dict, optional): paths to be mounted
    -
    -    Raises:
    -        Value: Container with specified name already exists
    -    """
    -    if docker_client.exists(name):
    -        raise Value("Container with specified name already exists")
    -
    -    volumes = volumes or {}
    -    if development:
    -        volumes = {Dirs.CODEDIR: {"bind": "/sandbox/code", "mode": "rw"}}
    -
    -    print(f"Creating container {name}")
    -    return docker_client.run(name, image, entrypoint="/sbin/my_init", volumes=volumes, detach=True)
    -
    -
    -
    -def start(name) -
    -
    -

    Starts an existing container

    -

    Args

    -
    -
    name : str
    -
    name of the container
    -
    -
    - -Expand source code - -
    @staticmethod
    -def start(name):
    -    """Starts an existing container
    -
    -    Args:
    -        name (str): name of the container
    -    """
    -    if not docker_client.exists(name):
    -        raise Value("Container with specified name doesn't exist")
    -    docker_client.start(name)
    -
    -
    -
    -def stop(name) -
    -
    -

    Stops an existing container

    -

    Args

    -
    -
    name : str
    -
    name of the container
    -
    -
    - -Expand source code - -
    @staticmethod
    -def stop(name):
    -    """Stops an existing container
    -
    -    Args:
    -        name (str): name of the container
    -    """
    -    if not docker_client.exists(name):
    -        raise Value("Container with specified name doesn't exist")
    -    docker_client.stop(name)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/api/jumpscale/threesdk/identitymanager.html b/docs/api/jumpscale/threesdk/identitymanager.html deleted file mode 100644 index 8f60cf0d0..000000000 --- a/docs/api/jumpscale/threesdk/identitymanager.html +++ /dev/null @@ -1,531 +0,0 @@ - - - - - - -jumpscale.threesdk.identitymanager API documentation - - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.threesdk.identitymanager

    -
    -
    -
    - -Expand source code - -
    import binascii
    -
    -import requests
    -from collections import namedtuple
    -
    -from jumpscale.data.encryption import mnemonic
    -from jumpscale.data.nacl.jsnacl import NACL
    -from jumpscale.data.serializers import base64
    -from jumpscale.core import exceptions
    -from jumpscale.tools.console import ask_choice, ask_string, printcolors
    -
    -NETWORKS = {"mainnet": "explorer.grid.tf", "testnet": "explorer.testnet.grid.tf", "devnet": "explorer.devnet.grid.tf"}
    -
    -RESTART_CHOICE = "Restart from the begining"
    -REENTER_CHOICE = "Re-Enter your value"
    -CHOICES = [RESTART_CHOICE, REENTER_CHOICE]
    -
    -IdentityInfo = namedtuple("IdentityInfo", ["identity", "email", "words", "explorer"])
    -
    -
    -class IdentityManager:
    -    def __init__(self, identity: str = "", email: str = None, words: str = None, explorer: str = None):
    -        self.identity = identity
    -        self.email = email
    -        self.words = words
    -        self.explorer = explorer
    -
    -    def reset(self):
    -        self.identity = ""
    -        self.email = ""
    -        self.words = ""
    -        self.explorer = ""
    -
    -    def _check_keys(self, user_explorer_key, user_app):
    -        if not user_app:
    -            return True
    -        pub_key_app = base64.decode(user_app["publicKey"])
    -        if binascii.unhexlify(user_explorer_key) != pub_key_app:
    -            return False
    -        return True
    -
    -    def _get_user(self):
    -        response = requests.get(f"https://login.threefold.me/api/users/{self.identity}")
    -        if response.status_code == 404:
    -            raise exceptions.Value(
    -                "\nThis identity does not exist in 3bot mobile app connect, Please create an idenity first using 3Bot Connect mobile Application\n"
    -            )
    -        userdata = response.json()
    -
    -        resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"name": self.identity})
    -        if resp.status_code == 404 or resp.json() == []:
    -            # creating new user
    -            user = {}
    -            user["name"] = userdata["doublename"]
    -            user["pubkey"] = base64.decode(userdata["publicKey"]).hex()
    -            printcolors(
    -                f"\nWelcome {{CYAN}}{userdata['doublename']}{{WHITE}}. Creating a new record on {{CYAN}}{self.explorer}{{RESET}}.\n"
    -            )
    -            return user, userdata
    -        else:
    -            users = resp.json()
    -
    -            if not self._check_keys(users[0]["pubkey"], userdata):
    -                raise exceptions.Value(
    -                    f"\nYour 3bot on {self.explorer} seems to have been previously registered with a different public key.\n"
    -                    f"The identity of {self.identity} is mismatched with 3bot connect app"
    -                    "Please contact support.grid.tf to reset it.\n"
    -                    "Note: use the same email registered on the explorer to contact support otherwise we cannot reset the account.\n"
    -                )
    -
    -            if users:
    -                return (users[0], userdata)
    -            return None, userdata
    -
    -    def _check_email(self, email):
    -        resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"email": email})
    -        users = resp.json()
    -        if users:
    -            if users[0]["name"] == self.identity:
    -                return True
    -            else:
    -                return False
    -        else:
    -            return True
    -
    -    def ask_identity(self, identity=None, explorer=None):
    -        def _fill_identity_args(identity, explorer):
    -            def fill_words():
    -                words = ask_string("Copy the phrase from your 3bot Connect app here: ")
    -                self.words = words
    -
    -            def fill_identity():
    -                identity = ask_string("what is your threebot name (identity)? ")
    -                if "." not in identity:
    -                    identity += ".3bot"
    -                self.identity = identity
    -
    -            if identity:
    -                if self.identity != identity and self.identity:
    -                    self.reset()
    -                self.identity = identity
    -
    -            if explorer:
    -                self.explorer = explorer
    -            elif not self.explorer:
    -                response = ask_choice(
    -                    "Which network would you like to register to? ", ["mainnet", "testnet", "devnet", "none"]
    -                )
    -                self.explorer = NETWORKS.get(response, None)
    -            if not self.explorer:
    -                return True
    -
    -            user, user_app = None, None
    -            while not user:
    -                fill_identity()
    -                try:
    -                    user, user_app = self._get_user()
    -                except exceptions.Value as e:
    -                    response = ask_choice(f"{e}What would you like to do? ", CHOICES)
    -                    if response == RESTART_CHOICE:
    -                        return False
    -
    -            while not self.email:
    -                self.email = ask_string("What is the email address associated with your identity? ")
    -                if self._check_email(self.email):
    -                    break
    -                else:
    -                    self.email = None
    -                    response = ask_choice(
    -                        "This email is currently associated with another identity. What would you like to do? ",
    -                        CHOICES,
    -                    )
    -                    if response == RESTART_CHOICE:
    -                        return False
    -
    -            print("Configured email for this identity is {}".format(self.email))
    -
    -            # time to do validation of words
    -            hexkey = None
    -            while True:
    -                if not self.words:
    -                    fill_words()
    -                try:
    -                    seed = mnemonic.mnemonic_to_key(self.words.strip())
    -                    hexkey = NACL(seed).get_verify_key_hex()
    -                    if (user and hexkey != user["pubkey"]) or not self._check_keys(hexkey, user_app):
    -                        raise Exception
    -                    else:
    -                        return True
    -                except Exception:
    -                    choice = ask_choice(
    -                        "\nSeems one or more more words entered is invalid.\nWhat would you like to do? ", CHOICES,
    -                    )
    -                    if choice == RESTART_CHOICE:
    -                        return False
    -                    fill_words()
    -
    -        while True:
    -            if _fill_identity_args(identity, explorer):
    -                identity_info = IdentityInfo(self.identity, self.email, self.words, self.explorer)
    -                return identity_info
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class IdentityInfo -(identity, email, words, explorer) -
    -
    -

    IdentityInfo(identity, email, words, explorer)

    -

    Ancestors

    -
      -
    • builtins.tuple
    • -
    -

    Instance variables

    -
    -
    var email
    -
    -

    Alias for field number 1

    -
    -
    var explorer
    -
    -

    Alias for field number 3

    -
    -
    var identity
    -
    -

    Alias for field number 0

    -
    -
    var words
    -
    -

    Alias for field number 2

    -
    -
    -
    -
    -class IdentityManager -(identity: str = '', email: str = None, words: str = None, explorer: str = None) -
    -
    -
    -
    - -Expand source code - -
    class IdentityManager:
    -    def __init__(self, identity: str = "", email: str = None, words: str = None, explorer: str = None):
    -        self.identity = identity
    -        self.email = email
    -        self.words = words
    -        self.explorer = explorer
    -
    -    def reset(self):
    -        self.identity = ""
    -        self.email = ""
    -        self.words = ""
    -        self.explorer = ""
    -
    -    def _check_keys(self, user_explorer_key, user_app):
    -        if not user_app:
    -            return True
    -        pub_key_app = base64.decode(user_app["publicKey"])
    -        if binascii.unhexlify(user_explorer_key) != pub_key_app:
    -            return False
    -        return True
    -
    -    def _get_user(self):
    -        response = requests.get(f"https://login.threefold.me/api/users/{self.identity}")
    -        if response.status_code == 404:
    -            raise exceptions.Value(
    -                "\nThis identity does not exist in 3bot mobile app connect, Please create an idenity first using 3Bot Connect mobile Application\n"
    -            )
    -        userdata = response.json()
    -
    -        resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"name": self.identity})
    -        if resp.status_code == 404 or resp.json() == []:
    -            # creating new user
    -            user = {}
    -            user["name"] = userdata["doublename"]
    -            user["pubkey"] = base64.decode(userdata["publicKey"]).hex()
    -            printcolors(
    -                f"\nWelcome {{CYAN}}{userdata['doublename']}{{WHITE}}. Creating a new record on {{CYAN}}{self.explorer}{{RESET}}.\n"
    -            )
    -            return user, userdata
    -        else:
    -            users = resp.json()
    -
    -            if not self._check_keys(users[0]["pubkey"], userdata):
    -                raise exceptions.Value(
    -                    f"\nYour 3bot on {self.explorer} seems to have been previously registered with a different public key.\n"
    -                    f"The identity of {self.identity} is mismatched with 3bot connect app"
    -                    "Please contact support.grid.tf to reset it.\n"
    -                    "Note: use the same email registered on the explorer to contact support otherwise we cannot reset the account.\n"
    -                )
    -
    -            if users:
    -                return (users[0], userdata)
    -            return None, userdata
    -
    -    def _check_email(self, email):
    -        resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"email": email})
    -        users = resp.json()
    -        if users:
    -            if users[0]["name"] == self.identity:
    -                return True
    -            else:
    -                return False
    -        else:
    -            return True
    -
    -    def ask_identity(self, identity=None, explorer=None):
    -        def _fill_identity_args(identity, explorer):
    -            def fill_words():
    -                words = ask_string("Copy the phrase from your 3bot Connect app here: ")
    -                self.words = words
    -
    -            def fill_identity():
    -                identity = ask_string("what is your threebot name (identity)? ")
    -                if "." not in identity:
    -                    identity += ".3bot"
    -                self.identity = identity
    -
    -            if identity:
    -                if self.identity != identity and self.identity:
    -                    self.reset()
    -                self.identity = identity
    -
    -            if explorer:
    -                self.explorer = explorer
    -            elif not self.explorer:
    -                response = ask_choice(
    -                    "Which network would you like to register to? ", ["mainnet", "testnet", "devnet", "none"]
    -                )
    -                self.explorer = NETWORKS.get(response, None)
    -            if not self.explorer:
    -                return True
    -
    -            user, user_app = None, None
    -            while not user:
    -                fill_identity()
    -                try:
    -                    user, user_app = self._get_user()
    -                except exceptions.Value as e:
    -                    response = ask_choice(f"{e}What would you like to do? ", CHOICES)
    -                    if response == RESTART_CHOICE:
    -                        return False
    -
    -            while not self.email:
    -                self.email = ask_string("What is the email address associated with your identity? ")
    -                if self._check_email(self.email):
    -                    break
    -                else:
    -                    self.email = None
    -                    response = ask_choice(
    -                        "This email is currently associated with another identity. What would you like to do? ",
    -                        CHOICES,
    -                    )
    -                    if response == RESTART_CHOICE:
    -                        return False
    -
    -            print("Configured email for this identity is {}".format(self.email))
    -
    -            # time to do validation of words
    -            hexkey = None
    -            while True:
    -                if not self.words:
    -                    fill_words()
    -                try:
    -                    seed = mnemonic.mnemonic_to_key(self.words.strip())
    -                    hexkey = NACL(seed).get_verify_key_hex()
    -                    if (user and hexkey != user["pubkey"]) or not self._check_keys(hexkey, user_app):
    -                        raise Exception
    -                    else:
    -                        return True
    -                except Exception:
    -                    choice = ask_choice(
    -                        "\nSeems one or more more words entered is invalid.\nWhat would you like to do? ", CHOICES,
    -                    )
    -                    if choice == RESTART_CHOICE:
    -                        return False
    -                    fill_words()
    -
    -        while True:
    -            if _fill_identity_args(identity, explorer):
    -                identity_info = IdentityInfo(self.identity, self.email, self.words, self.explorer)
    -                return identity_info
    -
    -

    Methods

    -
    -
    -def ask_identity(self, identity=None, explorer=None) -
    -
    -
    -
    - -Expand source code - -
    def ask_identity(self, identity=None, explorer=None):
    -    def _fill_identity_args(identity, explorer):
    -        def fill_words():
    -            words = ask_string("Copy the phrase from your 3bot Connect app here: ")
    -            self.words = words
    -
    -        def fill_identity():
    -            identity = ask_string("what is your threebot name (identity)? ")
    -            if "." not in identity:
    -                identity += ".3bot"
    -            self.identity = identity
    -
    -        if identity:
    -            if self.identity != identity and self.identity:
    -                self.reset()
    -            self.identity = identity
    -
    -        if explorer:
    -            self.explorer = explorer
    -        elif not self.explorer:
    -            response = ask_choice(
    -                "Which network would you like to register to? ", ["mainnet", "testnet", "devnet", "none"]
    -            )
    -            self.explorer = NETWORKS.get(response, None)
    -        if not self.explorer:
    -            return True
    -
    -        user, user_app = None, None
    -        while not user:
    -            fill_identity()
    -            try:
    -                user, user_app = self._get_user()
    -            except exceptions.Value as e:
    -                response = ask_choice(f"{e}What would you like to do? ", CHOICES)
    -                if response == RESTART_CHOICE:
    -                    return False
    -
    -        while not self.email:
    -            self.email = ask_string("What is the email address associated with your identity? ")
    -            if self._check_email(self.email):
    -                break
    -            else:
    -                self.email = None
    -                response = ask_choice(
    -                    "This email is currently associated with another identity. What would you like to do? ",
    -                    CHOICES,
    -                )
    -                if response == RESTART_CHOICE:
    -                    return False
    -
    -        print("Configured email for this identity is {}".format(self.email))
    -
    -        # time to do validation of words
    -        hexkey = None
    -        while True:
    -            if not self.words:
    -                fill_words()
    -            try:
    -                seed = mnemonic.mnemonic_to_key(self.words.strip())
    -                hexkey = NACL(seed).get_verify_key_hex()
    -                if (user and hexkey != user["pubkey"]) or not self._check_keys(hexkey, user_app):
    -                    raise Exception
    -                else:
    -                    return True
    -            except Exception:
    -                choice = ask_choice(
    -                    "\nSeems one or more more words entered is invalid.\nWhat would you like to do? ", CHOICES,
    -                )
    -                if choice == RESTART_CHOICE:
    -                    return False
    -                fill_words()
    -
    -    while True:
    -        if _fill_identity_args(identity, explorer):
    -            identity_info = IdentityInfo(self.identity, self.email, self.words, self.explorer)
    -            return identity_info
    -
    -
    -
    -def reset(self) -
    -
    -
    -
    - -Expand source code - -
    def reset(self):
    -    self.identity = ""
    -    self.email = ""
    -    self.words = ""
    -    self.explorer = ""
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/api/jumpscale/threesdk/index.html b/docs/api/jumpscale/threesdk/index.html deleted file mode 100644 index 6cf3f611c..000000000 --- a/docs/api/jumpscale/threesdk/index.html +++ /dev/null @@ -1,518 +0,0 @@ - - - - - - -jumpscale.threesdk API documentation - - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.threesdk

    -
    -
    -
    - -Expand source code - -
    from .threebot import ThreeBot as threebot
    -import inspect
    -import cgi
    -from prompt_toolkit.formatted_text import HTML
    -from prompt_toolkit.shortcuts import print_formatted_text
    -
    -__all__ = ["threebot", "info"]
    -
    -
    -def info():
    -    print_formatted_text(HTML(_get_doc(__all__)))
    -
    -
    -def _get_doc_line(doc):
    -    if not doc:
    -        return ""
    -    for line in doc.splitlines():
    -        if line.strip():
    -            return line.strip()
    -    return ""
    -
    -
    -def _get_doc(root_module, level=0, size=4):
    -    """get a formatted docstring from a module
    -    this will loop over __all__self.
    -
    -    :param root_module: root module
    -    :type root_module: module
    -    :param level: spacing level, defaults to 0
    -    :type level: int, optional
    -    :param level: spacing size, defaults to 4
    -    :type level: int, optional
    -    :return: docstring
    -    :rtype: str
    -    """
    -
    -    doc = ""
    -
    -    if isinstance(root_module, list):
    -        glob = globals()
    -        members = [(name, glob[name]) for name in root_module]
    -    else:
    -        members = inspect.getmembers(root_module)
    -    for name, obj in members:
    -        if name.startswith("_"):
    -            continue
    -        if name[0].lower() != name[0]:
    -            continue
    -
    -        is_module = not inspect.isroutine(obj)
    -        if is_module and level != 0:
    -            continue
    -
    -        spaces = " " * level
    -
    -        if is_module:
    -            doc += f"{spaces}<ansibrightblue>{name}</ansibrightblue>"
    -        elif getattr(obj, "__property__", False):
    -            doc += f"{spaces}<ansicyan>{name}</ansicyan>"
    -        else:
    -            doc += f"{spaces}<ansigreen>{name}</ansigreen>"
    -
    -        if obj.__doc__:
    -            try:
    -                # only get first line of member docstring
    -                first_line = _get_doc_line(obj.__doc__)
    -                doc += cgi.html.escape(f": {first_line}")
    -            except IndexError:
    -                pass
    -
    -        doc = f"{doc}\n"
    -
    -        if is_module:
    -            doc += _get_doc(obj, level=level + size)
    -
    -    return doc
    -
    -
    -
    -

    Sub-modules

    -
    -
    jumpscale.threesdk.container
    -
    -
    -
    -
    jumpscale.threesdk.identitymanager
    -
    -
    -
    -
    jumpscale.threesdk.settings
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def info() -
    -
    -
    -
    - -Expand source code - -
    def info():
    -    print_formatted_text(HTML(_get_doc(__all__)))
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class threebot -
    -
    -

    Manage your threebot

    -
    - -Expand source code - -
    class ThreeBot(Container):
    -    """
    -    Manage your threebot
    -    """
    -
    -    @staticmethod
    -    def install(
    -        name=None, image=None, identity=None, email=None, words=None, explorer=None, development: bool = None,
    -    ):
    -        """Creates a threebot container
    -
    -        Args:
    -            name (str, optional): name of the container. Defaults to 3bot-ng
    -            image (str, optional): container image. Defaults to "threefoldtech/js-ng:latest".
    -            identity (str, optional): threebot name. Defaults to None.
    -            email (str, optional): threebot email. Defaults to None.
    -            words (str, optional): seed phrase of the user. Defaults to None.
    -            explorer (str, optional): which explorer network to use: mainnet, testnet, devnet. Defaults to None.
    -            development (bool, optional): if true will mount codedir. Defaults to False.
    -
    -        Raises:
    -            Value: Container with specified name already exists
    -            Value: explorer not in mainnet, testnet, devnet
    -        """
    -        if development is None:
    -            development = settings.expert
    -        name = name or DEFAULT_CONTAINER_NAME
    -        current_version = get_current_version()
    -        image = image or f"{DEFAULT_IMAGE}:{current_version}"
    -
    -        pers_path = f"{PERSISTENT_STORE}/{name}"
    -        configure = not os.path.exists(pers_path)
    -        if configure:
    -            identity = IdentityManager(identity, email, words, explorer)
    -            identity, email, words, explorer = identity.ask_identity()
    -
    -        os.makedirs(PERSISTENT_STORE, exist_ok=True)
    -        volumes = {pers_path: {"bind": "/root/.config/jumpscale", "mode": "rw"}}
    -
    -        container = Container.install(name, image, development, volumes)
    -        container.exec_run(["redis-server", "--daemonize yes"])
    -
    -        if configure:
    -            container.exec_run(["jsng", f"j.core.identity.new('default', '{identity}', '{email}', '{words}')"])
    -            container.exec_run(["jsng", "j.core.identity.set_default('default')"])
    -
    -    @staticmethod
    -    def jsng(name=DEFAULT_CONTAINER_NAME):
    -        """Get's shell in threebot
    -
    -        Args:
    -            name (str): name of the container (default: 3bot-ng)
    -        """
    -        Container.exec(name, "jsng")
    -
    -    @staticmethod
    -    def shell(name=DEFAULT_CONTAINER_NAME):
    -        """Get's shell in threebot
    -
    -        Args:
    -            name (str): name of the container (default: 3bot-ng)
    -        """
    -        Container.exec(name, "bash")
    -
    -    @staticmethod
    -    def start(name=DEFAULT_CONTAINER_NAME):
    -        """Start threebot container with threebot server
    -
    -        Args:
    -            name (str): name of the container (default: 3bot-ng)
    -        """
    -        Container.start(name)
    -        Container.exec(name, ["threebot", "start", "--background"])
    -
    -    @staticmethod
    -    def stop(name=DEFAULT_CONTAINER_NAME):
    -        """Stop threebot installation with container
    -
    -        Args:
    -            name (str): name of the container (default: 3bot-ng)
    -        """
    -        if name in docker_client.list():
    -            Container.exec(name, ["threebot", "stop"])
    -            Container.stop(name)
    -        else:
    -            print("Container is already stopped")
    -
    -    @staticmethod
    -    def restart(name=DEFAULT_CONTAINER_NAME):
    -        """restart threebot installation with container
    -
    -        Args:
    -            name (str): name of the container (default: 3bot-ng)
    -        """
    -        ThreeBot.stop(name=name)
    -        ThreeBot.start(name=name)
    -
    -

    Ancestors

    - -

    Static methods

    -
    -
    -def install(name=None, image=None, identity=None, email=None, words=None, explorer=None, development: bool = None) -
    -
    -

    Creates a threebot container

    -

    Args

    -
    -
    name : str, optional
    -
    name of the container. Defaults to 3bot-ng
    -
    image : str, optional
    -
    container image. Defaults to "threefoldtech/js-ng:latest".
    -
    identity : str, optional
    -
    threebot name. Defaults to None.
    -
    email : str, optional
    -
    threebot email. Defaults to None.
    -
    words : str, optional
    -
    seed phrase of the user. Defaults to None.
    -
    explorer : str, optional
    -
    which explorer network to use: mainnet, testnet, devnet. Defaults to None.
    -
    development : bool, optional
    -
    if true will mount codedir. Defaults to False.
    -
    -

    Raises

    -
    -
    Value
    -
    Container with specified name already exists
    -
    Value
    -
    explorer not in mainnet, testnet, devnet
    -
    -
    - -Expand source code - -
    @staticmethod
    -def install(
    -    name=None, image=None, identity=None, email=None, words=None, explorer=None, development: bool = None,
    -):
    -    """Creates a threebot container
    -
    -    Args:
    -        name (str, optional): name of the container. Defaults to 3bot-ng
    -        image (str, optional): container image. Defaults to "threefoldtech/js-ng:latest".
    -        identity (str, optional): threebot name. Defaults to None.
    -        email (str, optional): threebot email. Defaults to None.
    -        words (str, optional): seed phrase of the user. Defaults to None.
    -        explorer (str, optional): which explorer network to use: mainnet, testnet, devnet. Defaults to None.
    -        development (bool, optional): if true will mount codedir. Defaults to False.
    -
    -    Raises:
    -        Value: Container with specified name already exists
    -        Value: explorer not in mainnet, testnet, devnet
    -    """
    -    if development is None:
    -        development = settings.expert
    -    name = name or DEFAULT_CONTAINER_NAME
    -    current_version = get_current_version()
    -    image = image or f"{DEFAULT_IMAGE}:{current_version}"
    -
    -    pers_path = f"{PERSISTENT_STORE}/{name}"
    -    configure = not os.path.exists(pers_path)
    -    if configure:
    -        identity = IdentityManager(identity, email, words, explorer)
    -        identity, email, words, explorer = identity.ask_identity()
    -
    -    os.makedirs(PERSISTENT_STORE, exist_ok=True)
    -    volumes = {pers_path: {"bind": "/root/.config/jumpscale", "mode": "rw"}}
    -
    -    container = Container.install(name, image, development, volumes)
    -    container.exec_run(["redis-server", "--daemonize yes"])
    -
    -    if configure:
    -        container.exec_run(["jsng", f"j.core.identity.new('default', '{identity}', '{email}', '{words}')"])
    -        container.exec_run(["jsng", "j.core.identity.set_default('default')"])
    -
    -
    -
    -def jsng(name='3bot-ng') -
    -
    -

    Get's shell in threebot

    -

    Args

    -
    -
    name : str
    -
    name of the container (default: 3bot-ng)
    -
    -
    - -Expand source code - -
    @staticmethod
    -def jsng(name=DEFAULT_CONTAINER_NAME):
    -    """Get's shell in threebot
    -
    -    Args:
    -        name (str): name of the container (default: 3bot-ng)
    -    """
    -    Container.exec(name, "jsng")
    -
    -
    -
    -def restart(name='3bot-ng') -
    -
    -

    restart threebot installation with container

    -

    Args

    -
    -
    name : str
    -
    name of the container (default: 3bot-ng)
    -
    -
    - -Expand source code - -
    @staticmethod
    -def restart(name=DEFAULT_CONTAINER_NAME):
    -    """restart threebot installation with container
    -
    -    Args:
    -        name (str): name of the container (default: 3bot-ng)
    -    """
    -    ThreeBot.stop(name=name)
    -    ThreeBot.start(name=name)
    -
    -
    -
    -def shell(name='3bot-ng') -
    -
    -

    Get's shell in threebot

    -

    Args

    -
    -
    name : str
    -
    name of the container (default: 3bot-ng)
    -
    -
    - -Expand source code - -
    @staticmethod
    -def shell(name=DEFAULT_CONTAINER_NAME):
    -    """Get's shell in threebot
    -
    -    Args:
    -        name (str): name of the container (default: 3bot-ng)
    -    """
    -    Container.exec(name, "bash")
    -
    -
    -
    -def start(name='3bot-ng') -
    -
    -

    Start threebot container with threebot server

    -

    Args

    -
    -
    name : str
    -
    name of the container (default: 3bot-ng)
    -
    -
    - -Expand source code - -
    @staticmethod
    -def start(name=DEFAULT_CONTAINER_NAME):
    -    """Start threebot container with threebot server
    -
    -    Args:
    -        name (str): name of the container (default: 3bot-ng)
    -    """
    -    Container.start(name)
    -    Container.exec(name, ["threebot", "start", "--background"])
    -
    -
    -
    -def stop(name='3bot-ng') -
    -
    -

    Stop threebot installation with container

    -

    Args

    -
    -
    name : str
    -
    name of the container (default: 3bot-ng)
    -
    -
    - -Expand source code - -
    @staticmethod
    -def stop(name=DEFAULT_CONTAINER_NAME):
    -    """Stop threebot installation with container
    -
    -    Args:
    -        name (str): name of the container (default: 3bot-ng)
    -    """
    -    if name in docker_client.list():
    -        Container.exec(name, ["threebot", "stop"])
    -        Container.stop(name)
    -    else:
    -        print("Container is already stopped")
    -
    -
    -
    -

    Inherited members

    - -
    -
    -
    -
    - -
    - - - diff --git a/docs/api/jumpscale/threesdk/settings.html b/docs/api/jumpscale/threesdk/settings.html deleted file mode 100644 index 02559f717..000000000 --- a/docs/api/jumpscale/threesdk/settings.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - -jumpscale.threesdk.settings API documentation - - - - - - - - - - - -
    -
    -
    -

    Module jumpscale.threesdk.settings

    -
    -
    -
    - -Expand source code - -
    expert = False
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - diff --git a/docs/api/jumpscale/tools/console/console.html b/docs/api/jumpscale/tools/console/console.html deleted file mode 100644 index 7ffb52530..000000000 --- a/docs/api/jumpscale/tools/console/console.html +++ /dev/null @@ -1,689 +0,0 @@ - - - - - - -jumpscale.tools.console.console API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.console.console

    -
    -
    -

    Console module helps with coloring in the console and asking for input from the user.

    -
    JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{WHITE}OK")                                                                     
    -JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{RESET}{WHITE}OK")                                                              
    -
    -
    -Source code -
    """Console module helps with coloring in the console and asking for input from the user.
    -```
    -JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{WHITE}OK")                                                                     
    -JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{RESET}{WHITE}OK")                                                              
    -```
    -
    -"""
    -
    -
    -import colorama
    -import getpass
    -import os
    -
    -<<<<<<< HEAD
    -"""
    -JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{WHITE}OK")                                                                     
    -JS-NG> j.tools.console.printcolors("{RED}Hello{BGRED}What{RESET}{WHITE}OK")                                                              
    -"""
    -=======
    ->>>>>>> development
    -
    -NAMES_TO_COLORS = {}
    -for attrname in dir(colorama.Fore):
    -    if attrname.isupper():
    -        NAMES_TO_COLORS[attrname] = getattr(colorama.Fore, attrname)
    -
    -for attrname in dir(colorama.Back):
    -    if attrname.isupper():
    -        NAMES_TO_COLORS["BG" + attrname] = getattr(colorama.Back, attrname)
    -
    -NAMES_TO_COLORS["RESET"] = colorama.Style.RESET_ALL
    -
    -
    -def format(s):
    -    return s.format(**NAMES_TO_COLORS)
    -
    -
    -def printcolors(s):
    -    """
    -        >>> j.tools.console.printcolors("{RED}Hello world")
    -        Hello world
    -        >>> j.tools.console.printcolors("{GREEN}Hello world")
    -        Hello world
    -
    -        Arguments:
    -        s {[type]} -- [description]
    -        """
    -    print(format(s))
    -
    -
    -def ask_password(prompt="Password : ", forbiddens=[]):
    -    """Prompt the user for a password without echoing
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Password : "})
    -        forbiddens {list} -- the list of bad passwords (default: {[]})
    -    
    -    Returns:
    -        str -- the appropriate input password
    -    """
    -    password = getpass.getpass(prompt)
    -    if password not in forbiddens:
    -        return password
    -    else:
    -        return ask_password(prompt, forbiddens)
    -
    -
    -def ask_yes_no(prompt="[y/n] :", default="y", valid=["y", "n"]):
    -    """Display a yes/no question and loop until a valid answer is entered
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {'[y/n] :'})
    -        default {str} -- the default answer if there is no answer (default: {"y"})
    -        valid {list} -- the list of appropriate answers (default: {["y", "n"]})
    -    
    -    Returns:
    -        str -- the answer
    -    """
    -
    -    answer = input(prompt)
    -    if answer in valid:
    -        return answer
    -    elif answer == "":
    -        return default
    -    else:
    -        return ask_yes_no(prompt, default, valid)
    -
    -
    -def ask_int(prompt="Type int :"):
    -    try:
    -        return int(input(prompt))
    -    except ValueError:
    -        return ask_int(prompt)
    -
    -
    -def ask_int_in_range(mini, maxi, prompt="Type int :"):
    -    """Get an integer response between two integer on asked question
    -    
    -    Arguments:
    -        mini {int} -- the minimum value for the number
    -        maxi {int} -- the maximum value for the number
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type int :"})
    -    
    -    Returns:
    -        int -- the input number on the range provided
    -    """
    -    try:
    -        answer = int(input(prompt))
    -        if mini <= answer <= maxi:
    -            return answer
    -        else:
    -            return ask_int_in_range(mini, maxi, prompt)
    -    except ValueError:
    -        return ask_int_in_range(mini, maxi, prompt)
    -
    -
    -def ask_float(prompt="Type float :"):
    -    try:
    -        return float(input(prompt))
    -    except ValueError:
    -        return ask_float(prompt)
    -
    -
    -def ask_float_in_range(mini, maxi, prompt="Type float :"):
    -    """Get an float response between two float on asked question
    -    
    -    Arguments:
    -        mini {float} -- the minimum value for the number
    -        maxi {float} -- the maximum value for the number
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type float :"})
    -    
    -    Returns:
    -        float -- the input number on the range provided
    -    """
    -    try:
    -        answer = float(input(prompt))
    -        if mini <= answer <= maxi:
    -            return answer
    -        else:
    -            return ask_float_in_range(mini, maxi, prompt)
    -    except ValueError:
    -        return ask_float_in_range(mini, maxi, prompt)
    -
    -
    -def _print_choices(choices_list):
    -    """Helper function : clear screen and print the choices in numbers"""
    -    os.system("clear")
    -    number = 0
    -    for choice in choices_list:
    -        number += 1
    -        print(f"{number}. " + choice)
    -
    -
    -def ask_choice(prompt="Type choice number : ", choices_list=[]):
    -    """Get an option from provided list
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type choice number : "})
    -        choices_list {list} -- the available options (default: {[]})
    -    
    -    Returns:
    -        str -- the chosen option
    -    """
    -    _print_choices(choices_list)
    -    answer = input(prompt)
    -    try:
    -        return choices_list[int(answer) - 1]
    -    except (IndexError, ValueError):
    -        return ask_choice(prompt, choices_list)
    -
    -
    -def ask_multi_choices(prompt="Add to choices : ", choices_list=[], to_save="s", to_quit="q"):
    -    """Collect multi choices from list
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question method (default: {"Add to choices : "})
    -        choices_list {list} -- the available options (default: {[]})
    -        to_save {str} -- escape and save choices (default: {"s"})
    -        to_quit {str} -- escape without saving (default: {"q"})
    -    
    -    Returns:
    -        list -- list of the selected choices
    -    """
    -    selected_choices = []
    -    print(f"'{to_save}' to save and '{to_quit}' to quit")
    -    _print_choices(choices_list)
    -
    -    while True:
    -        answer = input(prompt)
    -        if answer == to_quit:
    -            return []
    -        elif answer == to_save or answer == "":
    -            return selected_choices
    -        else:
    -            try:
    -                selected_choices.append(choices_list[int(answer) - 1])
    -            except (IndexError, ValueError):
    -                return ask_multi_choices(prompt, choices_list, to_save, to_quit)
    -
    -
    -def ask_multi_lines(prompt="Type :", escape_string="."):
    -    """Get input from user provided multilines
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type :"})
    -        escape_string {str} -- escape character (default: {"."})
    -    
    -    Returns:
    -        str -- the text seperated by lines
    -    """
    -    text = []
    -    user_input = input(prompt)
    -    while user_input != escape_string:
    -        text.append(user_input)
    -        user_input = input(prompt)
    -    return "\n".join(text)
    -
    -
    -def ask_string(prompt="Type :"):
    -    """Just input function
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type :"})
    -    
    -    Returns:
    -        str -- the string input
    -    """
    -    return input(prompt)
    -
    -    print(format(s))
    -
    -
    -def printobj(obj):
    -    from pprint import pprint
    -
    -    pprint(obj)
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def ask_choice(prompt='Type choice number : ', choices_list=[]) -
    -
    -

    Get an option from provided list

    -

    Keyword Arguments: -prompt {str} – the question message (default: {"Type choice number : "}) -choices_list {list} – the available options (default: {[]})

    -

    Returns

    -
    -
    strthe chosen option
    -
     
    -
    -
    -Source code -
    def ask_choice(prompt="Type choice number : ", choices_list=[]):
    -    """Get an option from provided list
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type choice number : "})
    -        choices_list {list} -- the available options (default: {[]})
    -    
    -    Returns:
    -        str -- the chosen option
    -    """
    -    _print_choices(choices_list)
    -    answer = input(prompt)
    -    try:
    -        return choices_list[int(answer) - 1]
    -    except (IndexError, ValueError):
    -        return ask_choice(prompt, choices_list)
    -
    -
    -
    -def ask_float(prompt='Type float :') -
    -
    -
    -
    -Source code -
    def ask_float(prompt="Type float :"):
    -    try:
    -        return float(input(prompt))
    -    except ValueError:
    -        return ask_float(prompt)
    -
    -
    -
    -def ask_float_in_range(mini, maxi, prompt='Type float :') -
    -
    -

    Get an float response between two float on asked question

    -

    Arguments

    -

    mini {float} – the minimum value for the number -maxi {float} – the maximum value for the number -Keyword Arguments: -prompt {str} – the question message (default: {"Type float :"})

    -

    Returns

    -
    -
    floatthe input number on the range provided
    -
     
    -
    -
    -Source code -
    def ask_float_in_range(mini, maxi, prompt="Type float :"):
    -    """Get an float response between two float on asked question
    -    
    -    Arguments:
    -        mini {float} -- the minimum value for the number
    -        maxi {float} -- the maximum value for the number
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type float :"})
    -    
    -    Returns:
    -        float -- the input number on the range provided
    -    """
    -    try:
    -        answer = float(input(prompt))
    -        if mini <= answer <= maxi:
    -            return answer
    -        else:
    -            return ask_float_in_range(mini, maxi, prompt)
    -    except ValueError:
    -        return ask_float_in_range(mini, maxi, prompt)
    -
    -
    -
    -def ask_int(prompt='Type int :') -
    -
    -
    -
    -Source code -
    def ask_int(prompt="Type int :"):
    -    try:
    -        return int(input(prompt))
    -    except ValueError:
    -        return ask_int(prompt)
    -
    -
    -
    -def ask_int_in_range(mini, maxi, prompt='Type int :') -
    -
    -

    Get an integer response between two integer on asked question

    -

    Arguments

    -

    mini {int} – the minimum value for the number -maxi {int} – the maximum value for the number -Keyword Arguments: -prompt {str} – the question message (default: {"Type int :"})

    -

    Returns

    -
    -
    intthe input number on the range provided
    -
     
    -
    -
    -Source code -
    def ask_int_in_range(mini, maxi, prompt="Type int :"):
    -    """Get an integer response between two integer on asked question
    -    
    -    Arguments:
    -        mini {int} -- the minimum value for the number
    -        maxi {int} -- the maximum value for the number
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type int :"})
    -    
    -    Returns:
    -        int -- the input number on the range provided
    -    """
    -    try:
    -        answer = int(input(prompt))
    -        if mini <= answer <= maxi:
    -            return answer
    -        else:
    -            return ask_int_in_range(mini, maxi, prompt)
    -    except ValueError:
    -        return ask_int_in_range(mini, maxi, prompt)
    -
    -
    -
    -def ask_multi_choices(prompt='Add to choices : ', choices_list=[], to_save='s', to_quit='q') -
    -
    -

    Collect multi choices from list

    -

    Keyword Arguments: -prompt {str} – the question method (default: {"Add to choices : "}) -choices_list {list} – the available options (default: {[]}) -to_save {str} – escape and save choices (default: {"s"}) -to_quit {str} – escape without saving (default: {"q"})

    -

    Returns

    -
    -
    listlist of the selected choices
    -
     
    -
    -
    -Source code -
    def ask_multi_choices(prompt="Add to choices : ", choices_list=[], to_save="s", to_quit="q"):
    -    """Collect multi choices from list
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question method (default: {"Add to choices : "})
    -        choices_list {list} -- the available options (default: {[]})
    -        to_save {str} -- escape and save choices (default: {"s"})
    -        to_quit {str} -- escape without saving (default: {"q"})
    -    
    -    Returns:
    -        list -- list of the selected choices
    -    """
    -    selected_choices = []
    -    print(f"'{to_save}' to save and '{to_quit}' to quit")
    -    _print_choices(choices_list)
    -
    -    while True:
    -        answer = input(prompt)
    -        if answer == to_quit:
    -            return []
    -        elif answer == to_save or answer == "":
    -            return selected_choices
    -        else:
    -            try:
    -                selected_choices.append(choices_list[int(answer) - 1])
    -            except (IndexError, ValueError):
    -                return ask_multi_choices(prompt, choices_list, to_save, to_quit)
    -
    -
    -
    -def ask_multi_lines(prompt='Type :', escape_string='.') -
    -
    -

    Get input from user provided multilines

    -

    Keyword Arguments: -prompt {str} – the question message (default: {"Type :"}) -escape_string {str} – escape character (default: {"."})

    -

    Returns

    -
    -
    strthe text seperated by lines
    -
     
    -
    -
    -Source code -
    def ask_multi_lines(prompt="Type :", escape_string="."):
    -    """Get input from user provided multilines
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type :"})
    -        escape_string {str} -- escape character (default: {"."})
    -    
    -    Returns:
    -        str -- the text seperated by lines
    -    """
    -    text = []
    -    user_input = input(prompt)
    -    while user_input != escape_string:
    -        text.append(user_input)
    -        user_input = input(prompt)
    -    return "\n".join(text)
    -
    -
    -
    -def ask_password(prompt='Password : ', forbiddens=[]) -
    -
    -

    Prompt the user for a password without echoing

    -

    Keyword Arguments: -prompt {str} – the question message (default: {"Password : "}) -forbiddens {list} – the list of bad passwords (default: {[]})

    -

    Returns

    -
    -
    strthe appropriate input password
    -
     
    -
    -
    -Source code -
    def ask_password(prompt="Password : ", forbiddens=[]):
    -    """Prompt the user for a password without echoing
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Password : "})
    -        forbiddens {list} -- the list of bad passwords (default: {[]})
    -    
    -    Returns:
    -        str -- the appropriate input password
    -    """
    -    password = getpass.getpass(prompt)
    -    if password not in forbiddens:
    -        return password
    -    else:
    -        return ask_password(prompt, forbiddens)
    -
    -
    -
    -def ask_string(prompt='Type :') -
    -
    -

    Just input function

    -

    Keyword Arguments: -prompt {str} – the question message (default: {"Type :"})

    -

    Returns

    -
    -
    strthe string input
    -
     
    -
    -
    -Source code -
    def ask_string(prompt="Type :"):
    -    """Just input function
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {"Type :"})
    -    
    -    Returns:
    -        str -- the string input
    -    """
    -    return input(prompt)
    -
    -    print(format(s))
    -
    -
    -
    -def ask_yes_no(prompt='[y/n] :', default='y', valid=['y', 'n']) -
    -
    -

    Display a yes/no question and loop until a valid answer is entered

    -

    Keyword Arguments: -prompt {str} – the question message (default: {'[y/n] :'}) -default {str} – the default answer if there is no answer (default: {"y"}) -valid {list} – the list of appropriate answers (default: {["y", "n"]})

    -

    Returns

    -
    -
    strthe answer
    -
     
    -
    -
    -Source code -
    def ask_yes_no(prompt="[y/n] :", default="y", valid=["y", "n"]):
    -    """Display a yes/no question and loop until a valid answer is entered
    -    
    -    Keyword Arguments:
    -        prompt {str} -- the question message (default: {'[y/n] :'})
    -        default {str} -- the default answer if there is no answer (default: {"y"})
    -        valid {list} -- the list of appropriate answers (default: {["y", "n"]})
    -    
    -    Returns:
    -        str -- the answer
    -    """
    -
    -    answer = input(prompt)
    -    if answer in valid:
    -        return answer
    -    elif answer == "":
    -        return default
    -    else:
    -        return ask_yes_no(prompt, default, valid)
    -
    -
    -
    -def format(s) -
    -
    -
    -
    -Source code -
    def format(s):
    -    return s.format(**NAMES_TO_COLORS)
    -
    -
    -
    -def printcolors(s) -
    -
    -
    >>> j.tools.console.printcolors("{RED}Hello world")
    -Hello world
    ->>> j.tools.console.printcolors("{GREEN}Hello world")
    -Hello world
    -
    -

    Arguments: -s {[type]} – [description]

    -
    -Source code -
    def printcolors(s):
    -    """
    -        >>> j.tools.console.printcolors("{RED}Hello world")
    -        Hello world
    -        >>> j.tools.console.printcolors("{GREEN}Hello world")
    -        Hello world
    -
    -        Arguments:
    -        s {[type]} -- [description]
    -        """
    -    print(format(s))
    -
    -
    -
    -def printobj(obj) -
    -
    -
    -
    -Source code -
    def printobj(obj):
    -    from pprint import pprint
    -
    -    pprint(obj)
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/dnstool/index.html b/docs/api/jumpscale/tools/dnstool/index.html deleted file mode 100644 index 1a0e1883e..000000000 --- a/docs/api/jumpscale/tools/dnstool/index.html +++ /dev/null @@ -1,197 +0,0 @@ - - - - - - -jumpscale.tools.dnstool API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.dnstool

    -
    -
    -

    Helper to get nameservers information and resolving domains.

    -
    -Source code -
    """
    -Helper to get nameservers information and resolving domains.
    -
    -"""
    -# TODO: update code
    -
    -
    -try:
    -    import dns
    -    import dns.message
    -    import dns.rdataclass
    -    import dns.rdatatype
    -    import dns.query
    -    import dns.resolver
    -
    -except ImportError as e:
    -    print("WARNING install dnspython: 'pip3 install dnspython'")
    -
    -
    -class DNSClient:
    -    def __init__(self, nameservers=None, port=53):
    -        self.nameservers = nameservers or ["8.8.8.8", "8.8.4.4"]
    -        if "localhost" in self.nameservers:
    -            nameservers.pop(nameservers.index("localhost"))
    -            nameservers.append("127.0.0.1")
    -        self.resolver = dns.resolver.Resolver(configure=False)
    -        self.resolver.nameservers = self.nameservers
    -        self.resolver.port = port
    -
    -    def nameservers_get(self, domain="threefoldtoken.org"):
    -        answer = self.resolver.query(domain, "NS")
    -
    -        res = []
    -        for rr in answer:
    -            res.append(rr.target.to_text())
    -        return res
    -
    -    def namerecords_get(self, url="www.threefoldtoken.org"):
    -        """
    -        return ip addr for a full name
    -        """
    -        answer = self.resolver.query(url, "A")
    -
    -        res = []
    -        for rr in answer:
    -            res.append(rr.address)
    -        return res
    -
    -
    -resolver = DNSClient()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class DNSClient -(nameservers=None, port=53) -
    -
    -
    -
    -Source code -
    class DNSClient:
    -    def __init__(self, nameservers=None, port=53):
    -        self.nameservers = nameservers or ["8.8.8.8", "8.8.4.4"]
    -        if "localhost" in self.nameservers:
    -            nameservers.pop(nameservers.index("localhost"))
    -            nameservers.append("127.0.0.1")
    -        self.resolver = dns.resolver.Resolver(configure=False)
    -        self.resolver.nameservers = self.nameservers
    -        self.resolver.port = port
    -
    -    def nameservers_get(self, domain="threefoldtoken.org"):
    -        answer = self.resolver.query(domain, "NS")
    -
    -        res = []
    -        for rr in answer:
    -            res.append(rr.target.to_text())
    -        return res
    -
    -    def namerecords_get(self, url="www.threefoldtoken.org"):
    -        """
    -        return ip addr for a full name
    -        """
    -        answer = self.resolver.query(url, "A")
    -
    -        res = []
    -        for rr in answer:
    -            res.append(rr.address)
    -        return res
    -
    -

    Methods

    -
    -
    -def namerecords_get(self, url='www.threefoldtoken.org') -
    -
    -

    return ip addr for a full name

    -
    -Source code -
    def namerecords_get(self, url="www.threefoldtoken.org"):
    -    """
    -    return ip addr for a full name
    -    """
    -    answer = self.resolver.query(url, "A")
    -
    -    res = []
    -    for rr in answer:
    -        res.append(rr.address)
    -    return res
    -
    -
    -
    -def nameservers_get(self, domain='threefoldtoken.org') -
    -
    -
    -
    -Source code -
    def nameservers_get(self, domain="threefoldtoken.org"):
    -    answer = self.resolver.query(domain, "NS")
    -
    -    res = []
    -    for rr in answer:
    -        res.append(rr.target.to_text())
    -    return res
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/imagelib/imagelib.html b/docs/api/jumpscale/tools/imagelib/imagelib.html deleted file mode 100644 index 46d46768c..000000000 --- a/docs/api/jumpscale/tools/imagelib/imagelib.html +++ /dev/null @@ -1,302 +0,0 @@ - - - - - - -jumpscale.tools.imagelib.imagelib API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.imagelib.imagelib

    -
    -
    -
    -Source code -
    import os
    -from PIL import Image
    -
    -
    -def get_list_files(dir_name):
    -    """returns a list of directories for all image files in a root folder
    -
    -    Arguments:
    -        dir_name (str) : the directory of the root folder
    -
    -    Returns:
    -        all_files (list) : the list of directories for all files in the root folder
    -    """
    -    # create a list of file and sub directories
    -    # names in the given directory
    -    files_list = os.listdir(dir_name)
    -    all_files = list()
    -    # Iterate over all the entries
    -    for entry in files_list:
    -        # Create full path
    -        full_path = os.path.join(dir_name, entry)
    -        # If entry is a directory then get the list of files in this directory
    -        if os.path.isdir(full_path):
    -            all_files = all_files + get_list_files(full_path)
    -        else:
    -            path_split = os.path.splitext(full_path)
    -            if path_split[1] in [".jpg", ".jpeg", ".png"]:
    -                all_files.append(full_path)
    -
    -    return all_files
    -
    -
    -def get_image(path):
    -    """returns an PIL.Image object by path
    -    
    -    Arguments:
    -        path (string) : the image path
    -    
    -    Returns:
    -        PIL.Image object
    -    """
    -    return Image.open(path)
    -
    -
    -def resize(path, pathnew, width=1024):
    -    """resize an image 
    -    
    -    Arguments:
    -        path (string) : the path of the image will be resized
    -        pathnew (string) : the path of new resized image
    -    
    -    Keyword Arguments:
    -        width (int) : the width of the new image , hieght is depending on it
    -    
    -    Returns:
    -        (string) : True if image resized successfully or the exception message if not
    -    """
    -    im = get_image(path)
    -    xnew = width
    -    x, y = im.size
    -    ynew = int(float(y) / (float(x) / float(xnew)))
    -    imnew = im.resize((xnew, ynew), Image.ANTIALIAS)
    -    try:
    -        imnew.save(pathnew)
    -        return "True"
    -    except Exception as e:
    -        return str(e)
    -
    -
    -def resize_images_in_dir(folder, foldernew, width=1024):
    -    """resize images in folder
    -    
    -    Arguments:
    -        folder (string) : the path of the root folder in which images will be resized
    -        foldernew (string) : the path of the folder in which new images will be stored
    -    
    -    Keyword Arguments:
    -        width (int) : the width of the new images , hieght is depending on it
    -    
    -    Returns:
    -        (dict) : a dict with img path as key and its statue as value
    -            statue : True if image resized successfully or the exception message if not
    -    """
    -    img_list = get_list_files(folder)
    -    print(img_list)
    -    img_statue = {}
    -    for img in img_list:
    -        statue = resize(img, os.path.join(foldernew, os.path.basename(img)), width=width)
    -        img_statue[img] = statue
    -    return img_statue
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def get_image(path) -
    -
    -

    returns an PIL.Image object by path

    -

    Arguments

    -

    path (string) : the image path

    -

    Returns

    -
    -
    PIL.Image object
    -
     
    -
    -
    -Source code -
    def get_image(path):
    -    """returns an PIL.Image object by path
    -    
    -    Arguments:
    -        path (string) : the image path
    -    
    -    Returns:
    -        PIL.Image object
    -    """
    -    return Image.open(path)
    -
    -
    -
    -def get_list_files(dir_name) -
    -
    -

    returns a list of directories for all image files in a root folder

    -

    Arguments

    -

    dir_name (str) : the directory of the root folder

    -

    Returns

    -
    -
    all_files (list) : the list of directories for all files in the root folder
    -
     
    -
    -
    -Source code -
    def get_list_files(dir_name):
    -    """returns a list of directories for all image files in a root folder
    -
    -    Arguments:
    -        dir_name (str) : the directory of the root folder
    -
    -    Returns:
    -        all_files (list) : the list of directories for all files in the root folder
    -    """
    -    # create a list of file and sub directories
    -    # names in the given directory
    -    files_list = os.listdir(dir_name)
    -    all_files = list()
    -    # Iterate over all the entries
    -    for entry in files_list:
    -        # Create full path
    -        full_path = os.path.join(dir_name, entry)
    -        # If entry is a directory then get the list of files in this directory
    -        if os.path.isdir(full_path):
    -            all_files = all_files + get_list_files(full_path)
    -        else:
    -            path_split = os.path.splitext(full_path)
    -            if path_split[1] in [".jpg", ".jpeg", ".png"]:
    -                all_files.append(full_path)
    -
    -    return all_files
    -
    -
    -
    -def resize(path, pathnew, width=1024) -
    -
    -

    resize an image

    -

    Arguments

    -

    path (string) : the path of the image will be resized -pathnew (string) : the path of new resized image -Keyword Arguments: -width (int) : the width of the new image , hieght is depending on it

    -

    Returns

    -

    (string) : True if image resized successfully or the exception message if not

    -
    -Source code -
    def resize(path, pathnew, width=1024):
    -    """resize an image 
    -    
    -    Arguments:
    -        path (string) : the path of the image will be resized
    -        pathnew (string) : the path of new resized image
    -    
    -    Keyword Arguments:
    -        width (int) : the width of the new image , hieght is depending on it
    -    
    -    Returns:
    -        (string) : True if image resized successfully or the exception message if not
    -    """
    -    im = get_image(path)
    -    xnew = width
    -    x, y = im.size
    -    ynew = int(float(y) / (float(x) / float(xnew)))
    -    imnew = im.resize((xnew, ynew), Image.ANTIALIAS)
    -    try:
    -        imnew.save(pathnew)
    -        return "True"
    -    except Exception as e:
    -        return str(e)
    -
    -
    -
    -def resize_images_in_dir(folder, foldernew, width=1024) -
    -
    -

    resize images in folder

    -

    Arguments

    -

    folder (string) : the path of the root folder in which images will be resized -foldernew (string) : the path of the folder in which new images will be stored -Keyword Arguments: -width (int) : the width of the new images , hieght is depending on it

    -

    Returns

    -

    (dict) : a dict with img path as key and its statue as value -statue : True if image resized successfully or the exception message if not

    -
    -Source code -
    def resize_images_in_dir(folder, foldernew, width=1024):
    -    """resize images in folder
    -    
    -    Arguments:
    -        folder (string) : the path of the root folder in which images will be resized
    -        foldernew (string) : the path of the folder in which new images will be stored
    -    
    -    Keyword Arguments:
    -        width (int) : the width of the new images , hieght is depending on it
    -    
    -    Returns:
    -        (dict) : a dict with img path as key and its statue as value
    -            statue : True if image resized successfully or the exception message if not
    -    """
    -    img_list = get_list_files(folder)
    -    print(img_list)
    -    img_statue = {}
    -    for img in img_list:
    -        statue = resize(img, os.path.join(foldernew, os.path.basename(img)), width=width)
    -        img_statue[img] = statue
    -    return img_statue
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/imagelib/index.html b/docs/api/jumpscale/tools/imagelib/index.html deleted file mode 100644 index 582b6d04f..000000000 --- a/docs/api/jumpscale/tools/imagelib/index.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - -jumpscale.tools.imagelib API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.imagelib

    -
    -
    -

    Wraps imagelib

    -

    TODO: examples

    -
    -Source code -
    """Wraps imagelib
    -
    -# TODO: examples
    -
    -"""
    -
    -from .imagelib import *
    -
    -
    -
    -

    Sub-modules

    -
    -
    jumpscale.tools.imagelib.imagelib
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/poolexecutor/index.html b/docs/api/jumpscale/tools/poolexecutor/index.html deleted file mode 100644 index 4221f0052..000000000 --- a/docs/api/jumpscale/tools/poolexecutor/index.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - -jumpscale.tools.poolexecutor API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.poolexecutor

    -
    -
    -
    -Source code -
    from .poolexecutor import PoolExecutor
    -
    -"""
    -
    -def sleepf(howlong, name="fun"):
    -    print("{} is sleeping for {}".format(name, howlong))
    -    for i in range(howlong):
    -        print("{} is sleeping slept for {}".format(name, howlong - i))
    -        gevent.sleep(i)
    -
    -with j.tools.poolexecutor.PoolExecutor() as p:
    -    for i in range(5):
    -        p.task_add(sleepf, i, name="fun{}".format(i))
    -
    -    gs = p.run()
    -    print(p.results(gs))
    -
    -
    -"""
    -
    -
    -
    -

    Sub-modules

    -
    -
    jumpscale.tools.poolexecutor.poolexecutor
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/poolexecutor/poolexecutor.html b/docs/api/jumpscale/tools/poolexecutor/poolexecutor.html deleted file mode 100644 index 78219e7eb..000000000 --- a/docs/api/jumpscale/tools/poolexecutor/poolexecutor.html +++ /dev/null @@ -1,273 +0,0 @@ - - - - - - -jumpscale.tools.poolexecutor.poolexecutor API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.poolexecutor.poolexecutor

    -
    -
    -
    -Source code -
    import gevent
    -
    -
    -class Job:
    -    def __init__(self, fun, *args, **kwargs):
    -        self.fun = fun
    -        self.args = args
    -        self.kwargs = kwargs
    -
    -
    -class PoolExecutor:
    -    def __init__(self):
    -        self.jobs = []
    -    
    -    def __enter__(self):
    -        return self
    -
    -    def __exit__(self, type, value, tb):
    -        pass
    -
    -    def task_add(self, fun, *args, **kwargs):
    -        self.jobs.append(Job(fun, *args, **kwargs))
    -
    -    def run(self, die=True):
    -        try:
    -            greenlets = [gevent.spawn(job.fun, *job.args, **job.kwargs) for job in self.jobs]
    -            # print("greenlets: ", greenlets)
    -            gevent.joinall(greenlets, raise_error=die)
    -        except Exception as e:
    -            self.jobs = []
    -            raise e
    -        else:
    -            self.jobs = []
    -            return greenlets
    -    
    -    def results(self, greenlets):
    -        return [greenlet.value for greenlet in greenlets]
    -
    -
    -    # def test_simple(self):
    -    #     with j.tools.poolexecutor.PoolExecutor() as p:
    -    #         for i in range(5):
    -    #             p.task_add(sleepf, i, name="fun{}".format(i))
    -
    -    #         gs = p.run()
    -    #         p.results(gs)
    -    
    -    #     def sleepf(howlong, name="fun"):
    -    #         print("{} is sleeping for {}".format(name, howlong))
    -    #         for i in range(howlong):
    -    #             print("{} is sleeping slept for {}".format(name, howlong - i))
    -    #             gevent.sleep(i)
    -
    -    #     for i in range(5):
    -    #         self.task_add(sleepf, i, name="fun{}".format(i))
    -
    -    #     self.run()
    -
    -    # def test_with_errors(self):
    -
    -    #     def sleepf(howlong, name="fun"):
    -    #         print("{} is sleeping for {}".format(name, howlong))
    -    #         for i in range(howlong):
    -    #             print("{} is sleeping slept for {}".format(name, howlong - i))
    -    #             gevent.sleep(i)
    -
    -    #     def sleepf_with_error(howlong, name="fun"):
    -    #         print("{} is sleeping for {}".format(name, howlong))
    -    #         for i in range(howlong):
    -    #             print("{} is sleeping slept for {}".format(name, howlong - i))
    -    #             gevent.sleep(i)
    -    #         raise RuntimeError("error here in sleepf_with_error")
    -
    -    #     for i in range(5):
    -    #         self.task_add(sleepf, i, name="fun{}".format(i))
    -
    -    #     self.task_add(sleepf_with_error, i, name="error_fun")
    -
    -    #     try:
    -    #         self.run()
    -    #     except:
    -    #         print("run has a function that raises and we caught it.")
    -
    -    # def test_with_results(self):
    -
    -    #     def sleepf(howlong, name="fun"):
    -    #         print("{} is sleeping for {}".format(name, howlong))
    -    #         for i in range(howlong):
    -    #             print("{} is sleeping slept for {}".format(name, howlong - i))
    -    #             gevent.sleep(i)
    -    #         return 7
    -
    -    #     for i in range(5):
    -    #         self.task_add(sleepf, i, name="fun{}".format(i))
    -
    -    #     greenlets = self.run()
    -    #     results = [greenlet.value for greenlet in greenlets]
    -    #     assert all(map(lambda x: x == 7, results)) == True
    -    #     print(results)
    -
    -    # def test(self):
    -    #     for f in [self.test_simple, self.test_with_results, self.test_with_errors]:
    -    #         f()
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -

    Classes

    -
    -
    -class Job -(fun, *args, **kwargs) -
    -
    -
    -
    -Source code -
    class Job:
    -    def __init__(self, fun, *args, **kwargs):
    -        self.fun = fun
    -        self.args = args
    -        self.kwargs = kwargs
    -
    -
    -
    -class PoolExecutor -
    -
    -
    -
    -Source code -
    class PoolExecutor:
    -    def __init__(self):
    -        self.jobs = []
    -    
    -    def __enter__(self):
    -        return self
    -
    -    def __exit__(self, type, value, tb):
    -        pass
    -
    -    def task_add(self, fun, *args, **kwargs):
    -        self.jobs.append(Job(fun, *args, **kwargs))
    -
    -    def run(self, die=True):
    -        try:
    -            greenlets = [gevent.spawn(job.fun, *job.args, **job.kwargs) for job in self.jobs]
    -            # print("greenlets: ", greenlets)
    -            gevent.joinall(greenlets, raise_error=die)
    -        except Exception as e:
    -            self.jobs = []
    -            raise e
    -        else:
    -            self.jobs = []
    -            return greenlets
    -    
    -    def results(self, greenlets):
    -        return [greenlet.value for greenlet in greenlets]
    -
    -

    Methods

    -
    -
    -def results(self, greenlets) -
    -
    -
    -
    -Source code -
    def results(self, greenlets):
    -    return [greenlet.value for greenlet in greenlets]
    -
    -
    -
    -def run(self, die=True) -
    -
    -
    -
    -Source code -
    def run(self, die=True):
    -    try:
    -        greenlets = [gevent.spawn(job.fun, *job.args, **job.kwargs) for job in self.jobs]
    -        # print("greenlets: ", greenlets)
    -        gevent.joinall(greenlets, raise_error=die)
    -    except Exception as e:
    -        self.jobs = []
    -        raise e
    -    else:
    -        self.jobs = []
    -        return greenlets
    -
    -
    -
    -def task_add(self, fun, *args, **kwargs) -
    -
    -
    -
    -Source code -
    def task_add(self, fun, *args, **kwargs):
    -    self.jobs.append(Job(fun, *args, **kwargs))
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - \ No newline at end of file diff --git a/docs/api/jumpscale/tools/profiler/index.html b/docs/api/jumpscale/tools/profiler/index.html deleted file mode 100644 index 45ba0608d..000000000 --- a/docs/api/jumpscale/tools/profiler/index.html +++ /dev/null @@ -1,206 +0,0 @@ - - - - - - -jumpscale.tools.profiler API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.profiler

    -
    -
    -

    This module is used to do profiling for methods. profiling can be visulaized or just printed to stdout -How to use it

    -
    @j.tools.profiler.profiled(visualized=True)
    -def foo():
    -  for i in range(10):
    -    print("test")
    -
    -

    to do visualizing, add (visualize=True) when u call profiled decorator -example -@j.tools.profiler.profiled() # this will print the profiling results to stdout -j.tools.profiler.profiled(visualized=True) # will launce a server with the visualized profiling on <http://127.0.0.1:8080/snakeviz/%2Fsandbox%2Fcode%2Fgithub%2Fthreefoldtech%2Fjs-ng%2Fresult.prof> -to change port and host -j.tools.profiler.profiled(visualized=True, port="8008", host="0.0.0.0", print_data=True) -this will print data to stdout and launce snakeviz server on this url -<http://127.0.0.1:8080/snakeviz/foo>

    -
    -Source code -
    """This module is used to do profiling for methods. profiling can be visulaized or just printed to stdout
    -How to use it
    -```
    -@j.tools.profiler.profiled(visualized=True)
    -def foo():
    -  for i in range(10):
    -    print("test")
    -```
    -to do visualizing, add (visualize=True) when u call profiled decorator
    -example
    -@j.tools.profiler.profiled() # this will print the profiling results to stdout
    -j.tools.profiler.profiled(visualized=True) # will launce a server with the visualized profiling on `http://127.0.0.1:8080/snakeviz/%2Fsandbox%2Fcode%2Fgithub%2Fthreefoldtech%2Fjs-ng%2Fresult.prof`
    -to change port and host
    -j.tools.profiler.profiled(visualized=True, port="8008", host="0.0.0.0", print_data=True)
    -this will print data to stdout and launce snakeviz server on this url
    -`http://127.0.0.1:8080/snakeviz/foo`
    -"""
    -from cProfile import Profile
    -from pstats import Stats
    -from snakeviz.main import app
    -import tornado
    -from subprocess import Popen
    -import socket
    -
    -
    -def profiled(visualized=False, host="127.0.0.1", port="8080", print_data=False):
    -    def do_profiling(func):
    -        def wrapper(*args, **kwargs):
    -            profiler = Profile()
    -            result = profiler.runcall(func, *args, **kwargs)
    -            if print_data:
    -                profiler.print_stats()
    -            filename = func.__name__
    -            profiler.dump_stats(filename)
    -            if visualized:
    -                visualize(filename, host, port)
    -            return result
    -
    -        return wrapper
    -
    -    return do_profiling
    -
    -
    -def visualize(filename, host="127.0.0.1", port="8080"):
    -    try:
    -        Stats(filename)
    -    except Exception as e:
    -        print(f"{filename} is not a valid stats file")
    -        raise e
    -    try:
    -        conn = app.listen(port, address=host)
    -    except socket.error as e:
    -        print("Port {0} already in use.".format(port))
    -        raise e
    -
    -    url = "http://{0}:{1}/snakeviz/{2}".format(host, port, filename)
    -    print(f"snakeviz web server started on {host}:{port}; enter Ctrl-C to exit")
    -    print(url)
    -
    -    try:
    -        tornado.ioloop.IOLoop.instance().start()
    -    except KeyboardInterrupt:
    -        conn.stop()
    -        print("\nBye!")
    -
    -    return 0
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def profiled(visualized=False, host='127.0.0.1', port='8080', print_data=False) -
    -
    -
    -
    -Source code -
    def profiled(visualized=False, host="127.0.0.1", port="8080", print_data=False):
    -    def do_profiling(func):
    -        def wrapper(*args, **kwargs):
    -            profiler = Profile()
    -            result = profiler.runcall(func, *args, **kwargs)
    -            if print_data:
    -                profiler.print_stats()
    -            filename = func.__name__
    -            profiler.dump_stats(filename)
    -            if visualized:
    -                visualize(filename, host, port)
    -            return result
    -
    -        return wrapper
    -
    -    return do_profiling
    -
    -
    -
    -def visualize(filename, host='127.0.0.1', port='8080') -
    -
    -
    -
    -Source code -
    def visualize(filename, host="127.0.0.1", port="8080"):
    -    try:
    -        Stats(filename)
    -    except Exception as e:
    -        print(f"{filename} is not a valid stats file")
    -        raise e
    -    try:
    -        conn = app.listen(port, address=host)
    -    except socket.error as e:
    -        print("Port {0} already in use.".format(port))
    -        raise e
    -
    -    url = "http://{0}:{1}/snakeviz/{2}".format(host, port, filename)
    -    print(f"snakeviz web server started on {host}:{port}; enter Ctrl-C to exit")
    -    print(url)
    -
    -    try:
    -        tornado.ioloop.IOLoop.instance().start()
    -    except KeyboardInterrupt:
    -        conn.stop()
    -        print("\nBye!")
    -
    -    return 0
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - diff --git a/docs/api/jumpscale/tools/tfgateway/index.html b/docs/api/jumpscale/tools/tfgateway/index.html deleted file mode 100644 index 972cf730c..000000000 --- a/docs/api/jumpscale/tools/tfgateway/index.html +++ /dev/null @@ -1,409 +0,0 @@ - - - - - - -jumpscale.tools.tfgateway API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.tfgateway

    -
    -
    -
    -Source code -
    from jumpscale.loader import j
    -
    -from ipaddress import IPv4Address, IPv6Address
    -
    -# TODO: fixme when ipaddr is primitive in types.
    -def addr_check(addr):
    -    try:
    -        IPv4Address(addr)
    -    except:
    -        try:
    -            IPv6Address(addr)
    -        except:
    -            return False
    -        else:
    -            return True
    -    else:
    -        return True
    -
    -"""
    -j.tools.tf_gateway.tcpservice_register("bing", "www.bing.com", "122.124.214.21")
    -j.tools.tf_gateway.domain_register_a("ahmed", "bots.grid.tf.", "123.3.23.54")
    -
    -"""
    -
    -def local_redis():
    -    local = None
    -    try:
    -        local = j.clients.redis.get('local')
    -    except:
    -        local = j.clients.redis.new('local')
    -
    -    return local
    -
    -def tcpservice_register(service_name, domain, service_endpoint):
    -    """
    -    register a tcpservice to be used by tcprouter in local_redis()
    -
    -    :param service_name: service name to register in tcprouter
    -    :type service_name: str
    -    :param domain: (Server Name Indicator SNI) (e.g www.facebook.com)
    -    :type domain: str
    -    :param service_endpoint: TLS endpoint 102.142.96.34:443 "ip:port"
    -    :type service_endpoint: string
    -    """
    -    service = {}
    -    service["Key"] = "/tcprouter/service/{}".format(service_name)
    -    record = {"addr": service_endpoint, "sni": domain, "name": service_name}
    -    json_dumped_record_bytes = j.data.serializers.json.dumps(record).encode()
    -    b64_record = j.data.serializers.base64.encode(json_dumped_record_bytes).decode()
    -    service["Value"] = b64_record
    -    local_redis().set(service["Key"], j.data.serializers.json.dumps(service))
    -
    -def domain_register(threebot_name, bots_domain="bots.grid.tf.", record_type="a", records=None):
    -    """registers domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: threebot_name
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "bots.grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_type: valid dns record (a, aaaa, txt, srv..), defaults to "a"
    -    :type record_type: str, optional
    -    :param records: records list, defaults to None
    -    :type records: [type], optional is [ {"ip":machine ip}] in case of a/aaaa records
    -    """
    -    if not bots_domain.endswith("."):
    -        bots_domain += "."
    -    data = {}
    -    records = records or []
    -    if local_redis().hexists(bots_domain, threebot_name):
    -        data = j.data.serializers.json.loads(local_redis().hget(bots_domain, threebot_name))
    -
    -    if record_type in data:
    -        records.extend(data[record_type])
    -    data[record_type] = records
    -    local_redis().hset(bots_domain, threebot_name, j.data.serializers.json.dumps(data))
    -
    -def domain_register_a(name, domain, record_ip):
    -    """registers A domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: myhost
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_ip: machine ip in ipv4 format
    -    :type record_ip: str
    -    """
    -    if addr_check(record_ip):
    -        return domain_register(name, domain, record_type="a", records=[{"ip": record_ip}])
    -    else:
    -        raise j.exceptions.Value("invalid ip {record_ip}".format(**locals()))
    -
    -def domain_register_aaaa(threebot_name, bots_domain, record_ip):
    -    """registers A domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: threebot_name
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "bots.grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_ip: machine ip in ipv6 format
    -    :type record_ip: str
    -    """
    -    if addr_check(record_ip):
    -        return domain_register(threebot_name, bots_domain, record_type="aaaa", records=[{"ip": record_ip}])
    -    else:
    -        raise j.exceptions.Value("invalid ip {record_ip}".format(**locals()))
    -
    -
    -def test():
    -    domain_register_a("ns", "3bot.me", "134.209.90.92")
    -    domain_register_a("a", "3bot.me", "134.209.90.92")
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def addr_check(addr) -
    -
    -
    -
    -Source code -
    def addr_check(addr):
    -    try:
    -        IPv4Address(addr)
    -    except:
    -        try:
    -            IPv6Address(addr)
    -        except:
    -            return False
    -        else:
    -            return True
    -    else:
    -        return True
    -
    -
    -
    -def domain_register(threebot_name, bots_domain='bots.grid.tf.', record_type='a', records=None) -
    -
    -

    registers domain in coredns (needs to be authoritative)

    -

    e.g: ahmed.bots.grid.tf

    -

    requires nameserver on bots.grid.tf (authoritative) -- ahmed is threebot_name -- bots_domain is bots.grid.tf

    -

    :param threebot_name: threebot_name -:type threebot_name: str -:param bots_domain: str, defaults to "bots.grid.tf." -:type bots_domain: str, optional -:param record_type: valid dns record (a, aaaa, txt, srv..), defaults to "a" -:type record_type: str, optional -:param records: records list, defaults to None -:type records: [type], optional is [ {"ip":machine ip}] in case of a/aaaa records

    -
    -Source code -
    def domain_register(threebot_name, bots_domain="bots.grid.tf.", record_type="a", records=None):
    -    """registers domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: threebot_name
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "bots.grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_type: valid dns record (a, aaaa, txt, srv..), defaults to "a"
    -    :type record_type: str, optional
    -    :param records: records list, defaults to None
    -    :type records: [type], optional is [ {"ip":machine ip}] in case of a/aaaa records
    -    """
    -    if not bots_domain.endswith("."):
    -        bots_domain += "."
    -    data = {}
    -    records = records or []
    -    if local_redis().hexists(bots_domain, threebot_name):
    -        data = j.data.serializers.json.loads(local_redis().hget(bots_domain, threebot_name))
    -
    -    if record_type in data:
    -        records.extend(data[record_type])
    -    data[record_type] = records
    -    local_redis().hset(bots_domain, threebot_name, j.data.serializers.json.dumps(data))
    -
    -
    -
    -def domain_register_a(name, domain, record_ip) -
    -
    -

    registers A domain in coredns (needs to be authoritative)

    -

    e.g: ahmed.bots.grid.tf

    -

    requires nameserver on bots.grid.tf (authoritative) -- ahmed is threebot_name -- bots_domain is bots.grid.tf

    -

    :param threebot_name: myhost -:type threebot_name: str -:param bots_domain: str, defaults to "grid.tf." -:type bots_domain: str, optional -:param record_ip: machine ip in ipv4 format -:type record_ip: str

    -
    -Source code -
    def domain_register_a(name, domain, record_ip):
    -    """registers A domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: myhost
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_ip: machine ip in ipv4 format
    -    :type record_ip: str
    -    """
    -    if addr_check(record_ip):
    -        return domain_register(name, domain, record_type="a", records=[{"ip": record_ip}])
    -    else:
    -        raise j.exceptions.Value("invalid ip {record_ip}".format(**locals()))
    -
    -
    -
    -def domain_register_aaaa(threebot_name, bots_domain, record_ip) -
    -
    -

    registers A domain in coredns (needs to be authoritative)

    -

    e.g: ahmed.bots.grid.tf

    -

    requires nameserver on bots.grid.tf (authoritative) -- ahmed is threebot_name -- bots_domain is bots.grid.tf

    -

    :param threebot_name: threebot_name -:type threebot_name: str -:param bots_domain: str, defaults to "bots.grid.tf." -:type bots_domain: str, optional -:param record_ip: machine ip in ipv6 format -:type record_ip: str

    -
    -Source code -
    def domain_register_aaaa(threebot_name, bots_domain, record_ip):
    -    """registers A domain in coredns (needs to be authoritative)
    -
    -    e.g: ahmed.bots.grid.tf
    -
    -    requires nameserver on bots.grid.tf (authoritative)
    -    - ahmed is threebot_name
    -    - bots_domain is bots.grid.tf
    -
    -    :param threebot_name: threebot_name
    -    :type threebot_name: str
    -    :param bots_domain: str, defaults to "bots.grid.tf."
    -    :type bots_domain: str, optional
    -    :param record_ip: machine ip in ipv6 format
    -    :type record_ip: str
    -    """
    -    if addr_check(record_ip):
    -        return domain_register(threebot_name, bots_domain, record_type="aaaa", records=[{"ip": record_ip}])
    -    else:
    -        raise j.exceptions.Value("invalid ip {record_ip}".format(**locals()))
    -
    -
    -
    -def local_redis() -
    -
    -
    -
    -Source code -
    def local_redis():
    -    local = None
    -    try:
    -        local = j.clients.redis.get('local')
    -    except:
    -        local = j.clients.redis.new('local')
    -
    -    return local
    -
    -
    -
    -def tcpservice_register(service_name, domain, service_endpoint) -
    -
    -

    register a tcpservice to be used by tcprouter in local_redis()

    -

    :param service_name: service name to register in tcprouter -:type service_name: str -:param domain: (Server Name Indicator SNI) (e.g www.facebook.com) -:type domain: str -:param service_endpoint: TLS endpoint 102.142.96.34:443 "ip:port" -:type service_endpoint: string

    -
    -Source code -
    def tcpservice_register(service_name, domain, service_endpoint):
    -    """
    -    register a tcpservice to be used by tcprouter in local_redis()
    -
    -    :param service_name: service name to register in tcprouter
    -    :type service_name: str
    -    :param domain: (Server Name Indicator SNI) (e.g www.facebook.com)
    -    :type domain: str
    -    :param service_endpoint: TLS endpoint 102.142.96.34:443 "ip:port"
    -    :type service_endpoint: string
    -    """
    -    service = {}
    -    service["Key"] = "/tcprouter/service/{}".format(service_name)
    -    record = {"addr": service_endpoint, "sni": domain, "name": service_name}
    -    json_dumped_record_bytes = j.data.serializers.json.dumps(record).encode()
    -    b64_record = j.data.serializers.base64.encode(json_dumped_record_bytes).decode()
    -    service["Value"] = b64_record
    -    local_redis().set(service["Key"], j.data.serializers.json.dumps(service))
    -
    -
    -
    -def test() -
    -
    -
    -
    -Source code -
    def test():
    -    domain_register_a("ns", "3bot.me", "134.209.90.92")
    -    domain_register_a("a", "3bot.me", "134.209.90.92")
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - diff --git a/docs/api/jumpscale/tools/timer/timer.html b/docs/api/jumpscale/tools/timer/timer.html deleted file mode 100644 index e3a3840be..000000000 --- a/docs/api/jumpscale/tools/timer/timer.html +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - -jumpscale.tools.timer.timer API documentation - - - - - - - - - -
    -
    -
    -

    Module jumpscale.tools.timer.timer

    -
    -
    -
    -Source code -
    import time
    -from jumpscale.loader import j
    -
    -
    -def timeit(func):
    -    def wrapper(*args, **kwargs):
    -        start_time = time.time()
    -        result = func(*args, **kwargs)
    -        end_time = time.time()
    -        diff = end_time - start_time
    -        j.logger.info("func {} with args: {}, kwargs: {} took {}".format(func.__name__, args, kwargs, diff))
    -        return result
    -
    -    return wrapper
    -
    -
    -
    -
    -
    -
    -
    -

    Functions

    -
    -
    -def timeit(func) -
    -
    -
    -
    -Source code -
    def timeit(func):
    -    def wrapper(*args, **kwargs):
    -        start_time = time.time()
    -        result = func(*args, **kwargs)
    -        end_time = time.time()
    -        diff = end_time - start_time
    -        j.logger.info("func {} with args: {}, kwargs: {} took {}".format(func.__name__, args, kwargs, diff))
    -        return result
    -
    -    return wrapper
    -
    -
    -
    -
    -
    -
    -
    - -
    - - - - - diff --git a/docs/wiki/3sdk.md b/docs/wiki/3sdk.md deleted file mode 100644 index 0ce851609..000000000 --- a/docs/wiki/3sdk.md +++ /dev/null @@ -1,69 +0,0 @@ -# Working with 3sdk - -`3sdk` is a command line tool that provides the user with a simple interface to orchestrate his threebot containers. -It allows the user to create a container that is ready to start a threebot server on with the user identity already registered on that container. - -## Using 3sdk - -You can get the binary from the [release page](https://github.com/threefoldtech/js-ng/releases). Make sure to change permission to allow the binary to be executed as follows: - -```bash -chmod +x {binary_path} -``` - -Once inside the shell you can see that it provides auto completion to the available commands: - -![Shell auto completion](images/sdkautocomplete.png) - -To install a new threebot container: - -![SDK install](images/sdkinstall.png) - -The user will be prompted to enter his user information which includes: - -- His 3bot name -- His 3bot email -- His phrase which is normally found in his `3bot connect` app - -![SDK prompt](images/sdkprompt.png) - -The user is then asked to choose which explorer networks he is in: - -![SDK explorer](images/sdkexplorer.png) - -The container should be created now with default name `3bot-ng`. - -## Building the 3sdk - -You can get latest available binary by using `pyinstaller`. Which creates the `3sdk` binary based on `threesdk.spec` file. - -To install `pyinstaller` run: - -```bash -pip3 install pyinstaller -``` - -And then to create the binary: - -```bash -cd {jsng repo path} -pyinstaller threesdk.spec -``` - -Binary should be created under `dist` directory in the repo root, and is ready to be used. - -### Building a static executable - -You bundle the dynamic executables to ensure that the binary can be run on any system by creating a static executable. - -First you need to install `staticx`: - -```bash -pip3 install staticx -``` - -After building your binary run the following for a static executable: - -```bash -staticx dist/3sdk 3sdk.static -``` diff --git a/docs/wiki/README.md b/docs/wiki/README.md index 7cec31ec5..6c6baf08b 100644 --- a/docs/wiki/README.md +++ b/docs/wiki/README.md @@ -30,7 +30,7 @@ * [Extending Jumpscale](./extend_j.md) * [Adding a new command](./distributing_cmds.md) * [Executors](./executors.md) - * [Registering new extensions on God object](./extend_j.md) + * [Registering new extensions on loader object](./extend_j.md) * [Logging](./logging.md) * [Exceptions](./exceptions.md) * [Errors](./errorhandling.md) @@ -41,7 +41,7 @@ * [Github actions](./githubactions.md) * [Specs](specs.md) * [Poetry](poetry.md) - * [God object and namespaces](god_object_namespaces_concepts.md) + * [Loader object and namespaces](loader_object_namespaces_concepts.md) * [Loader](loader.md) * [JS-NG shell](jsng_shell.md) * [Base Classes and Hierarchical Configurations](baseclasses.md) @@ -49,4 +49,4 @@ * [Exceptions](exceptions.md) * [Logging](logging.md) * [Executors](executors.md) - * [Distributing Commands](distributing_cmds.md) \ No newline at end of file + * [Distributing Commands](distributing_cmds.md) diff --git a/docs/wiki/_sidebar.md b/docs/wiki/_sidebar.md index b48d731d1..664092325 100644 --- a/docs/wiki/_sidebar.md +++ b/docs/wiki/_sidebar.md @@ -33,7 +33,7 @@ * [Extending Jumpscale](./extend_j.md) * [Adding a new command](./distributing_cmds.md) * [Executors](./executors.md) - * [Registering new extensions on God object](./extend_j.md) + * [Registering new extensions on loader object](./extend_j.md) * [Logging](./logging.md) * [Exceptions](./exceptions.md) * [Errors](./errorhandling.md) @@ -48,7 +48,7 @@ * [Specs](specs.md) * [Poetry](poetry.md) - * [God object and namespaces](god_object_namespaces_concepts.md) + * [Loader object and namespaces](loader_object_namespaces_concepts.md) * [Loader](loader.md) * [JS-NG shell](jsng_shell.md) * [Base Classes and Hierarchical Configurations](baseclasses.md) diff --git a/docs/wiki/docker.md b/docs/wiki/docker.md deleted file mode 100644 index 639354653..000000000 --- a/docs/wiki/docker.md +++ /dev/null @@ -1,16 +0,0 @@ -# Starting docker container with js-ng installed -## Start usershell with this -``` - poetry run usershell -``` -## instantiate docker container from js-ng usershell -``` -container.install(name="jsng", image="threefoldtech/js-ng:latest", ports=None, volumes=None, devices=None, identity=None) -# name is the docker container name, default is jsng -# image is the jsng-image you want to run, default is threefoldtech/js-ng:latest -# ports is the port you want to forward -# volumes is the volumes you want to mount on docker -# devices the devices you want to include in docker -# identity is the private key you want to create on docker -# mount_code mount codedir into container,default is True -``` diff --git a/docs/wiki/god_object_namespaces_concepts.md b/docs/wiki/loader_object_namespaces_concepts.md similarity index 97% rename from docs/wiki/god_object_namespaces_concepts.md rename to docs/wiki/loader_object_namespaces_concepts.md index d4fe7a8cd..81c1d952c 100644 --- a/docs/wiki/god_object_namespaces_concepts.md +++ b/docs/wiki/loader_object_namespaces_concepts.md @@ -66,7 +66,7 @@ Example structure ├── projectmain │ └── jumpscale -│ ├── god.py +│ ├── loader.py │ ├── __init__.py ├── projectsals │ └── jumpscale @@ -104,7 +104,7 @@ Solved by design using python modules # Problem 4: jslocation -If we open `god.py` +If we do like the following ```python import jumpscale.sal @@ -113,9 +113,10 @@ import jumpscale.clients j = jumpscale ``` + we have handcrafted imports for sal, tools, clients so their subpackages can be autoloaded, but how should it work with packages like `digitalme` -## How to register digitalme in the god object +## How to register digitalme in the global object "j" Do we generate `import jumpscale.digitalme`? is there a standard python way to do it? a reliable plugin system? ## where would its module be registered? diff --git a/docs/wiki/specs.md b/docs/wiki/specs.md index 6b1882fc9..4dab58c5e 100644 --- a/docs/wiki/specs.md +++ b/docs/wiki/specs.md @@ -1,5 +1,5 @@ * [Poetry](poetry.md) -* [God object and namespaces](god_object_namespaces_concepts.md) +* [Loader object and namespaces](loader_object_namespaces_concepts.md) * [Loader](loader.md) * [JS-NG shell](jsng_shell.md) * [Base Classes and Hierarchical Configurations](baseclasses.md) @@ -7,4 +7,4 @@ * [Exceptions](exceptions.md) * [Logging](logging.md) * [Executors](executors.md) -* [Distributing Commands](distributing_cmds.md) \ No newline at end of file +* [Distributing Commands](distributing_cmds.md) diff --git a/docs/wiki/tutorials/developing_sal.md b/docs/wiki/tutorials/developing_sal.md index 18e6b4bf3..8739c4a93 100644 --- a/docs/wiki/tutorials/developing_sal.md +++ b/docs/wiki/tutorials/developing_sal.md @@ -26,6 +26,4 @@ You can put all of your code directly in the `__init__.py` of your SAL package. ## Accessing code -Code will be auto registered in the god object `j` like that `j.sal.YOUR_NEW_SAL` - - +Code will be auto registered in the loader object `j` like that `j.sal.YOUR_NEW_SAL` diff --git a/jumpscale/core/config/config.py b/jumpscale/core/config/config.py index 421250dc1..b90846b86 100644 --- a/jumpscale/core/config/config.py +++ b/jumpscale/core/config/config.py @@ -114,7 +114,10 @@ def get_default_config(): "debug": True, "shell": "ptpython", "logging": { - "default": {"enabled": True, "level": 10,}, + "default": { + "enabled": True, + "level": 10, + }, "redis": { "enabled": True, "level": 15, @@ -139,8 +142,9 @@ def get_default_config(): }, "factory": {"always_reload": False}, "store": "filesystem", - "threebot": {"default": "",}, - "explorer": {"default_url": "https://explorer.testnet.grid.tf/explorer",}, + "threebot": { + "default": "", + }, } @@ -165,7 +169,7 @@ def update_config(data): def get(key, default=None): - """ Retrives value from jumpscale config + """Retrives value from jumpscale config Arguments: key (str): the key you wish to retrieve @@ -176,7 +180,7 @@ def get(key, default=None): def set(key, val): - """ Sets value in jumpscale config + """Sets value in jumpscale config Arguments: key (str): the key you wish to update @@ -188,7 +192,7 @@ def set(key, val): def set_default(key, val): - """ Sets key to value in jumpscale config and returns + """Sets key to value in jumpscale config and returns Arguments: key (str): the key you wish to update diff --git a/jumpscale/entry_points/usershell.py b/jumpscale/entry_points/usershell.py deleted file mode 100644 index 9e5cc9600..000000000 --- a/jumpscale/entry_points/usershell.py +++ /dev/null @@ -1,247 +0,0 @@ -import os -import re -import time -import sys -import traceback -import argparse -import requests - -import inspect -import cgi - -from prompt_toolkit import PromptSession -from prompt_toolkit.completion import Completion -from prompt_toolkit.shortcuts import print_formatted_text -from prompt_toolkit.eventloop.async_generator import AsyncGeneratorItem -from prompt_toolkit.validation import Validator, ValidationError -from prompt_toolkit.styles import Style -from prompt_toolkit.formatted_text import HTML -from jumpscale import threesdk -from jumpscale.threesdk import settings -from jumpscale.core.exceptions.exceptions import JSException -from jumpscale.clients.docker.docker import DockerClient -from jumpscale.threesdk.threebot import ThreeBot, DEFAULT_IMAGE -from jumpscale.core.config import get_current_version - - -BASE_CONFIG_DIR = os.path.join(os.environ.get("HOME", "/root"), ".jsng") -HISTORY_FILENAME = os.path.join(BASE_CONFIG_DIR, "history.txt") - -DEFAULT_TOOLBAR_MSG = "Welcome to 3sdk enter info for help" - -style = Style.from_dict( - { - # User input (default text). - "bottom-toolbar": "#ffffff bg:#333333", - "default": "#aaaaaa", - # Prompt. - } -) - - -def get_binary_link(): - resp = requests.get("https://api.github.com/repos/threefoldtech/js-ng/releases/latest") - resp = resp.json() - # get versions - download_link = "" - version = resp["tag_name"] - for platform in resp["assets"]: - if sys.platform in platform["name"]: - download_link = platform["browser_download_url"] - return version, download_link - - -def update(): - print("checking for updates") - latest_version, binary_link = get_binary_link() - current_version = get_current_version() - if latest_version != current_version: - print(f"version: {latest_version} is available get it from {binary_link}") - return - docker_client = DockerClient() - print("Checking for new docker image") - docker_client.client.images.pull(f"{DEFAULT_IMAGE}:{latest_version}") - print("Starting 3sdk containers") - for container_name in os.listdir(os.path.expanduser("~/.config/jumpscale/containers")): - ThreeBot.delete(container_name) - ThreeBot.install(container_name) - - -def print_error(error): - print_formatted_text(HTML("{}".format(cgi.html.escape(str(error))))) - - -def partition_line(line): - def replacer(m): - return m.group().replace(" ", "\0").strip("\"'") - - result = re.sub(r"""(['"]).*?\1""", replacer, line) - parts = [] - for part in result.split(): - parts.append(part.replace("\0", " ")) - return parts - - -def noexpert_error(error): - reports_location = f"{os.environ.get('HOME', os.environ.get('USERPROFILE', ''))}/sandbox/reports" - error_file_location = f"{reports_location}/jsngreport_{time.strftime('%d%H%M%S')}.log" - if not os.path.exists(reports_location): - os.makedirs(reports_location) - with open(error_file_location, "w") as f: - f.write(str(error)) - err_msg = f"""Something went wrong. Please contact support at https://support.grid.tf/ -Error report file has been created on your machine in this location: {error_file_location} - """ - return err_msg - - -class Shell(Validator): - def __init__(self): - self._prompt = PromptSession() - self.mode = None - self.toolbarmsg = DEFAULT_TOOLBAR_MSG - - def get_completions_async(self, document, complete_event): - text = document.current_line_before_cursor - parts = partition_line(text) - if not parts: - root = None - more = [] - else: - root, more = parts[0], parts[1:] - items = [] - if not root or not hasattr(threesdk, root): - style = "bg:ansibrightblue" - items += threesdk.__all__ - self.toolbarmsg = DEFAULT_TOOLBAR_MSG - else: - style = "bg:ansigreen" - obj = getattr(threesdk, root) - if not more or not hasattr(obj, more[0]): - # complete object attributes - self.toolbarmsg = threesdk._get_doc_line(obj.__doc__) - for name, member in inspect.getmembers(obj, inspect.isroutine): - if not name.startswith("_"): - items.append(name) - text = "" if not more else more[-1] - else: - # complete arguments - func = getattr(obj, more[0]) - self.toolbarmsg = threesdk._get_doc_line(func.__doc__) - style = "bg:ansired" - for arg in inspect.getfullargspec(func).args: - field = arg + "=" - if field in text: - continue - items.append(field) - if len(more) > 1: - text = more[-1] - else: - text = "" - - for item in items: - if not item: - continue - if isinstance(item, Completion): - item.start_position = -len(text) - else: - item = Completion(item, -len(text)) - regex = ".*".join(text) - item.style = style - if not text or re.search(regex, item.text): - yield AsyncGeneratorItem(item) - - def bottom_toolbar(self): - return [("class:bottom-toolbar", self.toolbarmsg)] - - def validate(self, document): - text = document.current_line_before_cursor - if not text: - return - root, *more = text.split(" ") - submodule = getattr(threesdk, root, None) - if not submodule: - raise ValidationError(message=f"No such subcommand {root}") - if not more and callable(submodule): - func = root - elif more: - func = getattr(submodule, more[0], None) - if not func: - raise ValidationError(message=f"{root} has no command called {more[0]}") - else: - raise ValidationError(message="Invalid command") - # TODO: validate args - return - - def get_func_kwargs(self, cmd): - parts = partition_line(cmd) - root, extra = parts[0], parts[1:] - module = getattr(threesdk, root) - if inspect.isroutine(module): - return module, self.get_kwargs(module, *extra) - else: - func = getattr(module, extra[0]) - return func, self.get_kwargs(func, *extra[1:]) - - def get_kwargs(self, func, *args): - funcspec = inspect.getfullargspec(func) - kwargs = {} - for arg in args: - key, val = arg.split("=", 1) - isbool = funcspec.annotations.get(key) is bool - if isbool: - if val: - val = val.lower() in ["y", "yes", "1", "true"] - else: - val = True - kwargs[key] = val - return kwargs - - def execute(self, cmd): - if not cmd.strip(): - return - try: - func, kwargs = self.get_func_kwargs(cmd) - func(**kwargs) - except JSException as e: - if not settings.expert: - print_error(str(e)) - else: - print_error(traceback.format_exc()) - except Exception: - if not settings.expert: - print_error(noexpert_error(traceback.format_exc())) - else: - print_error(traceback.format_exc()) - - def make_prompt(self): - root = ("class:default", "3sdk>") - while True: - try: - result = self.prompt([root]) - self.execute(result) - except (EOFError, KeyboardInterrupt): - sys.exit(0) - - def prompt(self, msg): - return self._prompt.prompt( - msg, completer=self, validator=self, style=style, bottom_toolbar=self.bottom_toolbar, - ) - - -def run(): - parser = argparse.ArgumentParser() - parser.add_argument("--update", action="store_true", help="Update 3sdk") - parser.add_argument("--expert", action="store_true", help="Run 3sdk in expert mode") - args = parser.parse_args() - settings.expert = args.expert - - if args.update: - update() - else: - shell = Shell() - shell.make_prompt() - - -if __name__ == "__main__": - run() diff --git a/jumpscale/threesdk/__init__.py b/jumpscale/threesdk/__init__.py deleted file mode 100755 index 12a0de91a..000000000 --- a/jumpscale/threesdk/__init__.py +++ /dev/null @@ -1,76 +0,0 @@ -from .threebot import ThreeBot as threebot -import inspect -import cgi -from prompt_toolkit.formatted_text import HTML -from prompt_toolkit.shortcuts import print_formatted_text - -__all__ = ["threebot", "info"] - - -def info(): - print_formatted_text(HTML(_get_doc(__all__))) - - -def _get_doc_line(doc): - if not doc: - return "" - for line in doc.splitlines(): - if line.strip(): - return line.strip() - return "" - - -def _get_doc(root_module, level=0, size=4): - """get a formatted docstring from a module - this will loop over __all__self. - - :param root_module: root module - :type root_module: module - :param level: spacing level, defaults to 0 - :type level: int, optional - :param level: spacing size, defaults to 4 - :type level: int, optional - :return: docstring - :rtype: str - """ - - doc = "" - - if isinstance(root_module, list): - glob = globals() - members = [(name, glob[name]) for name in root_module] - else: - members = inspect.getmembers(root_module) - for name, obj in members: - if name.startswith("_"): - continue - if name[0].lower() != name[0]: - continue - - is_module = not inspect.isroutine(obj) - if is_module and level != 0: - continue - - spaces = " " * level - - if is_module: - doc += f"{spaces}{name}" - elif getattr(obj, "__property__", False): - doc += f"{spaces}{name}" - else: - doc += f"{spaces}{name}" - - if obj.__doc__: - try: - # only get first line of member docstring - first_line = _get_doc_line(obj.__doc__) - doc += cgi.html.escape(f": {first_line}") - except IndexError: - pass - - doc = f"{doc}\n" - - if is_module: - doc += _get_doc(obj, level=level + size) - - return doc diff --git a/jumpscale/threesdk/container.py b/jumpscale/threesdk/container.py deleted file mode 100644 index 45da51b43..000000000 --- a/jumpscale/threesdk/container.py +++ /dev/null @@ -1,76 +0,0 @@ -from jumpscale.clients.docker.docker import DockerClient -from jumpscale.core.dirs.dirs import Dirs -from jumpscale.core.exceptions import Value -from jumpscale.core.executors.local import execute - -docker_client = DockerClient() - - -class Container: - """Container management - """ - - @staticmethod - def install(name, image, development: bool = False, volumes=None): - """Creates a container - - Args: - name (str): name of the container - image (str): container image. - development (bool, optional): if true will mount codedir. Defaults to False. - volumes (dict, optional): paths to be mounted - - Raises: - Value: Container with specified name already exists - """ - if docker_client.exists(name): - raise Value("Container with specified name already exists") - - volumes = volumes or {} - if development: - volumes = {Dirs.CODEDIR: {"bind": "/sandbox/code", "mode": "rw"}} - - print(f"Creating container {name}") - return docker_client.run(name, image, entrypoint="/sbin/my_init", volumes=volumes, detach=True) - - @staticmethod - def start(name): - """Starts an existing container - - Args: - name (str): name of the container - """ - if not docker_client.exists(name): - raise Value("Container with specified name doesn't exist") - docker_client.start(name) - - @staticmethod - def exec(name, cmd): - """Execute command in container - - Args: - name (str): name of the container - cmd (str or list): command to execute - """ - basecmd = ["docker", "exec", "-it", name] - if isinstance(cmd, str): - basecmd.append(cmd) - else: - basecmd += cmd - execute(basecmd, pty=True) - - @staticmethod - def stop(name): - """Stops an existing container - - Args: - name (str): name of the container - """ - if not docker_client.exists(name): - raise Value("Container with specified name doesn't exist") - docker_client.stop(name) - - @staticmethod - def delete(name): - Container.stop(name) - docker_client.delete(name) diff --git a/jumpscale/threesdk/identitymanager.py b/jumpscale/threesdk/identitymanager.py deleted file mode 100644 index e3822235b..000000000 --- a/jumpscale/threesdk/identitymanager.py +++ /dev/null @@ -1,161 +0,0 @@ -import binascii - -import requests -from collections import namedtuple - -from jumpscale.data.encryption import mnemonic -from jumpscale.data.nacl.jsnacl import NACL -from jumpscale.data.serializers import base64 -from jumpscale.core import exceptions -from jumpscale.tools.console import ask_choice, ask_string, printcolors - -NETWORKS = {"mainnet": "explorer.grid.tf", "testnet": "explorer.testnet.grid.tf", "devnet": "explorer.devnet.grid.tf"} - -RESTART_CHOICE = "Restart from the begining" -REENTER_CHOICE = "Re-Enter your value" -CHOICES = [RESTART_CHOICE, REENTER_CHOICE] - -IdentityInfo = namedtuple("IdentityInfo", ["identity", "email", "words", "explorer"]) - - -class IdentityManager: - def __init__(self, identity: str = "", email: str = None, words: str = None, explorer: str = None): - self.identity = identity - self.email = email - self.words = words - self.explorer = explorer - - def reset(self): - self.identity = "" - self.email = "" - self.words = "" - self.explorer = "" - - def _check_keys(self, user_explorer_key, user_app): - if not user_app: - return True - pub_key_app = base64.decode(user_app["publicKey"]) - if binascii.unhexlify(user_explorer_key) != pub_key_app: - return False - return True - - def _get_user(self): - response = requests.get(f"https://login.threefold.me/api/users/{self.identity}") - if response.status_code == 404: - raise exceptions.Value( - "\nThis identity does not exist in 3bot mobile app connect, Please create an idenity first using 3Bot Connect mobile Application\n" - ) - userdata = response.json() - - resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"name": self.identity}) - if resp.status_code == 404 or resp.json() == []: - # creating new user - user = {} - user["name"] = userdata["doublename"] - user["pubkey"] = base64.decode(userdata["publicKey"]).hex() - printcolors( - f"\nWelcome {{CYAN}}{userdata['doublename']}{{WHITE}}. Creating a new record on {{CYAN}}{self.explorer}{{RESET}}.\n" - ) - return user, userdata - else: - users = resp.json() - - if not self._check_keys(users[0]["pubkey"], userdata): - raise exceptions.Value( - f"\nYour 3bot on {self.explorer} seems to have been previously registered with a different public key.\n" - f"The identity of {self.identity} is mismatched with 3bot connect app" - "Please contact support.grid.tf to reset it.\n" - "Note: use the same email registered on the explorer to contact support otherwise we cannot reset the account.\n" - ) - - if users: - return (users[0], userdata) - return None, userdata - - def _check_email(self, email): - resp = requests.get("https://{}/explorer/users".format(self.explorer), params={"email": email}) - users = resp.json() - if users: - if users[0]["name"] == self.identity: - return True - else: - return False - else: - return True - - def ask_identity(self, identity=None, explorer=None): - def _fill_identity_args(identity, explorer): - def fill_words(): - words = ask_string("Copy the phrase from your 3bot Connect app here: ") - self.words = words - - def fill_identity(): - identity = ask_string("what is your threebot name (identity)? ") - if "." not in identity: - identity += ".3bot" - self.identity = identity - - if identity: - if self.identity != identity and self.identity: - self.reset() - self.identity = identity - - if explorer: - self.explorer = explorer - elif not self.explorer: - response = ask_choice( - "Which network would you like to register to? ", ["mainnet", "testnet", "devnet", "none"] - ) - self.explorer = NETWORKS.get(response, None) - if not self.explorer: - return True - - user, user_app = None, None - while not user: - fill_identity() - try: - user, user_app = self._get_user() - except exceptions.Value as e: - response = ask_choice(f"{e}What would you like to do? ", CHOICES) - if response == RESTART_CHOICE: - return False - - while not self.email: - self.email = ask_string("What is the email address associated with your identity? ") - if self._check_email(self.email): - break - else: - self.email = None - response = ask_choice( - "This email is currently associated with another identity. What would you like to do? ", - CHOICES, - ) - if response == RESTART_CHOICE: - return False - - print("Configured email for this identity is {}".format(self.email)) - - # time to do validation of words - hexkey = None - while True: - if not self.words: - fill_words() - try: - seed = mnemonic.mnemonic_to_key(self.words.strip()) - hexkey = NACL(seed).get_verify_key_hex() - if (user and hexkey != user["pubkey"]) or not self._check_keys(hexkey, user_app): - raise Exception - else: - return True - except Exception: - choice = ask_choice( - "\nSeems one or more more words entered is invalid.\nWhat would you like to do? ", CHOICES, - ) - if choice == RESTART_CHOICE: - return False - fill_words() - - while True: - if _fill_identity_args(identity, explorer): - identity_info = IdentityInfo(self.identity, self.email, self.words, self.explorer) - return identity_info diff --git a/jumpscale/threesdk/settings.py b/jumpscale/threesdk/settings.py deleted file mode 100644 index a8d4b36dc..000000000 --- a/jumpscale/threesdk/settings.py +++ /dev/null @@ -1 +0,0 @@ -expert = False diff --git a/jumpscale/threesdk/threebot.py b/jumpscale/threesdk/threebot.py deleted file mode 100644 index 88285e649..000000000 --- a/jumpscale/threesdk/threebot.py +++ /dev/null @@ -1,114 +0,0 @@ -import os - - -from jumpscale.core.config import get_current_version -from jumpscale.core.exceptions import Value -from jumpscale.clients.docker.docker import DockerClient - -from . import settings -from .container import Container -from .identitymanager import IdentityManager - -DEFAULT_CONTAINER_NAME = "3bot-ng" -DEFAULT_IMAGE = "threefoldtech/js-ng" -PERSISTENT_STORE = os.path.expanduser("~/.config/jumpscale/containers") - -docker_client = DockerClient() - - -class ThreeBot(Container): - """ - Manage your threebot - """ - - @staticmethod - def install( - name=None, image=None, identity=None, email=None, words=None, explorer=None, development: bool = None, - ): - """Creates a threebot container - - Args: - name (str, optional): name of the container. Defaults to 3bot-ng - image (str, optional): container image. Defaults to "threefoldtech/js-ng:latest". - identity (str, optional): threebot name. Defaults to None. - email (str, optional): threebot email. Defaults to None. - words (str, optional): seed phrase of the user. Defaults to None. - explorer (str, optional): which explorer network to use: mainnet, testnet, devnet. Defaults to None. - development (bool, optional): if true will mount codedir. Defaults to False. - - Raises: - Value: Container with specified name already exists - Value: explorer not in mainnet, testnet, devnet - """ - if development is None: - development = settings.expert - name = name or DEFAULT_CONTAINER_NAME - current_version = get_current_version() - image = image or f"{DEFAULT_IMAGE}:{current_version}" - - pers_path = f"{PERSISTENT_STORE}/{name}" - configure = not os.path.exists(pers_path) - if configure: - identity = IdentityManager(identity, email, words, explorer) - identity, email, words, explorer = identity.ask_identity() - - os.makedirs(PERSISTENT_STORE, exist_ok=True) - volumes = {pers_path: {"bind": "/root/.config/jumpscale", "mode": "rw"}} - - container = Container.install(name, image, development, volumes) - container.exec_run(["redis-server", "--daemonize yes"]) - - if configure: - container.exec_run(["jsng", f"j.core.identity.new('default', '{identity}', '{email}', '{words}')"]) - container.exec_run(["jsng", "j.core.identity.set_default('default')"]) - - @staticmethod - def jsng(name=DEFAULT_CONTAINER_NAME): - """Get's shell in threebot - - Args: - name (str): name of the container (default: 3bot-ng) - """ - Container.exec(name, "jsng") - - @staticmethod - def shell(name=DEFAULT_CONTAINER_NAME): - """Get's shell in threebot - - Args: - name (str): name of the container (default: 3bot-ng) - """ - Container.exec(name, "bash") - - @staticmethod - def start(name=DEFAULT_CONTAINER_NAME): - """Start threebot container with threebot server - - Args: - name (str): name of the container (default: 3bot-ng) - """ - Container.start(name) - Container.exec(name, ["threebot", "start", "--background"]) - - @staticmethod - def stop(name=DEFAULT_CONTAINER_NAME): - """Stop threebot installation with container - - Args: - name (str): name of the container (default: 3bot-ng) - """ - if name in docker_client.list(): - Container.exec(name, ["threebot", "stop"]) - Container.stop(name) - else: - print("Container is already stopped") - - @staticmethod - def restart(name=DEFAULT_CONTAINER_NAME): - """restart threebot installation with container - - Args: - name (str): name of the container (default: 3bot-ng) - """ - ThreeBot.stop(name=name) - ThreeBot.start(name=name) diff --git a/pyproject.toml b/pyproject.toml index 9ac47f22b..041ace870 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,6 @@ objgraph = "^3.4.1" [tool.poetry.scripts] jsng = "jumpscale.entry_points.jsng:run" -usershell = "jumpscale.entry_points.usershell:run" jsctl = "jumpscale.entry_points.jsctl:cli" jsync = "jumpscale.entry_points.jsync:cli"