def evaluate(): print("Predicting...") speek("Predicting...") env = Env() env.read_env() project_id = 'recycle-pi' compute_region = 'us-central1' model_id = env("ML_MODEL_ID") file_path = 'temp.jpg' score_threshold = '0.0' automl_client = automl.AutoMlClient() model_full_id = automl_client.model_path(project_id, compute_region, model_id) prediction_client = automl.PredictionServiceClient() with open(file_path, "rb") as image_file: content = image_file.read() payload = {"image": {"image_bytes": content}} params = {} if score_threshold: params = {"score_threshold": score_threshold} response = prediction_client.predict(model_full_id, payload, params) items = [] for result in response.payload: fixed = "{:.5f}".format(result.classification.score) name = result.display_name score = fixed item = Item(name, score) items.append(item) sorted_items = sorted(items, key=lambda x: x.score) #for sorted_item in sorted_items: # print("Predicted class name: " + sorted_item.name) # print("Predicted class score: " + sorted_item.score) length = len(sorted_items) confident = sorted_items[length - 1] confident.name = confident.name.replace("_", " ") condition = float(confident.score) <= 0.3 if condition: recyclability = "Item may be trash, it may not be recyclable." speek(recyclability) confident.name = "trash" #speek("That's a " + confident.name + ", innit?" + recyclability) else: if confident.name == "soft plastic": recyclability = "Item is recyclable only at a specialist facility." else: recyclability = "Item is recyclable." vlc.MediaPlayer('recyclable.mp3').play() sleep(2) speek("That's a " + confident.name + ", " + recyclability) print("\nMost confident class name: " + confident.name) print("Most confident class score: " + confident.score) print(recyclability) sleep(5) runapi = IotAPI() runapi.post_measurement(1, "wasteType", confident.name) print("\nDetecting motion...") speek("Detecting motion...")
from environs import Env import pymongo import logging env = Env() env.read_env() DEBUG = env.bool("DEBUG", False) TOKEN = env("DISCORD_BOT_SECRET") DB_CONN = env('DB_CONN') DB_NAME = env('DB_NAME') GRAB_LOOT_CHANNEL = env.int('DISCORD_LOOT_GRAB_CHANNEL') WIKI_COMMANDS_ALLOW = env.int('DISCORD_WIKI_COMMANDS_ALLOW') logger = logging.getLogger('discord') logger.setLevel(logging.WARNING) handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w') handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s')) logger.addHandler(handler) DB_CLIENT = pymongo.MongoClient(DB_CONN) DB = DB_CLIENT[DB_NAME]
# -*- coding: utf-8 -*- """Application configuration. Most configuration is set via environment variables. For local development, use a .env file to set environment variables. """ from environs import Env env = Env() env.read_env(override=True) ENV = env.str('FLASK_ENV', default='production') DEBUG = ENV == 'development' SECRET_KEY = env.str('SECRET_KEY') # BCRYPT_LOG_ROUNDS = env.int('BCRYPT_LOG_ROUNDS', default=13) DEBUG_TB_ENABLED = DEBUG DEBUG_TB_INTERCEPT_REDIRECTS = False CACHE_TYPE = 'simple' # Can be "memcached", "redis", etc. SQLALCHEMY_TRACK_MODIFICATIONS = False WEBPACK_MANIFEST_PATH = 'webpack/manifest.json'
import os from environs import Env env = Env() env.read_env(path="./.env") def env(key, *, default=None): if key not in os.environ: return default return os.environ[key]
Any setting that is configured via an environment variable may also be set in a `.env` file in the project base directory. """ from os import path import django_heroku import dj_database_url from environs import Env from furl import furl # Build paths inside the project like this: path.join(BASE_DIR, ...) BASE_DIR = path.dirname(path.dirname(path.abspath(__file__))) env = Env() env.read_env(BASE_DIR, recurse=False) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY', 'v8sk33sy82!uw3ty=!jjv5vp7=s2phrzw(m(hrn^f7e_#1h2al') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DEBUG', True) # ALLOWED_HOSTS = [] # Application definition
response.json()['info'], item) print(data) mongoBulkImport(data, rates) return "[Historic Data Handler]: Operation Complete." except HTTPError as Http_err: print(str(Http_err)) except Exception as err: print(str(err)) if __name__ == '__main__': env = Env() env.read_env(".env", recurse=False) API_CREDENTIAL = env("API_CREDENTIAL") # Run this block to Import Current Rates # for reqItem in requestList: # # print("[Request]: " + reqItem['name']) # response = requestRates(reqItem, API_CREDENTIAL) # print("[Response]: " + json.dumps(response)) # # if response != "Error": # # responseLength = len(response) # itemList = fixDocument(response, reqItem) # mongoBulkImport(itemList, rates)
https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from environs import Env env = Env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def join(path): return os.path.join(BASE_DIR, path) env.read_env(recurse=False, path=join('.env'), override=True) # noqa SECRET_KEY = env('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = [] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth',
log_level = env.log_level("LOG_LEVEL") # => logging.DEBUG # providing a default value enable_login = env.bool("ENABLE_LOGIN", False) # => True enable_feature_x = env.bool("ENABLE_FEATURE_X", False) # => False # parsing lists gh_repos = env.list("GITHUB_REPOS") # => ['webargs', 'konch', 'ped'] coords = env.list("COORDINATES", subcast=float) # => [23.3, 50.0] """ 将环境变量定义到文件中,使用environs进行读取和加载,默认会读取本地当前运行目录下的 .env 文件 """ from environs import Env env = Env() # env.read_env() # read .env file, if it exists env.read_env(path='.env.test') # 读取自定义的文件 # 在.env文件中写入如下内容 # APP_DEBUG=false # APP_ENV=prod APP_DEBUG = env.bool('APP_DEBUG') APP_ENV = env.str('APP_ENV') print(APP_DEBUG) print(APP_ENV) """ 前缀处理 environs 还支持前缀处理,一般来说我们定义一些环境变量,如数据库的连接,可能有 host、port、password 等, 但在定义环境变量的时候往往会加上对应的前缀,如 MYSQL_HOST、MYSQL_PORT、MYSQL_PASSWORD 等,但在解析时,我们可以根据前缀进行分组处理 """ # export MYAPP_HOST=localhost # export MYAPP_PORT=3000 with env.prefixed("MYAPP_"):
def init_app(app: Flask): env = Env() env.read_env() config = config_selector[env.str("FLASK_ENV")] app.config.from_object(config)
from pathlib import Path import os import rest_framework import dj_database_url import django_heroku # variavel de ambiente from environs import Env # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # variaveis de ambiente conf env = Env() # local pra ler a key env.read_env(BASE_DIR / ".env", recurse=False) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False #hosts ALLOWED_HOSTS = ['anime-list-django.herokuapp.com', '127.0.0.1', 'localhost'] # na prodution COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False) # somente de deploy
def __init__(self, data_dir, log_level, log_to_file): env = Env() env.read_env() try: self.data_dir = env.str("PROGBOTT_DATA_DIR") except EnvError: self.data_dir = data_dir env.read_env(self.data_dir + "/.env") try: self.log_level = env.log_level("PROGBOTT_LOG_LEVEL") except EnvError: self.log_level = log_level try: self.log_to_file = env.str("PROGBOTT_LOG_FILE") except EnvError: self.log_to_file = log_to_file setting_path = self.data_dir + "/settings.json" extra = {"github": {}} try: with codecs.open(setting_path, "r", encoding="utf8") as f: fil = json.load(f) self.token = fil.get("token") self.prefix = fil.get("prefixes") extra = {**extra, **fil.get("extra")} except FileNotFoundError: pass try: with env.prefixed("PROGBOTT_"): self.token = env.str("TOKEN") self.prefix = env.list("PREFIXES") with env.prefixed("EXTRA_GITHUB_"): extra["github"]["secret"] = env.str("SECRET") extra["github"]["client_id"] = env.str("CLIENTID") extra["github"]["callback_url"] = env.str("CALLBACKURL", validate=URL()) except EnvError: pass if not self.prefix: self.prefix = "^" try: isinstance(self.token, str) except AttributeError: raise NoToken("No token found") try: self.extra = namedtuple("settings", extra.keys())(*extra.values()) except KeyError: pass
# For youtube-dl updates ~> "pip install --upgrade youtube-dl" from __future__ import unicode_literals from os import listdir from os.path import isfile from environs import Env import os import json import youtube_dl # ---------------------- # Constants # ---------------------- env = Env() env.read_env('../.env') DOWNLOAD_FOLDER = env('DOWNLOAD_FOLDER') SOURCE_FILE = env('SOURCE_FILE') BOOKMARK_ROOT_FOLDER_NAME = env('BOOKMARK_ROOT_FOLDER_NAME') # ---------------------- # Get urls # ---------------------- f = open(SOURCE_FILE, 'r') bookmarks = f.read() f.close() bookmarks_as_json = json.loads(bookmarks) music_root_folder_index = 0 for i in list(bookmarks_as_json['roots']['bookmark_bar']['children']): if i['name'] == BOOKMARK_ROOT_FOLDER_NAME:
import os import halo_app from environs import Env import json from halo_app.const import LOC, DEV, TST, PRD print("== start config") BASE_DIR = os.path.dirname(os.path.abspath(__file__)) env = Env() if 'HALO_STAGE' in os.environ: STAGE = os.environ['HALO_STAGE'] else: STAGE = LOC THE_ENV = os.path.join(BASE_DIR, '..', 'env', '.env.' + STAGE) env.read_env(path=THE_ENV, verbose=True) print('The .env file has been loaded. path= ' + str(THE_ENV)) print(env.dump()) def get_redis_host_and_port(): host = os.environ.get('REDIS_HOST', 'localhost') port = 63791 if host == 'localhost' else 6379 return dict(host=host, port=port) def get_email_host_and_port(): host = os.environ.get('EMAIL_HOST', 'localhost') port = 11025 if host == 'localhost' else 587 #fix http_port = 18025 if host == 'localhost' else 8025 return dict(host=host, port=port, http_port=http_port)
from environs import Env env = Env() env.read_env() SECRET_KEY = env('SECRET_KEY', '') DEBUG = env.bool('DEBUG', False) HTTP_HOST = env('HTTP_HOST', 'localhost') HTTP_PORT = env.int('HTTP_PORT', 8085) DB_HOST = env('DB_HOST', 'localhost') DB_PORT = env.int('DB_PORT', 5432) DB_NAME = env('DB_NAME', 'airy') DB_USERNAME = env('DB_USERNAME', 'airy') DB_PASSWORD = env('DB_PASSWORD', 'airy') TIMEZONE = env('TIMEZONE', 'Europe/Moscow') SMTP_SERVER = env('SMTP_SERVER', 'localhost') SMTP_PORT = env.int('SMTP_PORT', 25) SMTP_USER = env('SMTP_USER', '') SMTP_PASSWORD = env('SMTP_PASSWORD', '') SMTP_SENDER = env('SMTP_SENDER', 'no-reply@localhost') USER_NAME = env('USER_NAME', 'username') USER_PASSWORD = env('USER_PASSWORD', 'password') USER_EMAIL = env('USER_EMAIL')
from pathlib import Path from environs import Env # new env = Env() # new env.read_env() # new # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("DJANGO_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DJANGO_DEBUG") ALLOWED_HOSTS = ['.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # new
Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from environs import Env env = Env() env.read_env(recurse=False) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dyd!t0&)45q!h_1+jn-ra)^8jgu+4x&sbkx*(sp_7u-t$j^ctm' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DEBUG", False) ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", [".localhost"])
from environs import Env env = Env() env.read_env() # Read .env into os.environ, if it exists domains = { 'stage1': { 'home': 'https://staging.osf.io', 'api': 'https://api.staging.osf.io', 'files': 'https://files.us.staging.osf.io', 'cas': 'https://accounts.staging.osf.io', 'custom_institution_domains': ['https://staging-osf-nd.cos.io'], }, 'stage2': { 'home': 'https://staging2.osf.io', 'api': 'https://api.staging2.osf.io', 'files': 'https://files.us.staging2.osf.io', 'cas': 'https://accounts.staging2.osf.io', 'custom_institution_domains': [], }, 'stage3': { 'home': 'https://staging3.osf.io', 'api': 'https://api.staging3.osf.io', 'files': 'https://files.us.staging3.osf.io', 'cas': 'https://accounts.staging3.osf.io', 'custom_institution_domains': [], }, 'test': { 'home': 'https://test.osf.io', 'api': 'https://api.test.osf.io', 'files': 'https://files.us.test.osf.io', 'cas': 'https://accounts.test.osf.io',
import boto3 import simplejson as json from environs import Env env = Env() print(env.read_env()) def save_json_file(response,file_name): with open(file_name, 'w') as outfile: json.dump(response['Items'], outfile) dynamodb = boto3.resource('dynamodb','eu-west-1',aws_access_key_id=env("aws_access_key_id"), aws_secret_access_key=env("aws_secret_access_key")) table_mc_features = dynamodb.Table('mc_features_production') table_feature_users = dynamodb.Table('feature_users_production') save_json_file(table_feature_users.scan(),'features_users_production.json') save_json_file(table_mc_features.scan(),'data.json') # read_file('/Users/alisoliman/Development/Python/aiesecinternational-rnd/features_users_production.json')
import os import sys from github import Github from environs import Env env = Env() env.read_env() # read the .env file folderName = str(sys.argv[1]) # to get the folder name path = env("pp") # to get the path from .env file token = env('gt') # to get the github token form .env file _dir = path + '\\' + folderName # the path into the folder that the command made and will be the repo g = Github(token) # the main class to access github API user = g.get_user() # methods for login and get your account login = user.login repo = user.create_repo( folderName) # to make a new repo in your github account # the commands that will print inside the folder commands = [ f'echo"# {repo.name}" >> README.md', 'git init', 'git add README.md', 'git commit -m "Initial Commit"', 'git branch -M main', f'git remote add origin https://github.com/{login}/{folderName}.git', 'git push -u origin main', 'code .', ] if sys.argv[1] is not None:
import os from pathlib import Path from environs import Env from exchange_rater.app import create_app if __name__ == '__main__': current_path = os.path.dirname(os.path.abspath(__file__)) current_path = Path(current_path) root_path = current_path.parent env_path = os.path.join(root_path, '.env') env = Env() if os.path.exists(env_path): env.read_env(env_path) app = create_app() FLASK_APP_LOCAL_PORT = env.int('FLASK_APP_LOCAL_PORT', default=8000) app.run(host='0.0.0.0', port=FLASK_APP_LOCAL_PORT)
def run(self): import requests import os from environs import Env env = Env() env.read_env() API = env.str("API") auth_username = env.str("auth_username") auth_password = env.str("auth_password") if self.options['read']: if not self.options['--name'] and not self.options[ '--id'] and not self.options['--conf']: response = requests.get(API + "git/", auth=(auth_username, auth_password)) print(response.status_code, response.content.decode()) elif self.options['--name']: response = requests.get(API + "git/%s" % self.options['--name'], auth=(auth_username, auth_password)) print(response.status_code, response.content.decode()) elif self.options['--id']: response = requests.get(API + "git/id/%s" % self.options['--id'], auth=(auth_username, auth_password)) print(response.status_code, response.content.decode()) elif self.options['--conf']: response = requests.get( API + "git/config_set_id/%s" % self.options['--conf'], auth=(auth_username, auth_password)) print(response.status_code, response.content.decode()) if self.options['update']: data = {} if self.options['--url']: data['url'] = self.options['--url'] if self.options['--usr']: data['username'] = self.options['--usr'] if self.options['--pwd']: data['password'] = self.options['--pwd'] if self.options['--b']: data['branch'] = self.options['--b'] if self.options['--name']: data['module'] = self.options['--name'] response = requests.put(API + "git/%s" % self.options['<id>'], auth=(auth_username, auth_password), data=data) print(response.status_code, response.content.decode()) if self.options['delete']: response = requests.delete(API + "git/%s" % self.options['<id>'], auth=(auth_username, auth_password)) print(response.status_code, response.content.decode()) if self.options['create']: data = {} data['url'] = self.options['<git_url>'] data['username'] = self.options['<username>'] data['password'] = self.options['<password>'] data['branch'] = self.options['<branch>'] data['module'] = self.options['<module_name>'] response = requests.post( API + "git/insert/%s" % self.options['<configset_id>'], auth=(auth_username, auth_password), data=data) print(response.status_code, response.content.decode()) if self.options['check']: data = { 'url': self.options['<git_url>'], 'username': self.options['<username>'], 'password': self.options['<password>'], 'branch': self.options['<branch>'], 'module': self.options['<module_name>'] } response = requests.post(API + "git/git_module/check_git_creds", auth=(auth_username, auth_password), data=data) print(response.status_code, response.content.decode())
Any setting that is configured via an environment variable may also be set in a `.env` file in the project base directory. """ from os import path import django_heroku import dj_database_url from environs import Env from furl import furl # Build paths inside the project like this: path.join(BASE_DIR, ...) BASE_DIR = path.dirname(path.dirname(path.abspath(__file__))) env = Env() env.read_env(path.join(BASE_DIR, '.env'), recurse=False) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY', 'v8sk33sy82!uw3ty=!jjv5vp7=s2phrzw(m(hrn^f7e_#1h2al') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool('DEBUG', True) # True if you want to allow users to be able to create an account ALLOW_SIGNUP = env.bool('ALLOW_SIGNUP', True) # ALLOWED_HOSTS = []
import os from environs import Env env = Env() if os.environ.get('FLASK_ENV') is None or os.environ.get( 'FLASK_ENV') == 'production': env.read_env() else: env.read_env('.env.development') # You need to replace the next values with the appropriate values for your configuration basedir = os.path.abspath(os.path.dirname(__file__)) SQLALCHEMY_ECHO = False SQLALCHEMY_TRACK_MODIFICATIONS = True SQLALCHEMY_DATABASE_URI = f"postgresql://{env.str('DB_USER')}:{env.str('DB_PWD')}@{env.str('DB_HOST')}:{env.str('DB_PORT')}/{env.str('DB_NAME')}" JWT_SECRET_KEY = 'secret' PRE_PROCESSING_RAW = 'data/pre_processing' TRAIN_MODELS = 'data/models' TRAIN_PIPELINES = 'data/pipelines' TRAIN_TPOT_OUTPUT = 'data/tpot/output' PRE_PROCESSING_ENRICHED = 'data/enriched' TRAIN_FEATURES = 'data/train/features' TRAIN_TARGET = 'data/train/target' TEST_FEATURES = 'data/test/features' TEST_TARGET = 'data/test/target' BASE_URL = 'http://localhost:5000' UPLOAD_FOLDER = 'data/upload'
""" Production Configurations """ from .common import * # noqa from environs import Env, EnvValidationError import swiftclient # Normally you should not import ANYTHING from Django directly # into your settings, but ImproperlyConfigured is an exception. from django.core.exceptions import ImproperlyConfigured # Environment variables-based secrets env = Env() env.read_env() # also read .env file, if it exists def get_secret(setting, secret_type=env): """Get the secret variable or return explicit exception.""" try: return secret_type(setting) except EnvValidationError as e: raise ImproperlyConfigured(str(e)) # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/2.2/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not set SECRET_KEY = get_secret('DJANGO_SECRET_KEY')
import sys, os sys.path.append(os.getcwd()) import json from environs import Env from eva4.config.config import TrainingConfig env = Env() env.read_env("./cifar10.experiment.env.txt", recurse=False) config = TrainingConfig() print( "Experiment Config: ", json.dumps(config, default=lambda x: x.__dict__, sort_keys=False, indent=4)) from imageaug.transforms import Colorspace, RandomAdjustment, RandomRotatedCrop input_size = config.dataset.input_size crop_size = config.dataset.input_dimension angle_std = 7 # in degrees dataset_std = config.dataset.dataset_std dataset_mean = config.dataset.dataset_mean from torchvision import transforms # Define training transforms train_transforms = transforms.Compose([ transforms.RandomCrop(config.dataset.input_dimension, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(dataset_mean, dataset_std),
from environs import Env import slack env = Env() env.read_env("conf.d/99-secrets.yaml", recurse=False) slack_token = env("SLACK_TOKEN") client = slack.WebClient(token=slack_token) class SlackResource: def send_alert(self): client.chat_postMessage(channel="plex", text="New item added to Plex library.")
from environs import Env env = Env() env.read_env('.env') class Config: """Set configuration vars from .env file.""" # General Config IOT_ENDPOINT = env('IOT_ENDPOINT') CERT_PATH = "./cert.crt" PRIVATE_KEY_PATH = "./key.pem" ROOT_CA_PATH = "./AmazonRootCA1.pem" TOPIC_PREFIX = "sensors/" DEVICE_NAME = "1" MESSAGE_FREQUENCY = 0.1
import os from environs import Env BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = Env() DEBUG = env.bool('DEBUG', True) if DEBUG: env.read_env(os.path.join(BASE_DIR, 'env.dev')) SECRET_KEY = env.str("SECRET_KEY", "my$secret$key") ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', ['*'], subcast=str) CORS_HOSTS = env.list('CORS_HOSTS', ['*'], subcast=str) DATABASE = dict( driver=env.str("DB_DRIVER", 'postgresql'), user=env.str("DB_USER", 'postgres'), password=env.str("DB_PASSWORD", 'postgres'), host=env.str("DB_HOST", 'localhost'), port=env.str("DB_PORT", "5432"), dbname=env.str("DB_NAME", 'postgres'), url=env.str("DB_URL", None), ) if DATABASE['url'] is None: """ Build DATABASE url
from os.path import join, abspath, dirname from environs import Env SRC_DIR = dirname(abspath(__file__)) env = Env() env.read_env(join(SRC_DIR, ".env")) BOT_TOKEN = env.str("BOT_TOKEN") PERSON_DF_PATH = join(SRC_DIR, "person.csv") PERSON_SKILL_PATH = join(SRC_DIR, "person_skills.json") PROJECT_DF_PATH = join(SRC_DIR, "projects.csv") PROJECT_TAG_PATH = join(SRC_DIR, "project_tags.json") CONTRIBUTORS_PATH = join(SRC_DIR, "contributors.json") IMG_DIR = join(SRC_DIR, "profile_avatars")
class Config: ENV_VARS = { 'API_ALLOW_DEBUG', 'API_HOST', 'API_WS_PORT', 'CACHE_HOST', 'CACHE_PORT', 'CACHE_SIGN_KEY', 'CACHE_TIMEOUT', 'CACHE_TTL', 'ENV', 'LOG_LEVEL', 'ROLLBAR_ACCESS_TOKEN', 'ROLLBAR_LEVEL', 'VERSION', } def __init__(self): self._config = None self.env = Env() self.env.read_env() print( # noqa: T001 'Using overridden values for', self.ENV_VARS.intersection(os.environ.keys()), file=sys.stderr, ) def __getitem__(self, value): if self._config is None: raise RuntimeError('Config is not loaded, cannot access it') return self._config[value] def setup_config(self): # API must not start in prod like nev if we don't have a sign key for cache. # This is for security reasons. env = self.env.str('ENV', 'production') cache_sign_key = self.env.str('CACHE_SIGN_KEY', '') if env != 'development' and not cache_sign_key: raise EnvironmentError('You must supply a CACHE_SIGN_KEY env var') self._config = MappingProxyType({ 'api': { 'allow_debug': self.env.bool('API_ALLOW_DEBUG', False), # Binding to all interfaces, bandit don't allow this (#104) 'host': self.env.str('API_HOST', '0.0.0.0'), # noqa: S104 'ws_port': self.env.int('API_WS_PORT', 8181), }, 'cache': { 'host': self.env.str('CACHE_HOST', 'aot-redis'), 'port': self.env.int('CACHE_PORT', 6379), # Sign key must be of type bytes, not str. 'sign_key': cache_sign_key.encode('utf-8'), 'timeout': self.env.int('CACHE_TIMEOUT', 5), 'ttl': self.env.int('CACHE_TTL', 2 * 24 * 60 * 60), # 2 days }, # Amount of time to wait for pending futures before forcing them to shutdown. 'cleanup_timeout': self.env.int('CLEANUP_TIMEOUT', 5), 'env': env, 'log': { 'level': self.env.str('LOG_LEVEL', None), }, 'rollbar': { 'access_token': self.env.str('ROLLBAR_ACCESS_TOKEN', None), 'level': self.env.int('ROLLBAR_LEVEL', 30), }, 'version': self.env.str('VERSION', 'latest'), })
from pathlib import Path from environs import Env ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent env = Env() env.read_env(ROOT_DIR / ".env") VALID_COMMANDS = [ "vol", "search", "url", "playlist", "skip", "stop", "cancel", "shuffle", "queue", ] MAX_FILES = 20 MAX_AUDIO_DURATION = 15 * 60 MUMBLE_HOST = env("MUMBLE_HOST") MUMBLE_PORT = env.int("MUMBLE_PORT") MUMBLE_USER = env("MUMBLE_USER") MUMBLE_PASSWORD = env("MUMBLE_PASSWORD") REDIS_URL = env("REDIS_URL") DOWNLOAD_FOLDER = ROOT_DIR / "tmp"
import os from environs import Env print("start local") # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print('BASE_DIR : {}'.format(BASE_DIR)) env = Env() THE_ENV=os.path.join(BASE_DIR,'..','env','.env') env.read_env(path=THE_ENV) print('The .env file has been loaded. env: '+str(THE_ENV)) from .base import * ENV_TYPE = LOC ALLOWED_HOSTS = ['*','127.0.0.1',SERVER] DEBUG_TOOLBAR_CONFIG = { 'DISABLE_PANELS': [ 'debug_toolbar.panels.redirects.RedirectsPanel', ], 'SHOW_TEMPLATE_CONTEXT': True, } INTERNAL_IPS = ['127.0.0.1', '192.168.0.1'] #get local urls for services file_dir = os.path.dirname(__file__) file_path = os.path.join(file_dir,'..','..','env', 'loc_settings.json') with open(file_path, 'r') as fi:
def load_env_file(): env = Env() # Read .env into os.environ env.read_env() return env