def read_env(): # Liest evironment variables von .django_env/.SITE_NAME_env DJANGO_ROOT = dirname(dirname(abspath(__file__))) SITE_NAME = basename(DJANGO_ROOT) path = string.replace(DJANGO_ROOT, SITE_NAME, '') path = string.rstrip(path, '/') path = ('%s/.django_env/.%s_env' % (path, SITE_NAME)) try: with open(path) as f: content = f.read() except IOError: content = '' exit('Datei .django_env/.%s_env nicht gefunden.' % SITE_NAME) for line in content.splitlines(): m1 = match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) if m1: key, val = m1.group(1), m1.group(2) m2 = match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = match(r'\A"(.*)"\Z', val) if m3: val = sub(r'\\(.)', r'\1', m3.group(1)) environ.setdefault(key, val)
def unpackONOS( destDir='/tmp', run=quietRun ): "Unpack ONOS and return its location" global ONOS_TAR environ.setdefault( 'ONOS_TAR', join( ONOS_ROOT, tarDefaultPath ) ) ONOS_TAR = environ[ 'ONOS_TAR' ] tarPath = ONOS_TAR if not isfile( tarPath ): raise Exception( 'Missing ONOS tarball %s - run buck build onos?' % tarPath ) info( '(unpacking %s)' % destDir) success = '*** SUCCESS ***' cmds = ( 'mkdir -p "%s" && cd "%s" && tar xzf "%s" && echo "%s"' % ( destDir, destDir, tarPath, success ) ) result = run( cmds, shell=True, verbose=True ) if success not in result: raise Exception( 'Failed to unpack ONOS archive %s in %s:\n%s\n' % ( tarPath, destDir, result ) ) # We can use quietRun for this usually tarOutput = quietRun( 'tar tzf "%s" | head -1' % tarPath, shell=True) tarOutput = tarOutput.split()[ 0 ].strip() assert '/' in tarOutput onosDir = join( destDir, dirname( tarOutput ) ) # Add symlink to log file run( 'cd %s; ln -s onos*/apache* karaf;' 'ln -s karaf/data/log/karaf.log log' % destDir, shell=True ) return onosDir
def test_load_keystone(self): """test_load_keystone check that we could build a map from keystone resources using Direct_objects directive.""" environ.setdefault('KEYSTONE_ADMIN_ENDPOINT', self.OS_AUTH_URL) openstackmap = OpenStackMap(auto_load=False, objects_strategy=OpenStackMap.DIRECT_OBJECTS) openstackmap.load_keystone() self.assertIsNotNone(openstackmap)
def main(*args, **kwargs): """ Entry point for the 'bw' command line utility. The args and path parameters are used for integration tests. """ if not args: args = argv[1:] path = kwargs.get('path', getcwd()) text_args = [force_text(arg) for arg in args] parser_bw = build_parser_bw() pargs = parser_bw.parse_args(args) io.activate_as_parent(debug=pargs.debug) environ.setdefault('BWADDHOSTKEYS', "1" if pargs.add_ssh_host_keys else "0") if len(text_args) >= 1 and ( text_args[0] == "--version" or (len(text_args) >= 2 and text_args[0] == "repo" and text_args[1] == "create") or text_args[0] == "zen" or "-h" in text_args or "--help" in text_args ): # 'bw repo create' is a special case that only takes a path repo = path else: try: repo = Repository(path) except NoSuchRepository: io.stderr(_( "{x} The current working directory " "is not a BundleWrap repository.\n".format(x=red("!")) )) exit(1) return # used during texting when exit() is mocked # convert all string args into text text_pargs = {key: force_text(value) for key, value in vars(pargs).items()} try: output = pargs.func(repo, text_pargs) if output is None: output = () return_code = 0 for line in output: if isinstance(line, int): return_code = line break else: io.stdout(line) finally: io.shutdown() if return_code != 0: # not raising SystemExit every time to ease testing exit(return_code)
def test_implement_openstackmap_with_keystone_admin_endpoint(self, mock_exists, mock_os): """test_implement_openstackmap_with_keystone_admin_endpoint check that we could build an empty map from the resources providing a keystone admin endpoint environment variable.""" environ.setdefault('KEYSTONE_ADMIN_ENDPOINT', self.OS_AUTH_URL) mock_exists.return_value = False mock_os.return_value = True openstackmap = OpenStackMap(auto_load=False) self.assertTrue(mock_os.called) self.assertIsNotNone(openstackmap)
def test_load_nova(self, mock_exists, mock_os): """test_load_nova check that we could build an empty map from nova resources.""" environ.setdefault('KEYSTONE_ADMIN_ENDPOINT', self.OS_AUTH_URL) mock_exists.return_value = False mock_os.return_value = True openstackmap = OpenStackMap(auto_load=False, objects_strategy=OpenStackMap.NO_CACHE_OBJECTS) openstackmap.load_nova() self.assertTrue(mock_os.called) self.assertIsNotNone(openstackmap)
def update(): from os import environ from devops.models import Environment environ.setdefault("DJANGO_SETTINGS_MODULE", "devops.settings") with open("hosts.pp", "w") as pp: for e in Environment.list_all(): ip = e.nodes().admin.get_ip_address_by_network_name(e.admin_net) pp.write("host {{ '{}': ip => '{}' }}\n".format(e.name, ip)) local("sudo puppet apply hosts.pp")
def get_env_variable(varname, default=None): """ Get environment variable or return exception. If the default argument is provided, set it as the value and return that. """ try: return environ[varname] except KeyError: if default: environ.setdefault(varname, default) return environ[varname] else: msg = 'Set the {} environment variable.'.format(varname) raise ImproperlyConfigured(msg)
def activate(): environ.setdefault('DJANGO_SETTINGS_MODULE', 'cyder.settings') activator = cy_path('.env/bin/activate_this.py') try: execfile(activator, {'__file__': activator}) except: pass cy_addsitedir(cy_path('vendor')) # global (upstream) vendor library cy_addsitedir(cy_path('vendor-local')) # local (project) vendor library import cyder.signal_handlers # register the handlers
def upgrade(pargs): environ['DJANGO_SETTINGS_MODULE'] = 'teamvault.settings' environ.setdefault("TEAMVAULT_CONFIG_FILE", "/etc/teamvault.cfg") print("\n### Running migrations...\n") execute_from_command_line(["", "migrate", "--noinput", "-v", "3", "--traceback"]) print("\n### Gathering static files...\n") from django.conf import settings try: rmtree(settings.STATIC_ROOT) except FileNotFoundError: pass mkdir(settings.STATIC_ROOT) execute_from_command_line(["", "collectstatic", "--noinput"])
def set_arguments(self): """ Get the parameters and make the adjusts necessary """ # Setting the paths run_path = getcwd() project_path = dirname(run_path) project_name = basename(run_path) # Suspect the user will run in root of program test path_list = [run_path, project_path] paths = self.kwdict.pop("paths") if paths: path_list.extend(paths.split(",")) for item in path_list: if item not in path: path.append(item) # Django self.is_django = self.kwdict.pop("django") module = self.kwdict.pop("module") if self.is_django: from os import environ # Set enviroment to run set_environ = "%s.settings" % project_name if module is None \ else module environ.setdefault("DJANGO_SETTINGS_MODULE", set_environ) verbosity = 0 if self.kwdict.pop("quiet") else 2 if \ self.kwdict.pop("verbose") else 1 # Extensions self.extension = { "requested" : self.kwdict.pop("is_extension"), "module" : self.kwdict.pop("extension"), "ext_type" : self.kwdict.pop("ext_type"), "ext_file" : self.kwdict.pop("ext_file"), } # Unit test self.unit_test = { "failfast" : self.kwdict.pop("failfast"), "catchbreak" : self.kwdict.pop("catch"), "verbosity" : verbosity, "buffer" : False } # Additional information that was input and not parsed self.args = self.kwdict.pop("args")
def populate_db(): environ.setdefault("DJANGO_SETTINGS_MODULE", "newrelic_python_kata.settings") from employees.models import Employee, BioData, Payroll with open('names.txt') as f: es = [] bs = [] ps = [] for idx, line in enumerate(f): name, sex, salary = line.rstrip('\r\n').split(',') e = Employee(name=name, employee_id=idx) b = BioData(employee=e, age=randint(18, 40), sex=sex) p = Payroll(employee=e, salary=salary) es.append(e) bs.append(b) ps.append(p) Employee.objects.bulk_create(es) BioData.objects.bulk_create(bs) Payroll.objects.bulk_create(ps)
def test_ConfigFile(): initialJson = '{ \ "iCloud" : { \ "login" : "None", \ "password" : "None", \ "url" : "http://www.icloud.com" \ },\ "Google" : { \ "username" : "None", \ "password" : "None", \ "url" : "http://calendar.google.com" \ },\ "sample" : "forTest"\ }' environ.setdefault("garbage", "") Env(initialJson, "garbage", "garbage") assert Env().get("sample") == "forTest" assert Env().get("iCloud", "login") == "None" assert Env().get("garbage") == '' Env().envConfigFileNameOverride("envConfigFileNameOverride") Env().load()
#!/usr/bin/env python # Copyright 2013 - 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # 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. from os import environ if __name__ == "__main__": environ.setdefault("DJANGO_SETTINGS_MODULE", "devops.settings") from devops.shell import main main()
from django.core.wsgi import get_wsgi_application from os import environ as env env.setdefault('DJANGO_SETTINGS_MODULE', 'MangAdventure.settings') application = get_wsgi_application()
To change settings file: `DJANGO_ENV=production python manage.py runserver` """ from os import environ import django_stubs_ext from split_settings.tools import include, optional # Monkeypatching Django, so stubs will work for all generics, # see: https://github.com/typeddjango/django-stubs django_stubs_ext.monkeypatch() # Managing environment via `DJANGO_ENV` variable: environ.setdefault('DJANGO_ENV', 'development') _ENV = environ['DJANGO_ENV'] _base_settings = ( 'components/common.py', 'components/logging.py', 'components/csp.py', 'components/caches.py', # Select the right env: 'environments/{0}.py'.format(_ENV), # Optionally override some settings: optional('environments/local.py'), )
def run(self): environ.setdefault('DJANGO_SETTINGS_MODULE', '{}.settings'.format(self.__name)) print('webapp:', self.__name) maincmd.run()
import telebot from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup import config import messages import logging from os import environ import django environ.setdefault("DJANGO_SETTINGS_MODULE", "telegram_bot.settings") django.setup() from Question.models import Question from django.core.exceptions import ObjectDoesNotExist def bot_start(): bot = telebot.TeleBot(config.token) new_question = Question() logger = logging.getLogger("information") logger.setLevel(logging.INFO) fh = logging.FileHandler("information.log") fh.setFormatter( logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s")) logger.addHandler(fh) def get_question_from_user(message):
from src.api.query import get_cls_gpa, get_usr_sections, find_hour, get_instructor, get_instructor_cls_gpa, \ get_default_term, get_rmp_gpa from os import environ environ.setdefault("DEFAULT_TERM", str(get_default_term()[0])) environ.setdefault("DEFAULT_TERM_NAME", str(get_default_term()[1])) # purposed algo sum((1 + int(cls_num/100)*weight)*(4 - avg_gpa)*(sentiment/5)*hrs) * (total_hrs/semester hr cap) # pre-defined weight = 0.15 # cap is 9 for summer cap = 9 # wrapper def calculate_difficulty(email, term=environ.get("DEFAULT_TERM")): status, response = fetch_grades(email, term) if status == 1: return status, response class_id, subject_id, credit, crn, gpa, sentiment = response print(class_id, subject_id, credit, crn, gpa, sentiment) return 0, sum([ (1 + int(cls_num / 100) * weight) * (4 - grade) * (s / 5.0) * c for cls_num, grade, c, s in zip(class_id, gpa, credit, sentiment) ]) * (sum(credit) / cap) # this output should reflect difficulty in some degree # but probably need some normalization using data # also weight and sentiment need to be implemented&&refined
File: ceesdbwrapper.py Author: Fernando Crespo Gravalos ([email protected]) Date: 2014/06/05 """ """ This script wraps queries to data model (CEES database). This keeps the view handling requests and responses. """ import constants as c ################################################################### # set-up to run a model query from ceesdbwrapper. ################################################################### from os import path as os_path, environ from sys import path as sys_path sys_path.append(os_path.abspath(os_path.join(os_path.dirname(__file__), os_path.pardir))) environ.setdefault(c.DJANGO_SETTINGS, c.CEES_SETTINGS) #################################################################### import uuid from datetime import datetime from django.db import Error from cees.models import ShopAssistants, Tokens, Devices, Stores, SaRegistrations, CheckIns, Clients, Customers, RfidCards, ClientArrivals, Licenses from ceesloggers import getDbLogger from cees.serializers import ClientSerializer dblogger = getDbLogger() DB_ERRORS = { 0 : c.SUCC_QUERY, 1 : c.OBJECT_NOT_FOUND, 2 : c.DB_ERROR} ################# # Authorization # #################
from os import environ environ.setdefault("DJANGO_SETTINGS_MODULE", "TwitterFriends.settings") import django django.setup() import tweepy from findfriends.models import TwitterUser # function to save frienship on database def create_frienship(api, userid): user = TwitterUser.objects.get(user_id=userid) if len(user.friends.all()) == 0: friends = api.friends_ids(user_id=userid) print("Saving ", user.screen_name, "'s friends") for friend in friends: if TwitterUser.objects.filter(user_id=friend).exists(): u = TwitterUser.objects.get(user_id=friend) print(u.screen_name, " is friend of ", user.screen_name) user.friends.add(u) else: print(user.screen_name, "'s friends are already saved") auth = tweepy.OAuthHandler(environ["TWITTER_CONSUMER_KEY"], environ["TWITTER_CONSUMER_SECRET"]) auth.set_access_token(environ["TWITTER_ACCESS_TOKEN"], environ["TWITTER_ACCESS_TOKEN_SECRET"]) api = tweepy.API(auth_handler=auth, wait_on_rate_limit_notify=True,
'NAME': 'plivo', # Or path to database file if using sqlite3. 'USER': '******', # Not used with sqlite3. 'PASSWORD': '******', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '3306', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. environ.setdefault('DJANGO_DATABASE_ENGINE', 'django.db.backends.mysql') environ.setdefault('DJANGO_DATABASE_NAME', 'plivo') environ.setdefault('DJANGO_DATABASE_USER', 'root') environ.setdefault('DJANGO_DATABASE_PASSWORD', 'abc123') environ.setdefault('DJANGO_DATABASE_HOST', 'localhost') environ.setdefault('DJANGO_DATABASE_PORT', '3306') TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1
opt = variant.get('optimize') if opt is not None: CONFIGURE_ARGS += (" --enable-optimize" if opt else " --disable-optimize") opt = args.debug if opt is None and args.platform: # Override variant['debug']. opt = ('-debug' in args.platform) if opt is None: opt = variant.get('debug') if opt is not None: CONFIGURE_ARGS += (" --enable-debug" if opt else " --disable-debug") # Any jobs that wish to produce additional output can save them into the upload # directory if there is such a thing, falling back to OBJDIR. env.setdefault('MOZ_UPLOAD_DIR', OBJDIR) ensure_dir_exists(env['MOZ_UPLOAD_DIR'], clobber=False) # Some of the variants request a particular word size (eg ARM simulators). word_bits = variant.get('bits') # On Linux and Windows, we build 32- and 64-bit versions on a 64 bit # host, so the caller has to specify what is desired. if word_bits is None and args.platform: platform_arch = args.platform.split('-')[0] if platform_arch in ('win32', 'linux'): word_bits = 32 elif platform_arch in ('win64', 'linux64'): word_bits = 64 # Fall back to the word size of the host.
#!/usr/bin/env python from os import environ, path, chdir import sys import shutil # change to manage.py's folder abspath = path.abspath(__file__) dname = path.dirname(abspath) chdir(dname) if __name__ == "__main__": from bptbx import b_iotools environ.setdefault("DJANGO_SETTINGS_MODULE", "pyntrest_project.settings") import_success, failed_modules = b_iotools.import_modules_with_check( [ 'PIL', 'django.http', 'markdown2', 'bs4' ]) if not import_success: print ('Sorry, but there are some packages missing: ' + '{0}\nPlease refer to README.md to find out what ' + 'you\'ve missed or, assuming you have \'pip\' installed,\n' + 'run \'pip install -r requirements.txt\'' ).format(failed_modules) exit(1) # this needs to be done here because why want to check for missing # packages first from django.core.management import execute_from_command_line
'PORT': '', # Set to empty string for default. Not used with sqlite3. } }""" """ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } """ environ.setdefault('DJANGO_MEDIA_ROOT', join(INSTALL_DIR, 'media/')) environ.setdefault('DJANGO_MEDIA_URL', '/media/') # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us'
def main(*args, **kwargs): """ Entry point for the 'bw' command line utility. The args and path parameters are used for integration tests. """ if not args: args = argv[1:] path = kwargs.get('path', getcwd()) text_args = [force_text(arg) for arg in args] parser_bw = build_parser_bw() pargs = parser_bw.parse_args(args) if not hasattr(pargs, 'func'): parser_bw.print_help() exit(2) io.debug_mode = pargs.debug io.activate() if 'BWADDHOSTKEYS' in environ: # TODO remove in 3.0.0 environ.setdefault('BW_ADD_HOST_KEYS', environ['BWADDHOSTKEYS']) if 'BWCOLORS' in environ: # TODO remove in 3.0.0 environ.setdefault('BW_COLORS', environ['BWCOLORS']) if 'BWITEMWORKERS' in environ: # TODO remove in 3.0.0 environ.setdefault('BW_ITEM_WORKERS', environ['BWITEMWORKERS']) if 'BWNODEWORKERS' in environ: # TODO remove in 3.0.0 environ.setdefault('BW_NODE_WORKERS', environ['BWNODEWORKERS']) environ.setdefault('BW_ADD_HOST_KEYS', "1" if pargs.add_ssh_host_keys else "0") if len(text_args) >= 1 and ( text_args[0] == "--version" or (len(text_args) >= 2 and text_args[0] == "repo" and text_args[1] == "create") or text_args[0] == "zen" or "-h" in text_args or "--help" in text_args ): # 'bw repo create' is a special case that only takes a path repo = path else: try: repo = Repository(path) except MissingRepoDependency as exc: io.stderr(str(exc)) exit(1) except NoSuchRepository: io.stderr(_( "{x} The current working directory " "is not a BundleWrap repository." ).format(x=red("!"))) exit(1) # convert all string args into text text_pargs = {key: force_text(value) for key, value in vars(pargs).items()} output = pargs.func(repo, text_pargs) if output is None: output = () return_code = 0 for line in output: if isinstance(line, int): return_code = line break else: io.stdout(line) if return_code != 0: # not raising SystemExit every time to ease testing exit(return_code)
from os import environ as env import sys if not 'DJANGO_SETTINGS_MODULE' in env: from recms import settings env.setdefault('DJANGO_SETTINGS_MODULE', settings.__name__) import django django.setup() def read_forward_zone(forward_zone_conf_file): """reads forward zone conf file to a dict consist of some lists""" import re forward_zone_conf = {'forward-zone': []} d = {} lines = open(forward_zone_conf_file).read().split('\n') lines.reverse() for line in lines: if re.search(r'forward-first', line): d['forward-first']='yes' continue match_addr = re.match(r'\s+forward-addr:\s+(.+)', line) if match_addr: if 'forward-addr' in d: d['forward-addr'].append(match_addr.group(1)) else:
def setUp(self): """define environment""" self.OS_AUTH_URL = 'http://cloud.lab.fi-ware.org:4731/v2.0' self.OS_USERNAME = '******' self.OS_PASSWORD = '******' self.OS_TENANT_NAME = 'user cloud' self.OS_TENANT_ID = '00000000000000000000000000000001' self.OS_REGION_NAME = 'Spain2' self.OS_TRUST_ID = '' environ.setdefault('OS_AUTH_URL', self.OS_AUTH_URL) environ.setdefault('OS_USERNAME', self.OS_USERNAME) environ.setdefault('OS_PASSWORD', self.OS_PASSWORD) environ.setdefault('OS_TENANT_NAME', self.OS_TENANT_NAME) environ.setdefault('OS_TENANT_ID', self.OS_TENANT_ID) environ.setdefault('OS_REGION_NAME', self.OS_REGION_NAME) environ.setdefault('OS_TRUST_ID', self.OS_TRUST_ID)
pdb.set_trace() with open(filepath, 'r', encoding='utf-8') as file: data = json.load(file) serializer = DogSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() else: print(serializer.errors) print('load_data done.') if __name__ == '__main__': sys.path.append(PROJ_DIR) environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings") django.setup() # Assuming your serializer is named DogSerializer # has to be imported after django.setup() try: from pugorugh.serializers import DogSerializer except ImportError: raise ImportError( 'serializers.py must contain a properly ' 'implemented DogSerializer class for this import to work.') load_data()
# -*- coding: utf-8 -*- """ Created on Mon May 8 10:59:08 2017 @author: rstreet """ from os import getcwd, path, remove, environ from sys import path as systempath, argv cwd = getcwd() systempath.append(path.join(cwd, '..')) from local_conf import get_conf app_config = get_conf('mulens_tom') systempath.append(app_config) environ.setdefault('DJANGO_SETTINGS_MODULE', 'mulens_tom.settings') from django.core import management from django.conf import settings from django.utils import timezone from django import setup from datetime import datetime, timedelta import pytz setup() import ingest, observing_strategy from tom.models import Target import lco_interface, observing_strategy, log_utilities, ingest def get_test_obs(simulate=False): """Function to return an example of an ObsRequest with default parameters for testing purposes"""
from fabric.api import env from fabric.api import get from fabric.api import local from fabric.api import prefix from fabric.api import prompt from fabric.api import put from fabric.api import run from fabric.api import task from fabric.colors import green from fabric.colors import red from fabric.context_managers import settings # add django settings module to the import search path sys.path.append(dirname(dirname(__file__))) environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") @task def get_db_data(root_dir=None, setting=''): """ Returns the name of the default database """ if not root_dir: root_dir = env.server_root_dir with cd(root_dir): with prefix('. .env/bin/activate'): return run('python -Wi manage.py printdatabasedata {}'.format( setting)) @task def migrate():
from os import environ, path, unlink # cleanup build/dist files for fn in ('_version.py', '_version_build.py'): fn = path.join('rosshm', fn) if path.isfile(fn): unlink(fn) # set testing os environ _osenv = { 'ROSSHM_CONFIG': '', 'ROSSHM_HOME': path.join(path.sep, 'opt', 'rosshm'), } for k, v in _osenv.items(): environ.setdefault(k, v) environ[k] = v # export fixtures __all__ = [ 'testing_cmd', 'testing_config', 'testing_db', 'testing_log', 'testing_wapp', 'testing_wapp_plugin', ] from testing.cmd_ctx import cmd_ctx
#!/usr/bin/env python # -*- coding: utf-8 -*- # # harlib # Copyright (c) 2014-2017, Andrew Robbins, All rights reserved. # # This library ("it") is free software; it is distributed in the hope that it # will be useful, but WITHOUT ANY WARRANTY; you can redistribute it and/or # modify it under the terms of LGPLv3 <https://www.gnu.org/licenses/lgpl.html>. from __future__ import absolute_import from django.core.wsgi import get_wsgi_application from os import environ ''' harlib - HTTP Archive (HAR) format library ''' ''' WSGI config for harlib_viewer.server 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/ ''' environ.setdefault('DJANGO_SETTINGS_MODULE', 'harlib_viewer.server.settings') application = get_wsgi_application()
opt = args.debug if opt is None and args.platform: # Override variant['debug']. opt = ('-debug' in args.platform) if opt is None: opt = variant.get('debug') if opt is not None: CONFIGURE_ARGS += (" --enable-debug" if opt else " --disable-debug") opt = args.jemalloc if opt is not None: CONFIGURE_ARGS += (" --enable-jemalloc" if opt else " --disable-jemalloc") # Any jobs that wish to produce additional output can save them into the upload # directory if there is such a thing, falling back to OBJDIR. env.setdefault('MOZ_UPLOAD_DIR', OBJDIR) ensure_dir_exists(env['MOZ_UPLOAD_DIR'], clobber=False) # Some of the variants request a particular word size (eg ARM simulators). word_bits = variant.get('bits') # On Linux and Windows, we build 32- and 64-bit versions on a 64 bit # host, so the caller has to specify what is desired. if word_bits is None and args.platform: platform_arch = args.platform.split('-')[0] if platform_arch in ('win32', 'linux'): word_bits = 32 elif platform_arch in ('win64', 'linux64'): word_bits = 64 # Fall back to the word size of the host.
#!/usr/bin/env python from os import environ import sys from os.path import dirname, join if __name__ == "__main__": environ.setdefault("DJANGO_SETTINGS_MODULE", "qprob.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: 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?") raise execute_from_command_line(sys.argv)
# serve to show the default. from collections import OrderedDict from datetime import datetime import os from os import environ from subprocess import ( CalledProcessError, check_output, ) import sys from pytz import UTC # Configure MAAS's settings. environ.setdefault("DJANGO_SETTINGS_MODULE", "maasserver.djangosettings.settings") # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # Include '.' in the path so that our custom extension, 'versions', can # be found. sys.path.insert(0, os.path.abspath('.')) # -- Multiple documentation options. # Add a widget to switch between different versions of the documentation to # each generated page. add_version_switcher = False
from os import environ environ.setdefault("NAVYCUT_SETTINGS_MODULE", "project_name___boiler_var.settings") # Asynchronus server gateway interface # use uvicorn asgi server to run this app from navycut.utils.server import create_asgi_app application = create_asgi_app()
from behave import * from hamcrest import assert_that, equal_to, is_not from sys import path as py_path py_path.append('/Users/admin/SERVER3/aprinto') from os import environ as os_environ os_environ.setdefault("DJANGO_SETTINGS_MODULE", "aprinto.settings") from uuid import uuid4 as get_guid from urllib2 import urlopen,Request import requests from api.serializers import Initial_PDF_serializer import pandas as pd from sqlalchemy import create_engine test_url = '192.168.3.52' BASE_URL = 'http://'+test_url+':8088' engine_url = 'postgresql://*****:*****@'+test_url+':8800/aprinto' engine = create_engine(engine_url,encoding='utf-8',echo=False) @given('data for posting to Aporo') def step_impl(context): headers = {'Content-type' : 'application/json'} context.data = {'json':[{ 'pdf_id' : str(get_guid()), 'printer_id' : 'printer_id1', 'machine_id' : 'vendor1', 'application_name' : 'application_name1', 'doc_name' : 'test_unit_1' }], 'headers' : headers}
import logging from os import environ from os.path import abspath, dirname, isfile import sys import django current_path = dirname(abspath(__file__)) fleio_path = dirname(dirname(dirname(current_path))) sys.path.append(fleio_path) environ.setdefault("DJANGO_SETTINGS_MODULE", "fleio.settings") django.setup() LOG = logging.getLogger('incoming_mail') from plugins.tickets.common.email_processor import EmailProcessor # noqa from plugins.tickets.common.tickets_utils import TicketUtils # noqa def run(): mail_contents = None if len(sys.argv) > 1: input_file = sys.argv[1] if isfile(input_file): mail_contents = open(sys.argv[1]).read() else: mail_contents = sys.stdin.read() if mail_contents: received_message = EmailProcessor.parse_email_message(
compiler = variant['compiler'] elif platform.system() == 'Darwin': compiler = 'clang' elif platform.system() == 'Windows': compiler = 'cl' else: compiler = 'gcc' info("using compiler '{}'".format(compiler)) cxx = {'clang': 'clang++', 'gcc': 'g++', 'cl': 'cl'}.get(compiler) compiler_dir = env.get('GCCDIR', os.path.join(DIR.fetches, compiler)) info("looking for compiler under {}/".format(compiler_dir)) if os.path.exists(os.path.join(compiler_dir, 'bin', compiler)): env.setdefault('CC', os.path.join(compiler_dir, 'bin', compiler)) env.setdefault('CXX', os.path.join(compiler_dir, 'bin', cxx)) if compiler == 'clang': platlib = 'lib' else: platlib = 'lib64' if word_bits == 64 else 'lib' env.setdefault('LD_LIBRARY_PATH', os.path.join(compiler_dir, platlib)) else: env.setdefault('CC', compiler) env.setdefault('CXX', cxx) bindir = os.path.join(OBJDIR, 'dist', 'bin') env['LD_LIBRARY_PATH'] = ':'.join( p for p in (bindir, env.get('LD_LIBRARY_PATH')) if p) for v in ('CC', 'CXX', 'LD_LIBRARY_PATH'):
from __future__ import (absolute_import, unicode_literals) from datetime import datetime from os import environ from celery import Celery from django.utils.timezone import localtime environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') class MyCelery(Celery): def now(self) -> datetime: return localtime() celery_app = MyCelery('core') celery_app.config_from_object(obj='django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks()
# serve to show the default. import sys import os import shlex from os import path, environ sys.path.insert(0, path.dirname(path.dirname(path.abspath(__file__)))) # print('\n'.join([k for k in sys.path])) sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('../../..')) sys.path.insert(0, os.path.abspath('../../../..')) sys.path.insert(0, os.path.abspath('../')) environ.setdefault("DJANGO_SETTINGS_MODULE", "siteconfig.settings") import django from django.utils import timezone django.setup() # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0'
""" Sphinx documentation generator configuration. More information on the configuration options is available at: http://www.sphinx-doc.org/en/master/usage/configuration.html """ from os import environ from pkg_resources import get_distribution import django import sphinx_rtd_theme environ.setdefault('DJANGO_SETTINGS_MODULE', 'axes.tests.settings') django.setup() # -- Extra custom configuration ------------------------------------------ title = 'django-axes documentation' description = 'Keep track of failed login attempts in Django-powered sites.', # -- General configuration ------------------------------------------------ # Add any Sphinx extension module names here, as strings. # They can be extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = [ '_templates',
def configure_django(settings): import django environ.setdefault("DJANGO_SETTINGS_MODULE", settings['DJANGO_SETTINGS']) django.setup()
from os import environ environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoSandBox.settings') import django django.setup() from ..populations.PopulatePersonBase import PopulatePersonBase from ..models import Person class PopulatePersonByGetOrCreate(PopulatePersonBase): def save_person(self, name, height, date_of_birth, sex): Person.objects.get_or_create(name=name, sex=sex, height=height, date_of_birth=date_of_birth) if __name__ == '__main__': a_populator = PopulatePersonByGetOrCreate() a_populator.populate() a_populator.display_people()
def setUp(self): """define environment""" self.OS_AUTH_URL = environ.get('OS_AUTH_URL') if self.OS_AUTH_URL is None: self.OS_AUTH_URL = 'http://cloud.lab.fi-ware.org:4731/v2.0' environ.setdefault('OS_AUTH_URL', self.OS_AUTH_URL) self.OS_USERNAME = environ.get('OS_USERNAME') if self.OS_USERNAME is None: self.OS_USERNAME = '******' environ.setdefault('OS_USERNAME', self.OS_USERNAME) self.OS_PASSWORD = environ.get('OS_PASSWORD') if self.OS_PASSWORD is None: self.OS_PASSWORD = '******' environ.setdefault('OS_PASSWORD', self.OS_PASSWORD) self.OS_TENANT_NAME = environ.get('OS_TENANT_NAME') if self.OS_TENANT_NAME is None: self.OS_TENANT_NAME = 'tenant_name' environ.setdefault('OS_TENANT_NAME', self.OS_TENANT_NAME) self.OS_TENANT_ID = environ.get('OS_TENANT_ID') if self.OS_TENANT_ID is None: self.OS_TENANT_ID = 'tenant_id' environ.setdefault('OS_TENANT_ID', self.OS_TENANT_ID) self.OS_REGION_NAME = environ.get('OS_REGION_NAME') if self.OS_REGION_NAME is None: self.OS_REGION_NAME = 'Spain2' environ.setdefault('OS_REGION_NAME', self.OS_REGION_NAME) self.OS_TRUST_ID = environ.get('OS_TRUST_ID') if self.OS_TRUST_ID is None: self.OS_TRUST_ID = '' environ.setdefault('OS_TRUST_ID', self.OS_TRUST_ID)
def jenkins_autoset(): if 'JENKINS_URL' not in environ: return environ.setdefault('TARGET_URL', environ.get('BUILD_URL'))
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.8/howto/deployment/wsgi/ Use this file wsgi_sample.py to create a new file wsgi.py in the same directory. And replace the 2 strings below with their actual paths: <path_to_virtual_python_installation> <path_to_hsnmailenbeheer> """ from os import environ from sys import path, version # setup the virtual environment activate_this = "<path_to_virtual_python_installation>/python2710/bin/activate_this.py" execfile( activate_this, dict( __file__ = activate_this ) ) print( version ) # additions to used python; prepend to path path.insert( 0, "<path_to_hsnmailenbeheer>/hsnmailenbeheer/server" ) # project parent dir path.insert( 0, "<path_to_hsnmailenbeheer>/hsnmailenbeheer/server/hsnmailenbeheer" ) # project root dir, containing settings.py environ.setdefault( "DJANGO_SETTINGS_MODULE", "hsnmailenbeheer.settings" ) from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # [eof]
#!/usr/bin/env python from os import environ, listdir from os.path import join, dirname, abspath, exists import sys if __name__ == "__main__": # Try to discover project name and set the default settings module # based on it. If discovery fails, DJANGO_SETTINGS_MODULE environment # variable must be set. root = dirname(abspath(__file__)) sys.path.append(root) sys.path.append(join(root, '..')) settings_module = None for name in listdir(root): full_name = join(root, name) if exists(join(full_name, 'settings', '__init__.py')): settings_module = name + '.settings' break if settings_module is not None: environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
#!/usr/bin/env python from os import environ as env import sys if __name__ == "__main__": env.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev") from django.core.management import execute_from_command_line from django.conf import settings if settings.DEBUG and \ (env.get('RUN_MAIN') or env.get('WERKZEUG_RUN_MAIN')): import ptvsd ptvsd.enable_attach(address=('0.0.0.0', 5678)) print("Attached remote debugger") execute_from_command_line(sys.argv)
#!/usr/bin/env python3 # coding: utf-8 from os import ( environ, path, ) from sys import ( path as py_path, stderr, ) ROOT = path.dirname(__file__) environ.setdefault( 'BERNARD_SETTINGS_FILE', path.join(ROOT, 'src/rocket_launcher/settings.py'), ) if __name__ == '__main__': try: py_path.append(path.join(ROOT, 'src')) from bernard.misc.main import main main() except ImportError: print( 'Could not import BERNARD. Is your environment correctly ' 'configured?', file=stderr, ) exit(1)
""" Helpful Resources: 1. https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ from django.core.wsgi import get_wsgi_application from os import environ # Register our web application with any WSGI-compliant web server environ.setdefault('DJANGO_SETTINGS_MODULE', 'programmingpals.settings') application = get_wsgi_application()
def sd(var, val): "Set default value for environment variable" env[var] = environ.setdefault(var, val) return env[var]
from configparser import SafeConfigParser # import djcelery # # Project Configuration # ---------------------------------------------------------------------------- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APPS_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir, 'ingxoxo')) PROJ_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) LOG_DIR = os.path.abspath(os.path.join(PROJ_DIR, 'log')) # # Config File # ---------------------------------------------------------------------------- environ.setdefault('INGXOXO_CONFIG', join(PROJ_DIR, "config.cfg")) config = SafeConfigParser() config.read(environ['INGXOXO_CONFIG']) # # Allow Hosts Configuration # ---------------------------------------------------------------------------- ALLOWED_HOSTS = ['*'] # # Manager Configuration # ---------------------------------------------------------------------------- ADMINS = ( ('Djordje Ilic', '*****@*****.**'), ) MANAGERS = ADMINS
#!/usr/bin/env python from __future__ import absolute_import from django.core.management import execute_from_command_line from os import environ from sys import argv if len(argv) > 1 and argv[1] == 'test': environ['ENV'] = 'test' if __name__ == '__main__': environ.setdefault('DJANGO_SETTINGS_MODULE', 'www.settings') execute_from_command_line(argv)
#!/usr/bin/env python # -*- coding: utf-8 -*- from sys import platform if platform == "win32": from os import environ environ.setdefault("FORKED_BY_MULTIPROCESSING", "1") __doc__ = """https://docs.celeryproject.org/en/latest/ https://zhuanlan.zhihu.com/p/22304455 issues: https://github.com/celery/celery/issues/4081 """