Ejemplo n.º 1
0
 def get(self, value):
     args = self._arg.parse_args()
     result = getattr(args, value)
     if result is None:
         key = self._environ.get(value)
         if key:
             result = _getenv(key)
         else:
             result = None
     return result
Ejemplo n.º 2
0
 def get(self, value):
     args = self._arg.parse_args()
     result = getattr(args, value)
     if result is None:
         key = self._environ.get(value)
         if key:
             result = _getenv(key)
         else:
             result = None
     return result
Ejemplo n.º 3
0
    def _get_sd_notify_socket():
        """
        Get systemd notify socket address.

        Returns:
            str: Systemd notify socket address.
        """
        address = _getenv('NOTIFY_SOCKET', '')
        if address.startswith('@'):
            address = '\0%s' % address[1:]
        return address
Ejemplo n.º 4
0
def f_read(f_name):
    ret = ""
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            ret += f.read()
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                ret += f.read()
        except:
            pass
    return ret
Ejemplo n.º 5
0
def f_read(f_name):
    ret = ""
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            ret += f.read()
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                ret += f.read()
        except:
            pass
    return ret
Ejemplo n.º 6
0
def f_readlines(f_name):
    ret = []
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            ret += f.readlines()
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                ret += f.readlines()
        except:
            pass
    for i in range(len(ret)):
        ret[i] = ret[i].strip("\n")
    return ret
Ejemplo n.º 7
0
def f_readlines(f_name):
    ret = []
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            ret += f.readlines()
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                ret += f.readlines()
        except:
            pass
    for i in range(len(ret)):
        ret[i] = ret[i].strip("\n")
    return ret
Ejemplo n.º 8
0
def f_read_json(f_name):
    ret = {}
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            temp = _json.load(f)
            for a in temp:
                ret[a] = temp[a]
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                temp = _json.load(f)
                for a in temp:
                    ret[a] = temp[a]
        except:
            pass
    return ret
Ejemplo n.º 9
0
def file(url):
    """file(url) -> None

    Asynchronously open a session with "emacs" in file browser
    mode, looking at the resource from a given "file://" URL.

    Raises an exception for some failures.  Note, however, that
    as an asynchronous process spawn, other types of failures
    could occur later that are not trapped at call time.

    (Below are REAL testcases run by doctest!)

    >>> file('file:///System/Library')

    >>> try:
    ...        file('not a file url!')
    ... except ValueError as e:
    ...        print(e)
    not a file URL

    """
    url_info = _parse_file(url)
    path = url_info.get('path', None)
    if path is not None:
        if len(path) == 0:
            # default to the home directory
            from os import getuid as _getuid
            from pwd import getpwuid as _getpwuid
            (pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, \
                pw_dir, pw_shell) = _getpwuid(_getuid())
            path = pw_dir
            if path is None or len(path) == 0:
                from os import getenv as _getenv
                path = _getenv('HOME')
                if path is None:
                    path = '/'
        # emacs is a good choice because it has a command line
        # option to set a start location, it is an excellent file
        # browser and it can remain running to perform other tasks
        args = ['/usr/bin/emacs', "--file=%s" % path]
        ignored_session = quills.Session(args)
    else:
        raise ValueError("unsupported form of file URL")
Ejemplo n.º 10
0
def file(url):
    """file(url) -> None

    Asynchronously open a session with "emacs" in file browser
    mode, looking at the resource from a given "file://" URL.

    Raises an exception for some failures.  Note, however, that
    as an asynchronous process spawn, other types of failures
    could occur later that are not trapped at call time.

    (Below are REAL testcases run by doctest!)

    >>> file('file:///System/Library')

    >>> try:
    ...        file('not a file url!')
    ... except ValueError as e:
    ...        print(e)
    not a file URL

    """
    url_info = _parse_file(url)
    path = url_info.get('path', None)
    if path is not None:
        if len(path) == 0:
            # default to the home directory
            from os import getuid as _getuid
            from pwd import getpwuid as _getpwuid
            (pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, \
                pw_dir, pw_shell) = _getpwuid(_getuid())
            path = pw_dir
            if path is None or len(path) == 0:
                from os import getenv as _getenv
                path = _getenv('HOME')
                if path is None:
                    path = '/'
        # emacs is a good choice because it has a command line
        # option to set a start location, it is an excellent file
        # browser and it can remain running to perform other tasks
        args = ['/usr/bin/emacs', "--file=%s" % path]
        ignored_session = quills.Session(args)
    else:
        raise ValueError("unsupported form of file URL")
