def main(): parser = argparse.ArgumentParser( description='MosaicMe Cacher. Lists the buckets "mosaic-outlarge" and "mosaic-outsmall", generates a JSON object and stores it on the Redis cache to be consumed by the Web app.') parser.add_argument('-c', '--config', help='Path to the Dotenv file. If not provided, it will try to get it from the "config" directory.', required=False) args = parser.parse_args() if args.config: config_path = args.config if not os.path.exists(config_path): logger.error('Config file not found at {}'.format(config_path)) sys.exit(2) logger.info('Reading dotenv file...') dotenv.read_dotenv(config_path) try: s3_access_key = os.environ['S3_ACCESS_KEY'] s3_secret_key = os.environ['S3_SECRET_KEY'] s3_host = os.environ['S3_HOST'] s3_port = int(os.environ['S3_PORT']) s3_is_secure = json.loads(os.environ['S3_HTTPS'].lower()) s3_http_proto = 'https' if s3_is_secure else 'http' redis_host = os.environ['REDIS_HOST'] redis_port = int(os.environ['REDIS_PORT']) redis_db = int(os.environ['REDIS_DB']) except KeyError, e: logger.error('Could not obtain environment variable: %s', str(e)) sys.exit(3)
def main(): parser = argparse.ArgumentParser( description='MosaicMe Twitter Collector. Listens on a hashtag and extracts the tweeted images.') parser.add_argument('-t', '--hashtag', help='List of comma-separated hashtags. Overwritten by MOSAIC_LISTEN_HASHTAG environment variable if present.', required=False) parser.add_argument('-b', '--bucket', help='Bucket. Overwritten by MOSAIC_BUCKET environment variable if present', required=False) parser.add_argument('-q', '--queue', help='Queue. If provided, it will send a message with the filename to the given queue. Overwritten by MOSAIC_QUEUE environment variable if present.', required=False) parser.add_argument('-c', '--config', help='Path to the Dotenv file to load environment variables.', required=False) args = parser.parse_args() hashtags = os.getenv('MOSAIC_LISTEN_HASHTAG', args.hashtag) if not hashtags: logger.error('No hashtag provided.') sys.exit(1) hashtags = hashtags.split(",") hashtags = map(lambda x: '#'+x, hashtags) logger.info("Hashtags: %r" % (hashtags, )) bucket = os.getenv('MOSAIC_BUCKET', args.bucket) if not bucket: logger.error('No bucket provided.') sys.exit(2) logger.info("Bucket: %s" % (bucket, )) queue = os.getenv('MOSAIC_QUEUE', args.queue) if queue: logger.info("Queue: %s" % (queue, )) if args.config: config_path = args.config if not os.path.exists(config_path): logger.error('Config file not found at {}'.format(config_path)) sys.exit(3) logger.info('Reading dotenv file...') dotenv.read_dotenv(config_path) try: twitter_consumer_key = os.environ['TWITTER_CONSUMER_KEY'] twitter_consumer_secret = os.environ['TWITTER_CONSUMER_SECRET'] twitter_access_token = os.environ['TWITTER_ACCESS_TOKEN'] twitter_access_token_secret = os.environ['TWITTER_ACCESS_TOKEN_SECRET'] twitter_username = os.environ['TWITTER_USERNAME'] s3_access_key = os.environ['S3_ACCESS_KEY'] s3_secret_key = os.environ['S3_SECRET_KEY'] s3_host = os.environ['S3_HOST'] s3_port = int(os.environ['S3_PORT']) s3_is_secure = json.loads(os.environ['S3_HTTPS'].lower()) rmq_host = os.getenv('RABBITMQ_HOST', 'rabbit') rmq_port = int(os.environ['RABBITMQ_PORT']) rmq_user = os.environ['RABBITMQ_USER'] rmq_password = os.environ['RABBITMQ_PASSWORD'] except KeyError, e: logger.error('Could not obtain environment variable: %s', str(e)) sys.exit(4)
def init_env(env_file): """ Loads environment variables from env_file to environ. """ root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) env_file = os.path.join(root_path, '.env') dotenv.read_dotenv(dotenv=env_file)
def read_config(self): if os.path.isfile(self.configfile): dotenv.read_dotenv(self.configfile) if "VIRTUALENV" in os.environ: os.environ["PATH"] = ":".join([os.path.join(os.environ["VIRTUALENV"], "bin"), os.environ["PATH"]]) self.configured = True else: self.configured = False
def test_warns_if_file_does_not_exist(self): with warnings.catch_warnings(record=True) as w: read_dotenv('.does_not_exist') self.assertEqual(len(w), 1) self.assertTrue(w[0].category is UserWarning) self.assertEqual( str(w[0].message), "Not reading .does_not_exist - it doesn't exist." )
def init_environment(filename): if filename is None: return path = normalize_path(filename) try: dotenv.read_dotenv(path) except Exception: raise
def __init__(self, dotenv_file, debug_level="INFO"): logging.basicConfig(level=debug_level) dotenv.read_dotenv(dotenv_file) db_connection_dict = { 'database': os.environ['TILESTACHE_DATABASE_NAME'], 'user': os.environ['TILESTACHE_DATABASE_USERNAME'], 'password': os.environ['TILESTACHE_DATABASE_PASSWORD'], 'host': os.environ['TILESTACHE_DATABASE_HOST'], 'port': os.environ['TILESTACHE_DATABASE_PORT'], } dirpath = os.environ['TILESTACHE_TMP_DIR'] connection = psycopg2.connect(**db_connection_dict) config = PGConfiguration(connection, dirpath, debug_level) TileStache.WSGITileServer.__init__(self, config, False)
def check_dotenv(local=True): """ Check if there is a .env file, otherwise create it. Works ATM only locally. """ require('prj_name') require('prj_path') require('user') dotenv_filename = '%(prj_path)s/%(prj_name)s/.env' % env if not os.path.isfile(dotenv_filename): print('I will now ask for the passwords to use for ' + ('local ' if local else '') + 'database and ' + 'email account access. If one is empty, I’ll use the non-empty ' + 'for both. If you leave both empty, I won’t create a database ' + 'user.') prompt('Please enter DATABASE_PASSWORD for user %(prj_name)s:' % env, key='database_password') prompt('Please enter EMAIL_PASSWORD for user %(user)s:' % env, key='email_password') if env.database_password and not env.email_password: env.email_password = env.database_password if env.email_password and not env.database_password: env.database_password = env.email_password # TODO: check input for need of quoting! # create .env and set database and email passwords from django.utils.crypto import get_random_string chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#^&*(-_=+)' # without % and $ dotenv = 'SECRET_KEY="%s"\n' % get_random_string(50, chars) dotenv += 'DJANGO_SETTINGS_MODULE=settings%s\n' % ('.local' if local else '') dotenv += 'DATABASE_PASSWORD="******"\n' % env dotenv += 'EMAIL_PASSWORD="******"\n' % env try: dotenv_file = open(dotenv_filename, 'x', encoding='utf-8') dotenv_file.write(dotenv) except TypeError: # Python 2.x dotenv_file = open(dotenv_filename, 'w') dotenv_file.write(dotenv.encode('utf-8')) dotenv_file.close() else: print('Reading existing .env file...') import dotenv dotenv.read_dotenv(dotenv_filename) env.database_password = os.environ['DATABASE_PASSWORD']
def connect(): from mongolog.handlers import MongoHandler from configurations import importer import os import logging from hbproject import settings import dotenv dotenv.read_dotenv() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hbproject.settings') os.environ.setdefault('DJANGO_CONFIGURATION', 'Development') importer.install() log = logging.getLogger('heliosburn') log.setLevel(logging.DEBUG) log.addHandler(MongoHandler.to(db=settings.MONGODB_DATABASE['production'], collection='log')) return log
def bootstrap(): """application bootstrap""" global _bootstrapped if _bootstrapped: return project_dir = os.path.dirname(__file__) # insert apps and libs into the system path sys.path.insert(0, os.path.join(project_dir, 'apps')) sys.path.insert(0, os.path.join(project_dir, 'libs')) import heroku_env dotenv.read_dotenv() # from envparse import Env # this converts (('Hoat Le', '*****@*****.**'),) to u'((Hoat Le, [email protected]),))' # which is not expected # Env.read_envfile() heroku_env.set_env() _bootstrapped = True
def main(): parser = argparse.ArgumentParser( description='MosaicMe Twitter History. Collects images from tweets containing the given hashtag. If a file called "max_id" is placed in the same directory, it will start processing tweets older than the ID contained in the file, otherwise it will start from the most recent tweet and create and update the "max_id" file.') parser.add_argument('-t', '--hashtag', help='Hashtag', required=True) parser.add_argument('-b', '--bucket', help='Bucket', required=True) parser.add_argument('-c', '--config', help='Path to the Dotenv file. If not provided, it will try to get it from the base directory.', required=False) args = parser.parse_args() if args.config: config_path = args.config else: config_path = os.path.join(BASE_DIR, '../../', '.env') if not os.path.exists(config_path): logger.error('Config file not found at {}'.format(config_path)) sys.exit(2) logger.info('Reading dotenv file...') dotenv.read_dotenv(config_path) try: twitter_consumer_key = os.environ['TWITTER_CONSUMER_KEY'] twitter_consumer_secret = os.environ['TWITTER_CONSUMER_SECRET'] twitter_access_token = os.environ['TWITTER_ACCESS_TOKEN'] twitter_access_token_secret = os.environ['TWITTER_ACCESS_TOKEN_SECRET'] s3_access_key = os.environ['S3_ACCESS_KEY'] s3_secret_key = os.environ['S3_SECRET_KEY'] s3_host = os.environ['S3_HOST'] s3_port = int(os.environ['S3_PORT']) s3_is_secure = json.loads(os.environ['S3_HTTPS'].lower()) except KeyError, e: logger.error('Could not obtain environment variable: %s', str(e)) sys.exit(3)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import sys import dotenv import logging logger = logging.getLogger(__name__) from os.path import expanduser home = expanduser("~") dotenv.read_dotenv(os.path.join('.','.env')) DEPLOYMENT = os.environ.get('DEPLOYMENT','production') SITE_URL = os.environ.get('SITE_URL','https://localhost') BASE_DIR = os.environ.get('BASE_DIR',os.path.dirname(os.path.realpath(__file__))) APPLICATION_TITLE = os.environ.get('APPLICATION_TITLE',"Test Application") BRAND = '' DB_NAME = os.environ.get('DB_NAME','mysite') DB_USER = os.environ.get('DB_USER','db_user') DB_PASS = os.environ.get('DB_PASS','ee0Er8Hbg9') DEBUG = bool(os.environ.get('DEBUG', False)) DEBUG_VALUE = os.environ.get('DEBUG', False) PATH_LOG = os.path.join(BASE_DIR,'log') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#QM\\D8lfx9CZLW5V!BAcm)l\\mKX95KuZ:r4!BRcL)Ir]5Tsq3y'
from fabric.api import run, sudo from fabric.api import prefix, warn, abort from fabric.api import settings, task, env, shell_env from fabric.context_managers import cd from datetime import datetime import json import os import dotenv import requests dotenv.read_dotenv('environment') env.hosts = ['web2.openprescribing.net'] env.forward_agent = True env.colorize_errors = True env.user = '******' environments = { 'production': 'openprescribing', 'staging': 'openprescribing_staging' } # This zone ID may change if/when our account changes # Run `fab list_cloudflare_zones` to get a full list ZONE_ID = "198bb61a3679d0e1545e838a8f0c25b9" # Newrelic Apps NEWRELIC_APPIDS = {
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": if 'test' in sys.argv: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ironcage.settings.test") else: dotenv.read_dotenv() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ironcage.settings.local") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv)
""" WSGI config for itassets project. It exposes the WSGI callable as a module-level variable named ``application``. """ import dotenv from django.core.wsgi import get_wsgi_application import os from pathlib import Path # These lines are required for interoperability between local and container environments. d = Path(__file__).resolve().parents[1] dot_env = os.path.join(str(d), '.env') if os.path.exists(dot_env): dotenv.read_dotenv(dot_env) # Must precede dj_static imports. from dj_static import Cling, MediaCling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'itassets.settings') application = Cling(MediaCling(get_wsgi_application()))
# -*- coding: utf-8 -*- __author__ = 'lundberg' """Production settings and globals.""" from os import environ import dotenv from common import * # Read .env from project root dotenv.read_dotenv(join(SITE_ROOT, '.env')) ########## DEBUG CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = bool(environ.get('DEBUG', '')) ########## END DEBUG CONFIGURATION ########## PROJECT CONFIGURATION EDUROAM_META_DATA = environ.get('EDUROAM_META_DATA', '') ########## PROJECT CONFIGURATION ########## ALLOWED HOSTS CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts ALLOWED_HOSTS = environ.get('ALLOWED_HOSTS', '').split() ########## END ALLOWED HOST CONFIGURATION ########## SENTRY CONFIGURATION # Set your DSN value RAVEN_CONFIG = { 'dsn': environ.get('SENTRY_DSN', ''), }
import os import os.path import dotenv from gitstatic.settings_helpers import env if 'GITSTATIC_DOTENV' in os.environ: dotenv.read_dotenv(os.environ['GITSTATIC_DOTENV']) PROPAGATE_EXCEPTIONS = True ''' The directory to put files in. Static content is placed into $WEB_ROOT/$CNAME for each site. So, for example, if your webroot is /var/www/gitstatic, and your site has a cname of blog.my-awesome-site.com, the static content will go into /var/www/gitstatic/blog.my-awesome-site.com. You should configure your http server to do virtual hosting based on the directories in WEB_ROOT. ''' WEB_ROOT = env('GITSTATIC_WEB_ROOT') if not os.path.isabs(WEB_ROOT): raise RuntimeError( 'WEB_ROOT must be an absolute path (got: %s)' % WEB_ROOT) ''' A directory to place jobs in. This directory shouldn't be used for anything else. Example: /var/www/jobs ''' JOBS_DIR = env('GITSTATIC_JOBS_DIR') if not os.path.isabs(JOBS_DIR): raise RuntimeError(
""" WSGI config for tbk project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os import dotenv from django.core.wsgi import get_wsgi_application dot_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), "../.env") if os.path.exists(dot_file): dotenv.read_dotenv(dot_file) os.environ.setdefault("WS_DJANGO_RUN_MODE", "sync") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tbk.settings") application = get_wsgi_application()
""" WSGI config for carboi project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os import dotenv from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv.read_dotenv(BASE_DIR + "/.env") environment = os.environ.get("CARBOI_ENV", "development") os.environ["DJANGO_SETTINGS_MODULE"] = "carboi.settings.{}".format(environment) application = get_wsgi_application()
# SET UP NLP LIB LOGGING NLP_LIB_LOG_FILENAME = LOG_PATH + 'nlp_log.log' # Set up a specific logger with our desired output level nlp_logger = logging.getLogger('NLPLibLogger') nlp_logger.setLevel(logging.DEBUG) # Add the log message handler to the logger handler = logging.handlers.RotatingFileHandler(NLP_LIB_LOG_FILENAME, maxBytes=10 * 1024 * 1024, backupCount=5) formatter = logging.Formatter("%(asctime)s\t%(levelname)s\t%(message)s", "%Y-%m-%d %H:%M:%S") handler.setFormatter(formatter) nlp_logger.addHandler(handler) if os.path.exists(CONFIG_PATH): dotenv.read_dotenv(CONFIG_PATH) else: ner_logger.debug( 'Warning: no file named "config" found at %s. This is not a problem if your ' 'datastore(elasticsearch) connection settings are already available in the environment', CONFIG_PATH) # TODO Consider prefixing everything config with HAPTIK_NER_ because these names are in the environment and so are # TODO lot of others too which may conflict in name. Example user is already using some another instance of # TODO Elasticsearch for other purposes ENGINE = os.environ.get('ENGINE') if ENGINE: ENGINE = ENGINE.lower() ES_URL = os.environ.get('ES_URL') ES_HOST = os.environ.get('ES_HOST') ES_PORT = os.environ.get('ES_PORT')
from __future__ import absolute_import, unicode_literals import os from pathlib import Path import dotenv from celery import Celery dotenv.read_dotenv(Path(__file__).parent / ".env") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_bike.settings.dev") app = Celery("django_bike") # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django app configs. app.autodiscover_tasks()
# Copyright 2018 Biz2Credit Infoservices Pvt Ltd. All Rights Reserved. # # Author: Mohit Kumar # Version: 1.0.0 # # Loads all configuration from ENV file import os from pathlib import Path try: from dotenv import read_dotenv # Load the env file from the APP root directory env_path = Path('..') / '.env' read_dotenv(env_path) except: from dotenv import load_dotenv # Load the env file from the APP root directory env_path = Path('..') / '.env' load_dotenv(env_path) #Loads all configuration from ENV file DB_HOST = os.environ.get('DB_HOST', None) DB_PORT = os.environ.get('DB_PORT', None) DB_NAME = os.environ.get('DB_NAME', None) DB_USER = os.environ.get('DB_USER', None) DB_PASSWORD = os.environ.get('DB_PASSWORD', None) DB_COLLECTION = os.environ.get('DB_COLLECTION', None) DB_PROVIDER = os.environ.get('DB_PROVIDER', None) SESSION_EXPIRY_TIME=os.environ.get('SESSION_EXPIRY_TIME', None) SUPERUSEREMAIL=os.environ.get('SUPERUSEREMAIL', None)
def test_defaults_to_dotenv(self): read_dotenv() self.assertEqual(os.environ.get('DOTENV'), 'true')
flash, session ) from flask_mail import Mail, Message from utilities import paginate_model, combine_identical_parameters, handle_fields import re mail = Mail() metpet_ui = Flask(__name__) metpet_ui.config.from_object("config") mail.init_app(metpet_ui) metpet_ui.config["UPLOAD_FOLDER"] = "./temp" metpet_ui.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # limits maximum size of contents to 16 MB dotenv.read_dotenv("../app_variables.env") @metpet_ui.route("/") def index(): return render_template("index.html", auth_token = session.get("auth_token",None), email = session.get("email",None), name = session.get("name",None) ) @metpet_ui.route("/help/") # links to .md files in user guide git def help(): links = [('Creating a profile','https://raw.githubusercontent.com/metpetdb/userguide/master/creating-a-profile.html'), \ ('Uploading data','https://raw.githubusercontent.com/metpetdb/userguide/master/uploading-data.html'), \ ('Viewing your own data','https://raw.githubusercontent.com/metpetdb/userguide/master/viewing-data.html'),\
from django.db import transaction import dotenv dotenv.read_dotenv('../../env_variables.env') from tastyapi.models import Sample, Subsample, ChemicalAnalyses, Image @transaction.atomic def main(): for sample in Sample.objects.all(): sample.subsample_count = sample.subsamples.all().count() sample.image_count = sample.images.all().count() chem_analyses_count = 0 img_count = 0 for subsample in sample.subsamples.all(): chem_analyses_count += subsample.chemical_analyses.all().count() img_count += subsample.images.all().count() sample.chem_analyses_count = chem_analyses_count sample.image_count += img_count sample.save() for subsample in Subsample.objects.all(): subsample.image_count = subsample.images.all().count() subsample.chem_analyses_count = subsample.chemical_analyses.all().count() subsample.save() if __name__ == "__main__": main()
""" WSGI config for future_of_thainlp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import dotenv import os from django.core.wsgi import get_wsgi_application # Select and read environment variables from .env file dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env' if os.environ.get('DJANGO_ENV', '').lower() == 'production' else '.env.debug'), override=True) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'future_of_thainlp.settings') application = get_wsgi_application()
import os import dotenv dotenv.read_dotenv(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".env"))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conf.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
def get_environ(key): return True if key in os.environ and os.environ[key].lower() == "true" else False def get_env(key): return True if os.getenv(key) is not None and os.getenv(key).lower() == "true" else False def get_dotenv(): if get_environ('USE_DOCKER'): return '.env.docker.prod' if get_environ('IS_PROD') else '.env.docker.dev' return '.env.prod' if get_environ('IS_PROD') else '.env.dev' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), get_dotenv())) IS_PROD = get_environ('IS_PROD') DEBUG = not IS_PROD SECRET_KEY = os.getenv('SECRET_KEY') # General settings ROOT_URLCONF = 'app.urls' WSGI_APPLICATION = 'app.wsgi.application' AUTH_USER_MODEL = 'models.User' DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' SITE_ID = 1 # Files definitions
""" WSGI config for info_reborn project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os, sys BASE_DIR = os.path.dirname(os.path.dirname(__file__)) ENV = os.path.join(BASE_DIR,'.env') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") import dotenv dotenv.read_dotenv(ENV) from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
import dotenv dotenv.read_dotenv(dotenv='.env') from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
""" WSGI config for stoic_web project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os import dotenv #sys.path.insert(0,os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])) dotenv.read_dotenv(os.path.dirname(os.path.abspath(__file__))+"/.env") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stoic_web.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
""" ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os import sys filepath = os.path.abspath(__file__) sys.path.append( os.path.dirname(os.path.dirname(os.path.dirname( os.path.dirname(filepath))))) import dotenv dotenv.read_dotenv( os.path.join(os.path.dirname(os.path.dirname(filepath)), '.env')) import django from django.core.asgi import get_asgi_application from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import django_eventstream os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") application = ProtocolTypeRouter({ 'http': URLRouter([ url( r'^rooms/(?P<room_id>[^/]+)/events/',
from django.db import transaction import dotenv dotenv.read_dotenv('../../env_variables.env') from tastyapi.models import Sample, Subsample, ChemicalAnalyses, Image @transaction.atomic def main(): for sample in Sample.objects.all(): sample.subsample_count = sample.subsamples.all().count() sample.image_count = sample.images.all().count() chem_analyses_count = 0 img_count = 0 for subsample in sample.subsamples.all(): chem_analyses_count += subsample.chemical_analyses.all().count() img_count += subsample.images.all().count() sample.chem_analyses_count = chem_analyses_count sample.image_count += img_count sample.save() for subsample in Subsample.objects.all(): subsample.image_count = subsample.images.all().count() subsample.chem_analyses_count = subsample.chemical_analyses.all( ).count() subsample.save() if __name__ == "__main__": main()
For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import dj_database_url import dotenv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv.read_dotenv(os.path.join(BASE_DIR, '.env')) ENVIRONMENT = os.environ.get('ENVIRONMENT') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = ENVIRONMENT == 'development' or os.environ.get('DEBUG', False) ALLOWED_HOSTS = ['*'] # Application definition
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import dotenv def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": dotenv.read_dotenv(".env") main()
import os import dotenv from django.core.wsgi import get_wsgi_application dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "seating_site.settings") application = get_wsgi_application()
def test_can_read_dotenv_given_its_directory(self): read_dotenv(self.dotenv_dir) self.assertEqual(os.environ.get('DOTENV'), 'true')
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 os.path import join, dirname import dotenv import sys from datetime import timedelta dotenv_path = join(dirname(__file__), '../.env') dotenv.read_dotenv(dotenv_path) # 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 = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv('DEBUG')
def test_reads_the_file(self): read_dotenv('.env') self.assertEqual(os.environ.get('DOTENV'), 'true')
#!/usr/bin/env python3 from __future__ import absolute_import, unicode_literals import os import dotenv import environ from celery import Celery env = environ.Env() # set the default Django settings module for the 'celery' program. project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if not os.getenv('BUILD_ON_TRAVIS'): dotenv.read_dotenv(os.path.join(project_path, '.env')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings_dev') app = Celery('core', broker='amqp://', include=['apps.main.tasks']) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. # app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks()
# Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'apps/static'), ) dotenv.read_dotenv(os.path.join(BASE_DIR, '.env')) FOO = (os.environ['FOO']) LOGIN_URL = '/harvest/login' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. #os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings.get_env_variable('DJANGO_SETTINGS_MODULE')) current_dir = os.path.dirname(__file__) try: # django-dotenv-rw (Python 2.7) try: dotenv.load_dotenv(os.path.join(current_dir, '.env')) except UserWarning: dotenv.load_dotenv(os.path.abspath(os.path.join(current_dir, '../../..', '.env'))) except AttributeError: # django-dotenv (Python 3) try: dotenv.read_dotenv(os.path.join(current_dir, '.env')) except UserWarning: dotenv.read_dotenv(os.path.abspath(os.path.join(current_dir, '../../..', '.env'))) app = Celery('cerebrale') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass import dotenv env_file = os.path.join(BASE_DIR, '.env') # dotenv.read_dotenv(env_file) DEBUG = bool(int(os.environ.get('DEBUG', '0'))) TEMPLATE_DEBUG = DEBUG IN_DEV = bool(int(os.environ.get('IN_DEV', '0'))) ADMINS = ( ('Edilio Gallardo', '*****@*****.**'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
import os import dotenv import newrelic.agent os.environ['QLY_REALM'] = 'production' file_path = os.path.dirname(os.path.realpath(__file__)) project_root = ('/').join(os.path.abspath(file_path).split(os.sep)[:-2]) dotenv.read_dotenv('/var/qly/.env') newrelic.agent.initialize(project_root + '/newrelic.ini', os.environ['QLY_REALM']) from quietly.wsgi.base import *
gettext = lambda s: s def env(env_name): return os.environ.get(env_name) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.abspath( os.path.join(os.path.dirname(__file__), "../.."), ) # load .env file dotenv.read_dotenv("{0}/.env".format(PROJECT_DIR)) SITE_ID = 1 APP_ROOT_ENDPOINT = "/" LOGIN_URL = None LOGOUT_URL = None LOGIN_REDIRECT_URL = None EMAIL_HOST = "localhost" EMAIL_PORT = 25 SECRET_KEY = env('DJANGO_SECRET_KEY') # Application definition
# -*- coding: utf-8 -*- # Helper file to be loaded via both manage.py and settings import dotenv import dj_database_url # NOQA from getenv import env # NOQA def project_path(thefile, *args): from os.path import join, dirname, abspath root = abspath(join(dirname(abspath(thefile)), *args)) return lambda *a: join(root, *a) project_path = project_path(__file__, '..') # pointing to repo root dotenv.read_dotenv(project_path('.env'))
For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import dotenv import dj_database_url from django_engvtweb import repository_path from urlparse import urlparse REPOSITORY_PATH = repository_path() dotenv.read_dotenv(os.path.join(REPOSITORY_PATH, '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! DEFAULT_SECRET_KEY = '3iy-!-d$!pc_ll$#$elg&cpr@*tfn-d5&n9ag=)%#()t$$5%5^' SECRET_KEY = os.environ.get('SECRET_KEY', DEFAULT_SECRET_KEY) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = []
first_page=first_page_url, last_page=last) @app.route('/chemical_analysis/<int:id>') def chemical_analysis(id): email = session.get('email', None) api_key = session.get('api_key', None) payload = {'email': email, 'api_key': api_key} url = env('API_HOST') + '/chemical_analysis/{0}'.format(id) response = get(url, params=payload) return render_template('chemical_analysis.html', data=response.json()) @app.route('/user/<int:id>') def user(id): api = MetpetAPI(None, None).api user = api.user.get(id).data if sample: return render_template('user.html', user=user) else: return HttpResponse("User does not Exist") if __name__ == '__main__': dotenv.read_dotenv('../app_variables.env') app.run(debug=True)
url_for, redirect, request, jsonify, flash, session ) from flask_mail import Mail, Message from utilities import paginate_model mail = Mail() metpet_ui = Flask(__name__) metpet_ui.config.from_object("config") mail.init_app(metpet_ui) dotenv.read_dotenv(os.path.dirname(__file__) + '../app_variables.env') @metpet_ui.route("/") def index(): return render_template("index.html", auth_token = session.get("auth_token",None), email = session.get("email",None), name = session.get("name",None) ) @metpet_ui.route("/search/") def search(): #get all filter options from API, use format = json and minimum page sizes to speed it up if request.args.get("resource") == "samples":
#!/usr/bin/env python import os import sys import warnings import dotenv if __name__ == "__main__": with warnings.catch_warnings(): warnings.simplefilter("ignore") dotenv.read_dotenv( os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "coursera_dashboard.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?") execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) dotenv.read_dotenv(os.path.join(BASE_DIR, ".env")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "clatoolkit_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": #dotenv.read_dotenv() if os.getenv('PRODUCTION'): dotenv.read_dotenv( os.path.join(os.path.dirname(os.path.dirname(__file__)), './production.env')) else: dotenv.read_dotenv( os.path.join(os.path.dirname(os.path.dirname(__file__)), './development.env')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "towan.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": # read env vars path = os.path.abspath('.env') dotenv.read_dotenv(dotenv=path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/python from bottle import Bottle, route, static_file, request, response from caddy.utils import env import os import ujson from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session dot_env = os.path.join(os.getcwd(), '.env') if os.path.exists(dot_env): from dotenv import read_dotenv read_dotenv() database_url = env('DATABASE_URL').replace('postgis', 'postgres') engine = create_engine(database_url) Session = scoped_session(sessionmaker(bind=engine, autoflush=True)) app = application = Bottle() @app.route('/') def index(): return static_file('index.html', root='caddy/templates') @app.route('/api/geocode') def geocode(): response.content_type = 'application/json' # Allow cross-origin GET requests. response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS' response.headers[ 'Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
""" WSGI config for portal project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os import dotenv from django.core.wsgi import get_wsgi_application dotenv.read_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bakerydemo.settings.dev") application = get_wsgi_application()
from __future__ import absolute_import import os from celery import Celery import dotenv dotenv.read_dotenv('.env') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'db.settings') from django.conf import settings # noqa RUN_DAILY = 60 * 60 * 24 app = Celery('db') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.on_after_finalize.connect def setup_periodic_tasks(sender, **kwargs): from db.base.tasks import update_all_tle sender.add_periodic_task(RUN_DAILY, update_all_tle.s(), name='update-all-tle')
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Django settings for GAE_Django17 project. import os from os.path import join, dirname import sys import dotenv dotenv.read_dotenv(join(dirname(__file__), '../.env')) BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + os.sep SHARED_SOURCE_DIRECTORIES = [ 'ISB-CGC-Common', 'ISB-CGC-API' ] # Add the shared Django application subdirectory to the Python module search path for directory_name in SHARED_SOURCE_DIRECTORIES: sys.path.append(os.path.join(BASE_DIR, directory_name)) DEBUG = bool(os.environ.get('DEBUG', False)) ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOST', 'localhost')]
#!/usr/bin/env python import os import sys import warnings import dotenv if __name__ == '__main__': # Filter out missing .env warning, it's fine if we don't have one. warnings.filterwarnings('ignore', module='dotenv') # Read .env file and inject it's values into the environment dotenv.read_dotenv(os.environ.get("DOTENV_PATH")) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pontoon.settings') from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv dotenv.read_dotenv() if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tango_with_django_project.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python import os import sys import dotenv if __name__ == "__main__": dotenv.read_dotenv(os.environ.get('ENVFILE')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "checkout.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)