Ejemplo n.º 11
0
def f_read_json(f_name):
    ret = {}
    try:
        with open(_join(_expanduser("~"), ".klb/" + f_name)) as f:
            temp = _json.load(f)
            for a in temp:
                ret[a] = temp[a]
    except:
        pass
    if _getenv("SLAVE"):
        try:
            with open(_join(_expanduser("~"), ".slave/" + f_name)) as f:
                temp = _json.load(f)
                if len(ret) == 0:
                    ret = temp
                else:
                    for a in temp:
                        ret[a] = temp[a]
        except:
            pass
    return ret
Ejemplo n.º 12
0
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from os import getenv as _getenv

CONFIGURATION = {
    ## ending for all log files
    "logending": "log_v2",

    ## ODB2 connector settings
    "device": _getenv("CANADAPTER"),

    #### USB connected data reader
    "obd2reader": "BluetoothDataReader",
    "speed": "1",

    #### Blutooth connected data reader

    ## GPS daemon settings
    "gpsdPort": 2947,
    "gpsdHost": "localhost",

    ## display settings
    "refreshRate": 2,
    "height": 4,
    "width": 20,
Ejemplo n.º 13
0
import boto3
import jmespath
from os import getenv as _getenv
from functions.common import zoom_api_request

AWS_PROFILE = _getenv("AWS_PROFILE")
if AWS_PROFILE:
    boto3.setup_default_session(profile_name=AWS_PROFILE)

# wrap the default getenv so we can enforce required vars
def getenv(param_name, required=True):
    val = _getenv(param_name)
    if required and (val is None or val.strip() == ''):
        raise Exception(f"Missing environment variable {param_name}")
    return val

def zoom_admin_id():
    # get admin user id from admin email
    r = zoom_api_request(f"users/{getenv('ZOOM_ADMIN_EMAIL')}")
    return r.json()["id"]


def vpc_components():

    oc_cluster_name = getenv("OC_CLUSTER_NAME")
    opsworks = boto3.client("opsworks")

    stacks = opsworks.describe_stacks()
    vpc_id = jmespath.search(
        f"Stacks[?Name=='{oc_cluster_name}'].VpcId",
        stacks
Ejemplo n.º 14
0
from os import getenv as _getenv

if _getenv("SLAVE") and not _getenv("EXPORT_ME"):
    NAME = "28JHFAX"
else:
    NAME = "KLBFAX"
Ejemplo n.º 15
0
from pathlib import Path as _Path
from starlette.config import Config
from starlette.templating import Jinja2Templates
from starlette.staticfiles import StaticFiles
from .logging import LOGGING_CONFIG


def _import_config(path: _Path):
    if path.is_file():
        return Config(path)
    else:
        return Config(None)  # only os.environ


# Define in Dokerfile
APP_PROJECT = _getenv("APP_PROJECT", "ndlm_leak_monitoring_app")

PATH_LOCAL = _Path.home() / ".local"
PATH_CONFIG = PATH_LOCAL / "etc" / APP_PROJECT

_config = _import_config(PATH_CONFIG / ".env")
DEBUG = _config("DEBUG", cast=bool, default=False)

_path_here = _Path(__file__).parent
_templates = Jinja2Templates(directory=str(_path_here.parent / "templates"))

TemplateResponse = _templates.TemplateResponse
static_files = StaticFiles(directory=_path_here.parent / "static",
                           check_dir=True)

UVICORN_CONFIG = dict(host="0.0.0.0", port=8000, log_config=LOGGING_CONFIG)
Ejemplo n.º 16
0
from os.path import join as _join
from os.path import expanduser as _expanduser
from os.path import dirname as _dirname
from os.path import realpath as _realpath
from os.path import isdir as _isdir
from os import mkdir as _mkdir
from os import getenv as _getenv
import json as _json
import pickle
import config

if _getenv("SLAVE"):
    default_path = _join(_expanduser("~"), ".slave/")
else:
    default_path = _join(_expanduser("~"), ".klb/")


def test_dir(directory):
    if not _isdir(directory):
        try:
            _mkdir(directory)
        except:
            pass


test_dir(default_path)


def open_local(f_name, method="r"):
    try:
        return open(_join(_expanduser("~"), ".klb/" + f_name), method)
Ejemplo n.º 17
0
from os import getcwd as _getcwd
from os import getenv as _getenv
from os.path import normpath as _normpath

SUBREDDIT: str = _getenv("SUBREDDIT", "")
WEBHOOK_URL: str = _getenv("WEBHOOK_URL", "")

DB_URI: str = _getenv("DB_URI",
                      "sqlite:///" + (_normpath(_getcwd() + "/app.db")))

FEED_LIMIT: int = int(_getenv("FEED_LIMIT", 100))
REFRESH_TIME: int = int(_getenv("REFRESH_TIME", 60))

POST: bool = _getenv("POST", "true").lower() == "true"
FEED: bool = _getenv("FEED_ONLY", "true").lower() == "true"

DIRTY: int = int(_getenv("DIRTY", "86400"))
Ejemplo n.º 18
0
class ObjectUnsupportedOperation(AirfsInternalException):
    """Reraised as "io.UnsupportedOperation" by handle_os_exceptions."""


_OS_EXCEPTIONS = {
    ObjectNotFoundError: FileNotFoundError,
    ObjectPermissionError: PermissionError,
    ObjectExistsError: FileExistsError,
    ObjectNotADirectoryError: NotADirectoryError,
    ObjectIsADirectoryError: IsADirectoryError,
    ObjectSameFileError: _SameFileError,
    ObjectNotImplementedError: NotImplementedError,
    ObjectUnsupportedOperation: _UnsupportedOperation,
}
_FULLTRACEBACK = True if _getenv("AIRFS_FULLTRACEBACK") else False


@_contextmanager
def handle_os_exceptions():
    """
    Handles airfs exceptions and raise standard OS exceptions.
    """
    try:
        yield

    except AirfsInternalException as exception:
        exc_type, exc_value, _ = _exc_info()
        raise _OS_EXCEPTIONS.get(
            exc_type,
            OSError)(exc_value) from (exception if _FULLTRACEBACK else None)
Ejemplo n.º 19
0
def getenv(param_name, required=True):
    val = _getenv(param_name)
    if required and (val is None or val.strip() == ''):
        raise Exception(f"Missing environment variable {param_name}")
    return val
Ejemplo n.º 20
0
from uuid import uuid4 as _uuid4
from os import getenv as _getenv

APP_ENCRYPTION_ALGORITHM = _getenv("APP_ENCRYPTION_ALGORITHM", "HS256")
APP_SECRET_KEY = _getenv("APP_SECRET_KEY",
                         "d7da8827-b5d7-4820-9528-e501aa3ab787")
APP_CORS_ORIGINS = _getenv(
    "APP_CORS_ORIGINS",
    "http://localhost:8080,http://192.168.56.124:8080").split(",")
INGREDIENTS_UNITS = ('grammes', 'millilitres', 'kilogrammes', 'litres',
                     'cuillere à soupe', 'cuillère à café')
INGREDIENTS_CATEGORIES = ('Viande', 'Poisson', 'Fruits et Légumes',
                          'Epicerie sucrée', 'Epicerie salée', 'Boulangerie',
                          'Fromage')

SHOPPING_DATABASE_URI = _getenv("SHOPPING_DATABASE_URI",
                                "mongodb://localhost:27017/shopping")
#
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from os import getenv as _getenv

CONFIGURATION = {
    ## ODB2 connector settings
    "device":     _getenv("CANADAPTER"),
    
    #### USB connected data reader
    "obd2reader": "SerialDataReader",
    "speed":      "S6",

    #### Blutooth connected data reader

    ## GPS daemon settings
    "gpsdPort":  2947,
    "gpsdHost":  "localhost",

    ## display settings
    "refreshRate":  2,
    "height":       4,
    "width":       20,
Ejemplo n.º 22
0
def slow(test):
	"Decorator for slow tests -- turned off with the FAST=1 "
	if _getenv('FAST'):
		return unittest.skip('Test too slow in FAST mode')(test)
	return test
Ejemplo n.º 23
0
# -*- coding: utf-8 -*-
from logging.config import dictConfig as _dictConfig
from os import getenv as _getenv
from urllib.parse import urlparse as _urlparse


DEFAULT_PORT = 5512

SENTRY_DSN = _getenv("SENTRY_DSN")

LOGS_LOCATION = _getenv("LOGS_LOCATION")

DB_ENV = "TRANSLATIONS_SERVER_DB_URL"

TRANSLATIONS_SERVER_DB_URL = _getenv(DB_ENV)

TRANSLATIONS_SERVER_TEST_DB_URL = _getenv(
    "TRANSLATIONS_SERVER_TEST_DB_URL", "")  # optional

DB_MIN_CONNECTIONS = 0

DB_MAX_CONNECTIONS = 10

WORKERS = 20

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard_formatter": {
            "format": "[%(asctime)s] [%(process)d] [%(levelname)s] [%(name)s]:"
Ejemplo n.º 24
0
def getenv(key: str, default: T = None) -> T:
    value = _getenv(key, default)
    try:
        return literal_eval(value)
    except (ValueError, SyntaxError):
        return value
Ejemplo n.º 25
0
#!/usr/bin/python
from os import getenv as _getenv

DEBUG = True
SESSION_BACKEND = 'inmem'  # in memory kv store
API_VERSION = 'devel'
API_PROMPT = "Bus Tracker API Server"
API_DESCRIPTION = "Tracking the buses for you since 2017."
API_ROOT = '127.0.0.1:5000'
SQLALCHEMY_DATABASE_URI = 'sqlite:///data/bus-tracker.db'

# if there is environment variable prefixed with _prefix, override above
# variables only upper-case variables without underscore prefix will be
# overriden it might be useful to export environment variables
# in a -gitignored- *.conf file then source it
_prefix = "BUSTRACKER_"
_locals = locals()
_config_variables = filter(lambda x: not x.startswith('_') and x.isupper(),
                           _locals.keys())

for _variable in _config_variables:
    _locals[_variable] = _getenv(_prefix + _variable, _locals[_variable])
Ejemplo n.º 26
0
#!/usr/bin/env python
import configparser as _configparser
from os import getenv as _getenv
from os import path as _path

config_dir = _path.dirname(__file__)
env = _getenv('DBENV', 'development')

env = (env if env != "" else 'development')

Config = _configparser.ConfigParser()
Config.read(_path.join(config_dir, env, 'config.ini'))
Ejemplo n.º 27
0
from os.path import join as _join
from os.path import expanduser as _expanduser
from os.path import dirname as _dirname
from os.path import realpath as _realpath
from os.path import isdir as _isdir
from os import mkdir as _mkdir
from os import getenv as _getenv
import json as _json
import pickle

if _getenv("SLAVE"):
    default_path = _join(_expanduser("~"), ".slave/")
else:
    default_path = _join(_expanduser("~"), ".klb/")

def test_dir(directory):
    if not _isdir(directory):
        try:
            _mkdir(directory)
        except:
            pass

def open_local(f_name, method="r"):
    try:
        return open(_join(_expanduser("~"), ".klb/" + f_name),method)
    except:
        folder = _dirname(_realpath(__file__))
        return open(_join(folder, "blank_file"))

def f_readlines(f_name):
    ret = []