def enable_django(project_path,setting_module="settings" ): sys.path.insert(0, os.path.dirname( project_path) ) sys.path.insert(0, project_path ) os.environ['DJANGO_SETTINGS_MODULE'] = "%s.%s" % (project_path.split('/')[-1:][0],setting_module ) from app import settings from django.core.management import setup_environ setup_environ(settings)
def setup_environ(self): from django.core.management import setup_environ try: import settings setup_environ(settings) except ImportError, e: return self.no_settings(self.settings_modname, import_error=True)
def before_all(context): from django.core.management import setup_environ from config import settings from django.test import Client setup_environ(settings) context.client = Client()
def start (args): # if a specific conf has been provided (which it # will be), if we're inside the django reloaded if "RAPIDSMS_INI" in os.environ: ini = os.environ["RAPIDSMS_INI"] # use a local ini (for development) # if one exists, to avoid everyone # having their own rapidsms.ini elif os.path.isfile("local.ini"): ini = "local.ini" # otherwise, fall back else: ini = "rapidsms.ini" # add the ini path to the environment, so we can # access it globally, including any subprocesses # spawned by django os.environ["RAPIDSMS_INI"] = ini os.environ["DJANGO_SETTINGS_MODULE"] = "rapidsms.webui.settings" # read the config, which is shared # between the back and frontend conf = Config(ini) # if we found a config ini, try to configure Django if conf.sources: # This builds the django config from rapidsms.config, in a # round-about way. # Can't do it until env[RAPIDSMS_INI] is defined from rapidsms.webui import settings import_local_settings(settings, ini) # whatever we're doing, we'll need to call # django's setup_environ, to configure the ORM from django.core.management import setup_environ, execute_manager setup_environ(settings) else: settings = None # if one or more arguments were passed, we're # starting up django -- copied from manage.py if len(args) < 2: print "Commands: route, startproject <name>, startapp <name>" sys.exit(1) if hasattr(Manager, args[1]): handler = getattr(Manager(), args[1]) handler(conf, *args[2:]) elif settings: # none of the commands were recognized, # so hand off to Django from django.core.management import ManagementUtility # The following is equivalent to django's "execute_manager(settings)" # only without overriding RapidSMS webui settings utility = ManagementUtility() utility.execute()
def install_products_code(*products): """ Download and compile the external code for the products. Inputs: *products - A list of strings with the names of the packages to get. If None, all the packages will be processed. """ from django.core.exceptions import ObjectDoesNotExist from django.core.management import setup_environ import sys sys.path.append("webg2system") import settings as s setup_environ(s) import systemsettings.models as sm products_to_get = [] if len(products) == 0: products_to_get = sm.ExternalCode.objects.all() else: for p in products: try: products_to_get.append(sm.ExternalCode.objects.get(name=p)) except ObjectDoesNotExist: print("Couldn't find product %s" % p) for ec in products_to_get: _get_product_package_code(ec) _create_compilation_auxiliary_files(ec) _compile_product_package(ec)
def _detect_loader(): # pragma: no cover from django.conf import settings if settings.configured: return DjangoLoader try: # A settings module may be defined, but Django didn't attempt to # load it yet. As an alternative to calling the private _setup(), # we could also check whether DJANGO_SETTINGS_MODULE is set. settings._setup() except ImportError: if not callable(getattr(os, "fork", None)): # Platform doesn't support fork() # XXX On systems without fork, multiprocessing seems to be # launching the processes in some other way which does # not copy the memory of the parent process. This means # any configured env might be lost. This is a hack to make # it work on Windows. # A better way might be to use os.environ to set the currently # used configuration method so to propogate it to the "child" # processes. But this has to be experimented with. # [asksol/heyman] from django.core.management import setup_environ try: settings_mod = os.environ.get("DJANGO_SETTINGS_MODULE", "settings") project_settings = __import__(settings_mod, {}, {}, ['']) setup_environ(project_settings) return DjangoLoader except ImportError: pass else: return DjangoLoader return DefaultLoader
def setup_django_env(path): import imp from django.core.management import setup_environ f, filename, desc = imp.find_module('settings', [path]) project = imp.load_module('settings', f, filename, desc) print "Setting django environment: ", project setup_environ(project)
def setup_mytardis_paths(mytardis_base_path): sys.path.append(mytardis_base_path) for egg in os.listdir(os.path.join(mytardis_base_path, "eggs")): sys.path.append(os.path.join(mytardis_base_path, "eggs", egg)) from django.core.management import setup_environ from tardis import settings setup_environ(settings)
def scada_main_cli(options, django_settings_module): ''' Punto de entrada al scada en modo consola (CLI) @param options: Configuracion del motor @param django_settings_module: Modulo django ''' setup_environ(django_settings_module) from dscada.apps.scada.models import Concentrador #, UC, Puerto # xh_interfase = XMLRPCThread(options.xh_iface, options.xh_port) # xh_interfase.start()| hilos_concetradores = [] for con in Concentrador.objects.all(): # Los hilos arrancan en el constructor hilos_concetradores.append(ConcentradorThread(con)) while True: try: time.sleep(0.1) # Si no hay mas hilos, terminamos la aplicacion if ConcentradorThread.queue.empty(): break except KeyboardInterrupt, e: request_shutdown()
def test_syncdb(self): """ Create the test database and sync the schema """ setup_environ(Bcfg2.settings) import django.core.management django.core.management.call_command("syncdb", interactive=False, verbosity=0) self.assertTrue(os.path.exists(Bcfg2.settings.DATABASE_NAME))
def bootstrap(path): """ Call this function as the first thing in your cron, or console script; it will bootstrap Django, and allow you to access all of the Django modules from the console, without using 'python manage.py shell' Examples: # A script within your django project. from django_bootstrap import bootstrap bootstrap(__file__) --- or --- # A cron script located outside of your django project from django_bootstrap import bootstrap bootstrap("/path/to/your/project/root/") """ path = find_settings_path(path) parent_path = os.path.abspath(os.path.join(path, '..')) # Include path to settings.py directory os.sys.path.append(path) # Include path to django project directory os.sys.path.append(parent_path) from django.core import management try: from adm2 import settings # Assumed to be in the os path except ImportError: sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) management.setup_environ(settings)
def runNginxServer(self): from django.core.servers.fastcgi import runfastcgi from django.core.management import setup_environ from mysite import settings os.chdir("%s/nginx"%self.p) fname="conf/site.conf" f=file(fname, "w+") confStr=nginxConf%{"PORT":self.port, "FCGI_PORT":self.fcgiPort} f.write(confStr) f.close() if os.name=='posix': os.system("""./nginx""") else: #'nt', windows os.system("""nginx.exe -s stop""") os.system("""start nginx.exe""") os.chdir(self.p) #print "startup fcgi module ..." if os.name=='posix': setup_environ(settings) runfastcgi(method="threaded", maxrequests=500, protocol="fcgi", host="localhost", port=self.fcgiPort) else: #runfcgi method=threaded host=localhost port=10026 from django.core.management import execute_manager sys.argv.append("runfcgi") sys.argv.append("method=thread") sys.argv.append("host=localhost") sys.argv.append("port=%s"%self.fcgiPort) execute_manager(settings)
def __init__(self, settings_mod, queue=None, path=None, filter=True, bufferDelay=1, retryDelay=5, blackList=None): """ @filter: when True (default), removes all "", None, False, [] or {} entries. @bufferDelay: amount of time events are queued before sending, to reduce the number of push requests rate. This is the delay between the end of a request to initializing a new one. @retryDelay: amount of time between retries when no items were pushed on last serverPushCb call. @blackList: events that shouldn't be sent. """ setup_environ(settings_mod) from django.core.cache import cache StatusReceiverMultiService.__init__(self) # Parameters. self.cache = cache self.filter = filter self.bufferDelay = bufferDelay self.retryDelay = retryDelay self.blackList = blackList # Other defaults. # IDelayedCall object that represents the next queued push. self.task = None self.stopped = False self.lastIndex = -1 self.state = {} self.state['started'] = str(datetime.datetime.utcnow()) self.state['next_id'] = 1 self.state['last_id_pushed'] = 0
def main(settings_file, logfile=None): try: mod = __import__(settings_file) components = settings_file.split('.') for comp in components[1:]: mod = getattr(mod, comp) except ImportError: import sys # XXX: Hack for python < 2.6 _, e, _ = sys.exc_info() sys.stderr.write("Error loading the settings module '%s': %s" % (settings_file, e)) sys.exit(1) # Setup settings management.setup_environ(mod) from django.conf import settings options = getattr(settings, 'FCGI_OPTIONS', {}) if logfile: options['outlog'] = logfile options['errlog'] = logfile from django.core.servers.fastcgi import runfastcgi # Run FASTCGI handler runfastcgi(**options)
def prepare_environment(): """Makes it easy to create standalone scripts that reference Django modules""" sys.path.append(xoma_gallery.__path__[0]) # set up the environment using the settings module from django.core.management import setup_environ import settings setup_environ(settings)
def setup(root=None, settings_module_name=None): """ Simple setup snippet that makes easy to create fast sandbox to try new things. :param root: the root of your project :param settings_module_name: name of settings module eg: "project.setting" Usage: >>> import manage >>> manage.setup() >>> # from now on paths are setup, and django is configured >>> # you can use it in separate "sandbox" script just to check >>> # things really quick """ from django.utils.importlib import import_module from django.core.management import setup_environ root = os.path.dirname(os.path.abspath(root or __file__)) path = lambda *a: os.path.join(root, *a) settings_module_name = settings_module_name or 'settings' # 1) try to import module settings = import_module(settings_module_name) # 2) setup pythonpath if os.path.exists(path('lib')): site.addsitedir(path('lib')) # 2) cofigure django setup_environ(settings) return settings
def worker(w_inqueue): """ multiprocessing worker that grabs tasks (requests) from queue and gives them to the xmppface layer. """ # loading happens after the start. from multiprocessing import current_process curproc = "Process %r" % current_process() print "%s: starting." % curproc from django.core.management import setup_environ import settings setup_environ(settings) from . import xmppface try: while True: print "%s: waiting for stuff to process." % curproc data = w_inqueue.get() if data == "QUIT": # ? Which logging to use? print "%s: received QUIT." % curproc return xmppface.processcmd(data) except KeyboardInterrupt: print "%s: Interrupted; finishing." % curproc return
def setup_project(name): """ Helper for build_app_list to prepare the process for settings of a given Pinax project. """ settings_mod = import_module("%s.settings" % name) setup_environ(settings_mod)
def prepare_imports(): """Makes it easy to create standalone scripts that reference Django modules""" sys.path.append('/opt/local/var/apps/current/django/xoma_gallery') # set up the environment using the settings module from django.core.management import setup_environ import settings setup_environ(settings)
def include_enabled_extensions(settings): """ This adds enabled extensions to the INSTALLED_APPS cache so that operations like syncdb and evolve will take extensions into consideration. """ # Some of our checks require access to django.conf.settings, so # tell Django about our settings. # # This must go before the imports. setup_environ(settings) from django.db.models.loading import load_app from django.db import DatabaseError from reviewboard.extensions.base import get_extension_manager try: manager = get_extension_manager() manager.load() except DatabaseError: # This database is from a time before extensions, so don't attempt to # load any extensions yet. return for extension in manager.get_enabled_extensions(): load_app(extension.info.app_name)
def setup_environ(): # lib sys.path.insert(0, os.path.join(ROOT_PATH, 'lib')) # SDK (this will be simpler if SDK is in the codebase) sdk_path = None for path in os.environ.get('PATH').split(os.pathsep): if 'dev_appserver.py' in os.listdir(path): test_path = os.path.join(path, 'dev_appserver.py') sdk_path = os.path.dirname( os.readlink(test_path) if \ os.path.islink(test_path) else test_path) break if not sdk_path: sys.stderr.write("Fatal: Can't find sdk_path") sys.exit(1) sys.path.insert(0, sdk_path) # Use dev_appserver to set up the python path from dev_appserver import fix_sys_path fix_sys_path() from google.appengine.tools import dev_appserver as tools_dev_appserver from google.appengine import dist # Parse `app.yaml` appinfo, url_matcher, from_cache = tools_dev_appserver.LoadAppConfig( ROOT_PATH, {}, default_partition='dev') app_id = appinfo.application # Useful for later scripts os.environ['APPLICATION_ID'] = app_id os.environ['APPLICATION_VERSION'] = appinfo.version # Third party libraries on the path if appinfo.libraries: for library in appinfo.libraries: try: dist.use_library(library.name, library.version) except ValueError, e: if library.name == 'django' and library.version == '1.4': # Work around an SDK issue print 'Warning: django 1.4 not recognised by dist, fixing python path' sys.path.insert(0, os.path.join(sdk_path, 'lib', 'django-1.4')) else: print 'Warning: Unsupported library:\n%s\n' % e # Extra setup for django if library.name == 'django': try: import settings from django.core.management import setup_environ setup_environ(settings, original_settings_path='settings') except ImportError: sys.stderr.write("\nWarning! Could not import django settings")
def prepare_environment(): # we'll need this script's directory for searching purposess curdir, curfile = os.path.split(os.path.abspath(__file__)) # move up one directory at a time from this script's # path, searching for settings.py settings_module = None while not settings_module: try: sys.path.append(curdir) settings_module = __import__('settings', {}, {}, ['']) sys.path.pop() break except ImportError: settings_module = None # have we reached the top-level directory? if is_top_level(curdir): raise Exception("settings.py was not found in the script's directory or any of its parent directories.") # move up a directory curdir = os.path.normpath(os.path.join(curdir, '..')) # set up the environment using the settings module from django.core.management import setup_environ setup_environ(settings_module)
def setup(root=None, settings_module_name=None): """ Simple setup snippet that makes easy to create fast sandbox to try new things. :param root: the root of your project :param settings_module_name: name of settings module eg: "project.setting" Usage: >>> from lib import env >>> env.setup() >>> # from now on paths are setup, and django is configured >>> # you can use it in separate "sandbox" script just to check >>> # things really quick """ from django.utils.importlib import import_module from django.core.management import setup_environ settings_module_name = settings_module_name or 'settings' # 1) try to import module settings = import_module(settings_module_name) # 2) update sys.path if root is not None: sys.path[0] = os.path.join(root, 'lib') # 3) cofigure django setup_environ(settings)
def main(settings): if dirname(settings.__file__) == os.getcwd(): sys.stderr.write("manage.py should not be run from within the " "'reviewboard' Python package directory.\n") sys.stderr.write("Make sure to run this from the top of the " "Review Board source tree.\n") sys.exit(1) if len(sys.argv) > 1 and \ (sys.argv[1] == 'runserver' or sys.argv[1] == 'test'): if settings.DEBUG: # If DJANGO_SETTINGS_MODULE is in our environment, we're in # execute_manager's sub-process. It doesn't make sense to do this # check twice, so just return. if 'DJANGO_SETTINGS_MODULE' not in os.environ: sys.stderr.write('Running dependency checks (set DEBUG=False ' 'to turn this off)...\n') check_dependencies(settings) else: # Some of our checks require access to django.conf.settings, so # tell Django about our settings. # # This must go before the imports. setup_environ(settings) # Initialize Review Board, so we're in a state ready to load # extensions and run management commands. from reviewboard import initialize initialize() include_enabled_extensions(settings) execute_manager(settings)
def tag_unknown_locations_and_publish(): import sys, os sys.path.append(os.path.realpath(os.sep.join([os.path.dirname(__file__), os.pardir, os.pardir]))) from django.core.management import setup_environ import settings setup_environ(settings) from django.db.models.loading import cache as model_cache model_cache._populate() from django.core.cache import cache from entity_items.models.location import Location classified = Location.objects.filter(classification__isnull=False) decision_tree = LocationClassifier.train(classified) log.info("Decision tree: %s" % decision_tree) if decision_tree: cache.set(LocationClassifier.cache_key, decision_tree.copy()) # Have to copy it so it's a normal dict again unclassified = Location.objects.filter(classification__isnull=True) for loc in unclassified: classification = LocationClassifier.classify(loc) if classification: log.info("Saving location") loc.classification = classification loc.save()
def init(self, parser, opts, args): from django.conf import ENVIRONMENT_VARIABLE from django.core.management import setup_environ self.project_path = os.getcwd() if args: settings_path = os.path.abspath(os.path.normpath(args[0])) if not os.path.exists(settings_path): self.no_settings(settings_path) else: self.project_path = os.path.dirname(settings_path) else: try: self.settings_modname = os.environ[ENVIRONMENT_VARIABLE] try: import settings setup_environ(settings) except ImportError: self.no_settings(settings_path, import_error=True) return except KeyError: settings_path = os.path.join(self.project_path, "settings.py") if not os.path.exists(settings_path): self.no_settings(settings_path) project_name = os.path.split(self.project_path)[-1] settings_name, ext = os.path.splitext(os.path.basename(settings_path)) self.settings_modname = "%s.%s" % (project_name, settings_name) self.cfg.set("default_proc_name", self.settings_modname) sys.path.insert(0, self.project_path) sys.path.append(os.path.join(self.project_path, os.pardir))
def _make_django_maintenance_announcement( settings, seed_instance, seed_master_password, ): """ Post-fork call to connect to the database and set an announcement. """ # Connect to the database and add the announcement settings.DATABASES['default']['ENGINE'] = 'django.db.backends.mysql' host, port = seed_instance.endpoint settings.DATABASES['default']['HOST'] = host settings.DATABASES['default']['PORT'] = port settings.DATABASES['default']['USER'] = seed_instance.master_username settings.DATABASES['default']['PASSWORD'] = seed_master_password settings.DATABASES['default']['NAME'] = 'policystat' setup_environ(settings) # pylint: disable=W0404 from announcements.models import Announcement from django.contrib.auth.models import User # pylint: enable=W0404 if Announcement.objects.count() == 0: admin = User.objects.filter(is_superuser=True).order_by('pk')[0] Announcement.objects.create( title="Maintenance In Progress", content=( "Policy approvals, comments, edits and other changes will " "NOT persist until maintenance is complete" ), creator=admin, site_wide=True) count = Announcement.objects.all().count() if count != 1: exit(1) exit(0)
def setup_environment(): from django.core.management import setup_environ dirs = os.getcwd().split('/') settings_path = '/'.join(dirs[:len(dirs)-1]) sys.path.append(settings_path) import settings setup_environ(settings)
def start (args): # if a specific conf has been provided (which it # will be), if we're inside the django reloaded if "RAPIDSMS_INI" in os.environ: ini = os.environ["RAPIDSMS_INI"] # use a local ini (for development) # if one exists, to avoid everyone # having their own rapidsms.ini elif os.path.isfile("local.ini"): ini = "local.ini" # otherwise, fall back else: ini = "rapidsms.ini" # add the ini path to the environment, so we can # access it globally, including any subprocesses # spawned by django os.environ["RAPIDSMS_INI"] = ini # read the config, which is shared # between the back and frontend conf = Config(ini) # import the webui settings, which builds the django # config from rapidsms.config, in a round-about way. # can't do it until env[RAPIDSMS_INI] is defined from rapidsms.webui import settings # whatever we're doing, we'll need to call # django's setup_environ, to configure the ORM os.environ["DJANGO_SETTINGS_MODULE"] = "rapidsms.webui.settings" from django.core.management import setup_environ, execute_manager setup_environ(settings) # if one or more arguments were passed, we're # starting up django -- copied from manage.py if len(args) > 1: execute_manager(settings) # no arguments passed, so perform # the default action: START RAPIDSMS else: router = Router() router.set_logger(conf["log"]["level"], conf["log"]["file"]) router.info("RapidSMS Server started up") # add each application from conf for app_conf in conf["rapidsms"]["apps"]: router.add_app(app_conf) # add each backend from conf for backend_conf in conf["rapidsms"]["backends"]: router.add_backend(backend_conf) # wait for incoming messages router.start()
def django_env(): sys.path.insert(0, os.getcwd()) import settings as djsettings setup_environ(djsettings) try: yield finally: sys.path.pop(0)
#!/usr/bin/env python # coding:utf-8 import json # ------------------------------------------------------------------------------------ # 设置环境变量: sys.path(Initialized from the environment variable PYTHONPATH) import sys sys.path.append('/home/workspace/medusa') # 设置 Django settings from django.core.management import setup_environ from medusaweb import settings as django_settings setup_environ(django_settings) # 使用 Django ORM from medusaweb.spider.models import Movie # <class 'medusaweb.spider.models.Movie'> # ------------------------------------------------------------------------------------ # print '============================================================================ ElasticSearch' from pyelasticsearch import ElasticSearch es = ElasticSearch( urls='http://192.168.100.100', port=9200, ) # print es # <pyelasticsearch.client.ElasticSearch object at 0x1c86a90> # print '============================================================================ [1] create index' def create_index(): # 读 django 数据库, 获取模型数据 docs_movies = Movie.objects.all().values() # print docs_movies # [
# 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('.')) #Add the path of your virtualenv #sys.path.append('/home/areski/.virtualenvs/cdr-stats/lib/python2.7/site-packages/') APP_DIR = os.path.normpath(os.path.join(os.getcwd(), '../../')) + '/' APP_DIR_CDRSTATS = os.path.normpath(os.path.join(os.getcwd(), '../../')) + '/cdr_stats/' sys.path.insert(0, APP_DIR) sys.path.insert(1, APP_DIR_CDRSTATS) import cdr_stats.settings from django.core.management import setup_environ setup_environ(cdr_stats.settings) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # 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', 'sphinx.ext.coverage'] #extensions = ['sphinx.ext.autodoc', 'rst2pdf.pdfbuilder', 'sphinx.ext.coverage'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames.
# urlannotator documentation build configuration file, created by # sphinx-quickstart on Thu Jul 19 17:13:37 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os sys.path.append('%(manage_py_dir)s') from urlannotator.settings import development from django.core.management import setup_environ setup_environ(development) # 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' # 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']
import sys, os from conf.settings import TARGET_DJANGO_PROJ_PATH sys.path.append(TARGET_DJANGO_PROJ_PATH) from celery_app import app from django.core.wsgi import get_wsgi_application from django.core.management import setup_environ import GridForecastSys.settings from apps.Station.models import GridInfo import utils.file_readgrids os.environ.setdefault("DJANGO_SETTINGS_MODULE", "GridForecastSys.settings") application = get_wsgi_application() setup_environ(GridForecastSys.settings) # from GridForecastSys import settings def init(): print(GridForecastSys.settings.AreaNames_Dict) init() def initGrid(): for key in GridForecastSys.settings.AreaNames_Dict: value = GridForecastSys.settings.AreaNames_Dict[key] + ".txt" save_gridinfo(key, GridForecastSys.settings.AreaNames_DIR, value)
__FILENAME__ = fabfile from __future__ import with_statement import os from django.core import management # We have to re-name this to avoid clashes with fabric.api.settings. import settings as django_settings management.setup_environ(django_settings) from fabric.api import * # This will import every command, you may need to get more selective if # you aren't using all of the stuff we do. # For example: # from fabtastic.fabric.commands.c_common import * # from fabtastic.fabric.commands.c_git import git_pull from fabtastic.fabric.commands import * """ Here are some deployment related settings. These can be pulled from your settings.py if you'd prefer. We keep strictly deployment-related stuff in our fabfile.py, but you don't have to. """ # The path on your servers to your codebase's root directory. This needs to # be the same for all of your servers. Worse case, symlink away. env.REMOTE_CODEBASE_PATH = '/home/account/codebase' # Path relative to REMOTE_CODEBASE_PATH. env.PIP_REQUIREMENTS_PATH = 'requirements.txt' # The standardized virtualenv name to use. env.REMOTE_VIRTUALENV_NAME = 'your_virtualenv' # This is used for reloading gunicorn processes after code updates. # Only needed for gunicorn-related tasks.
# This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os sys.path.insert(0, os.path.abspath('../src')) from fabric_bolt.core.settings import local from django.core.management import setup_environ setup_environ(local) # 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' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [
# -*- coding: utf-8 -*- # import os import sys sys.path.insert(0, os.path.abspath('../readthedocs')) import settings.sqlite from django.core.management import setup_environ setup_environ(settings.sqlite) sys.path.append(os.path.abspath('_ext')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx_http_domain', 'djangodocs', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Read The Docs' copyright = u'2010, Eric Holscher, Charlie Leifer, Bobby Grace' version = '1.0' release = '1.0' exclude_patterns = ['_build'] default_role = 'obj' pygments_style = 'sphinx' intersphinx_mapping = { 'python': ('http://python.readthedocs.org/en/latest/', None), 'django': ('http://django.readthedocs.org/en/latest/', None), 'sphinx': ('http://sphinx.readthedocs.org/en/latest/', None),
import MySQLdb import twitter import time import sys sys.path.append('/home/ec2-user/code/charitweets') from django.core.management import setup_environ import charitweets.settings setup_environ(charitweets.settings) from django.contrib.auth.models import User api = twitter.Api('5g55QBgZPuiX7dGdZPoVg', '07yF7MBTPnjHEsUmEjMUIWcz3BOFh56rjR9edamUxw', '1364466696-Ma1SP8u47oKsu7Dl9Kp3I0T9fTnidnqEeFxZuEn', 'CUA6YHD0rlqLcS4X9a4udOgQjcGcn5QPMx6SLHtWiX4') with open('prev_tweet') as f: last_id = long(f.readlines()[0]) latest_tweets = api.GetReplies() #since_id = last_id) if len(latest_tweets) > 0: for tweet in latest_tweets: print tweet.GetUser().GetScreenName(), "!!!!!", tweet.GetText() try: user = User.objects.filter( username=tweet.GetUser().GetScreenName())[0] stripe_cards = [ card for card in user.stripecustomer_set.all() if card.valid ]
try: import settings as settings_mod # Assumed to be in the same directory. except ImportError: sys.stderr.write( "Error: Can't find the file 'settings.py' in the directory " \ "containing %r. It appears you've customized things.\nYou'll have " \ "to run django-admin.py, passing it your settings module.\n(If the " \ "file settings.py does indeed exist, it's causing an ImportError " \ "somehow.)\n" % __file__) sys.exit(1) import sys # setup the environment before we start accessing things in the settings. setup_environ(settings_mod) sys.path.insert(0, join(settings.PROJECT_ROOT, "apps")) from django.contrib.auth.models import User from django.db.models import Q from components.analytics.models import MakahikiLog MIN_SESSION = 60 # Assume user spends 60 seconds on a single page. USER_HEADER = 'user id,total seconds spent,home seconds spent, ' \ 'activities seconds spent,energy seconds spent, ' \ 'prizes seconds spent,news seconds spent,' \ 'profile seconds spent, help seconds spent,' \ 'canopy seconds spent\n'
#!/usr/bin/env python #coding:utf-8 from mongoengine import * import os, sys try: os.environ["DJANGO_SETTINGS_MODULE"] except Exception, what: sys.path.insert( 0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from django.core.management import setup_environ import settings setup_environ(settings) from settings import MEDIA_ROOT from images.models import Image, Album, create_image from images.utils import is_image, get_client_ip import json import utils def delete_image(uid, delhash): try: im = Image.objects.get(uid=uid) if delhash and im.delhash == delhash: # delete image from album and delete album if empty try: for a in im.albums: a.images.remove(im) a.save() if not a.images:
# -*- coding: utf-8 -*- import sys import time sys.path.append('D:/work/python/proc/src/') from django.core import management import mysite.settings as settings management.setup_environ(settings) from mysite.proc.models import * from mysite.proc.sys_model import * from mysite.proc.service_model import * from mysite.proc.tarif_model import * from mysite.proc.gateway import * import urllib2 import xml.etree.ElementTree as xml from datetime import datetime from django.db.models import Q from mysite.proc.helpers import * from mysite.route import * #import datetime #отправка всех данных и проверка ошибок def megafon_send_data(trans, url, gatew): err_code = dt_oper = reciept_num = '' #переменные которые возвращаются, если пустые, то нет ответа от сервера #произвести запись в справочник лог данные url ins_log(trans, url, True) # login = gatew.login password = gatew.password
#!/usr/bin/python # -*- coding: utf-8 -*- # make it possible to run as standalone program import sys import string import re sys.path.append('/srv/chemminetools') from django.core.management import setup_environ import chemminetools.settings setup_environ(chemminetools.settings) from django.contrib.auth.models import User from django.conf import settings from django.contrib import messages # load functions used from pubchem_soap_interface.DownloadCIDs import DownloadCIDs def main(): cids = sys.stdin.read() cids = cids.split() filteredCIDs = [] for cid in cids[:]: match = re.search("(\d{1,200})", cid) if match: filteredCIDs.append(int(match.group(1))) if len(filteredCIDs) > 0:
#__email__ = "*****@*****.**" #__website__ = "www.bemoss.org" #__created__ = "2014-09-12 12:04:50" #__lastUpdated__ = "2016-03-14 11:23:33" ''' __author__ = 'kruthika' import os import sys sys.path.append( os.path.dirname(os.path.realpath(__file__)).replace('/run', '')) from django.core.management import setup_environ import settings_tornado setup_environ(settings_tornado) from apps.alerts.models import Priority, NotificationChannel, EventTrigger, DeviceType, SeenNotifications, TempFailureTime from apps.dashboard.models import DeviceModel, Building_Zone from django.contrib.auth.models import Group, User from apps.dashboard.models import GlobalSetting from apps.schedule.models import Holiday from apps.discovery.models import Miscellaneous import datetime DEVICE_TYPE_CHOICES = (('1TH', 'thermostat'), ('1VAV', 'VAV'), ('1RTU', 'RTU'), ('2HUE', 'philips hue'), ('2WL', 'wemo light switch'), ('2WSL', 'wattstopper lighting'), ('3WSP', 'wemo smart plug'), ('3WIS', 'wemo insight switch'), ('3WP', 'wattstopper plugload'))
#!/usr/bin/env python # -*- coding:Utf-8 -*- #from python import os import re HERE = os.path.realpath(os.path.dirname(__file__)) # from project try: # Get the list of applications from the settings import settings from django.core.management import setup_environ setup_environ(settings) # some apps will fail to load without some # specific settings except ImportError: raise ImportError("The script should be run from the project root") class Modules(object): """ auto_modules.rst file to store all the apps automodules """ def __init__(self): self.internal_apps = [] self.external_apps = [] self.fname = settings.DS_FILENAME
#!/usr/bin/env python import os import sys from django.core.management import call_command, setup_environ if __name__ == '__main__': scripts_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.abspath(os.path.join(scripts_dir, '..', '..'))) sys.path.insert(0, os.path.join(scripts_dir, 'conf')) os.putenv('FORCE_BUILD_MEDIA', '1') import reviewboard.settings setup_environ(reviewboard.settings) ret = call_command('collectstatic', interactive=False, verbosity=2) sys.exit(ret)
#!/usr/bin/python """foreman sample test against portal""" import sys from portal.foreman import Foreman from django.core.management import setup_environ import nuages.settings setup_environ(nuages.settings) from portal.models import * profile = 'basic6' name1 = 'k1000' name2 = 'k8000' environment = 'production' classname = 'test2' ip1 = "192.168.8.90" dns = "ib" hostgroup = "default" parameters = "testdir=/root/megafrout" profile = Profile.objects.get(name=profile) foremanprovider = profile.foremanprovider foremanhost, foremanport, foremanuser, foremanpassword = foremanprovider.host, foremanprovider.port, foremanprovider.user, foremanprovider.password f = Foreman(foremanhost, foremanport, foremanuser, foremanpassword) #print f.exists(name1,dns) #print f.delete(name1,dns) #print f.hostgroups(environment) #classes = f.classes(environment) #print classes #for classe in classes: # print f.classinfo(classe)
def start(args): # if a specific conf has been provided (which it # will be), if we're inside the django reloaded if "RAPIDSMS_INI" in os.environ: ini = os.environ["RAPIDSMS_INI"] # use a local ini (for development) # if one exists, to avoid everyone # having their own rapidsms.ini elif os.path.isfile("local.ini"): ini = "local.ini" # otherwise, fall back else: ini = "rapidsms.ini" # add the ini path to the environment, so we can # access it globally, including any subprocesses # spawned by django os.environ["RAPIDSMS_INI"] = ini # read the config, which is shared # between the back and frontend conf = Config(ini) # if we found a config ini, try to configure Django if conf.sources: # import the webui settings, which builds the django # config from rapidsms.config, in a round-about way. # can't do it until env[RAPIDSMS_INI] is defined from rapidsms.webui import settings import_local_settings(settings, ini) import_i18n_sms_settings(conf) # whatever we're doing, we'll need to call # django's setup_environ, to configure the ORM os.environ["DJANGO_SETTINGS_MODULE"] = "rapidsms.webui.settings" from django.core.management import setup_environ, execute_manager setup_environ(settings) else: settings = None # if one or more arguments were passed, we're # starting up django -- copied from manage.py if len(args) < 2: print "Commands: route, testroute, runserver, startproject <name>, startapp <name>" sys.exit(1) if hasattr(Manager, args[1]): handler = getattr(Manager(), args[1]) handler(conf, *args[2:]) elif settings: # none of the commands were recognized, # so hand off to Django from django.core.management import ManagementUtility # The following is equivalent to django's "execute_manager(settings)" # only without overriding RapidSMS webui settings utility = ManagementUtility() utility.execute()
try: import django except ImportError: msg = ( 'django must be included in the "libraries:" clause of your app.yaml ' 'file when using the django_wsgi builtin.') logging.error(msg) raise RuntimeError(msg) from django.core import management from django.core.handlers import wsgi try: settings = __import__(settings_path) management.setup_environ(settings, original_settings_path=settings_path) except ImportError: pass app = wsgi.WSGIHandler() def main(): """Main program. Run the Django WSGIApplication.""" util.run_wsgi_app(app) if __name__ == '__main__': main()
# sphinx-quickstart on Thu Sep 29 15:20:35 2011. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os from django.conf import global_settings from django.core.management import setup_environ setup_environ(global_settings, original_settings_path='django.conf.global_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. sys.path.insert(0, os.path.abspath('..')) from jsonit import get_version # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
def init(): import settings setup_environ(settings)
#!/usr/bin/env python # -*- coding: utf-8 -*- #python2.7x django_orm_use.py zhizhi.liu@2014-03-21 import sys, os #pro_dir = '' #可以自己用绝对路径定义,目的是工程目录下 pro_dir = os.getcwd() #如果放在project目录,就不需要在配置绝对路径了 sys.path.append(pro_dir) os.environ['DJANGO_SETTINGS_MODULE'] = 'nirvana.settings' #项目的settings from django.core.management import setup_environ import settings #导入settings setup_environ(settings) #设置settings #===============调用代码部分================ from userManage.models import UserProfile print UserProfile.objects.all().count()
# -*- coding: utf-8 -*- import re import os import sys import codecs #import win32console from datetime import datetime #PROJECT_ROOT = os.path.join('D:/GitHub/disser_db/BigTable/BigTable') #sys.path.insert(0,PROJECT_ROOT) from django.core.management import setup_environ import BigTable.settings setup_environ(BigTable.settings) from django.core.exceptions import ObjectDoesNotExist from exams.models import Patient,Examination,Perfusion,Density,Phase #os.popen('chcp').read() #import locale #encoding = locale.getpreferredencoding(do_setlocale=True) """ reload(sys) sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() print sys.stdout.encoding # win32 win32console.SetConsoleCP(65001) sys.stdout = codecs.getwriter('utf8')(sys.stdout)
logger.warning("Broker logging handler does not set.") SOBEK_PROGRAM_ID = 1 HISSSM_PROGRAM_ID = 2 IMPORT_PROGRAM_ID = 3 GDAL_MEM_DRIVER = gdal.GetDriverByName(b'mem') GDAL_TIFF_DRIVER = gdal.GetDriverByName(b'gtiff') if __name__ == '__main__': sys.path.append('..') from django.core.management import setup_environ import lizard.settings setup_environ(lizard.settings) def common_generation(scenario_id, source_programs, tmp_dir): """ loop on all results computed for the given scenario_id, unpack them into a temporary directory, save as a pyramid, set in the results record. """ scenario = Scenario.objects.get(pk=scenario_id) maxwaterdepth_geotransform = ( calculate_export_maps.maxwaterdepth_geotransform(scenario)) logger.debug("select results relative to scenario %s" % scenario_id)
import sys sys.path.append('/home/alessandro/LAS/beamingManager/trunk/beaming/') #sys.path.append('/srv/www/beaming/') from django.core.management import setup_environ import beaming.settings setup_environ(beaming.settings) import shutil import argparse from __init__ import * import locale locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) def readMeasures (exp): header = True listMeasure = [] positions = {} mutations = {} aliquots = {} fin = open(exp) for line in fin: tokens = line.strip().split('\t') print tokens, len(tokens) if len(tokens) == 1: # line between samples header = True else: if header: # retrieve the header of the measures and the sample info sample_info = tokens[0].split(':')[1].strip().split() print sample_info
#!/usr/bin/env python import sys sys.path.append('/home/leon/projects/notebookWebapp/') from django.core import management; import notebook; import notebook.settings as settings;management.setup_environ(settings) from notebook.notes.views import getT, getW def add2workingset(username): W = getW(username) T = getT(username) tags = T.objects.all() w, created = W.objects.get_or_create(name='snippetbook') w.tags = tags#.values_list('id', flat=True) w.save() print 'a workingset is saved:', w.name, ' with tags: ', w.tags #TODO: more help for the command inputs if __name__ == "__main__": add2workingset(sys.argv[1])
# Setup django so we can run this from command-line from django.core.management import setup_environ import os import sys sys.path = [os.path.join(os.path.dirname(__file__), '../..')] + sys.path import ieeetags.settings setup_environ(ieeetags.settings) # ----- import time import urllib2 def get_url_time(url): start = time.time() url = urllib2.urlopen(url) end = time.time() return end - start urls = [ 'http://localhost:8001/', 'http://localhost:8001/ajax/textui_nodes?sector_id=all&sort=connectedness&search_for=', #'http://localhost:8001/ajax/tooltip/1170?parent_id=all&society_id=null&search_for=None', ] results = [] for url in urls: time1 = get_url_time(url)
def runserver(environ, start_response): if ws_connector(environ) != True: # If environment is not WebSocket, then call django server setup_environ(settings) application = DjangoWSGIApp() return application.__call__(environ, start_response)
import sys sys.path.append('/srv/www/fingerPrinting/') from django.core.management import setup_environ import fingerprinting.settings setup_environ(fingerprinting.settings) import shutil import argparse from __init__ import * import json import ast import datetime ## DEFINITIONS ## # Dictionaries sampleInfo = {} cases = {} # cases = {case:[samples]} sample_cases = {} # sample_cases = {sample:case} analyses = {} # analyses = {sample:{SNP:genotype}} # result = {SNP:genotype} refs = {} # refs = {type:[sample]} refs["germline"] = {} refs["tumor"] = {} summary_results = {} # scores = {sample:{ref_type:{ref:score}}} filtered_results = {} mismatched_cases = [] scores_to_germlines = {} scores_to_tumors = {} scores_to_case = {}
import site, sys sys.path.append('/home/ubuntu/code/dg_git') site.addsitedir( '/home/ubuntu/.virtualenv/dg_production/lib/python2.7/site-packages/') from django.core.management import setup_environ import dg.settings setup_environ(dg.settings) from django.db.models import Min, F from activities.models import * from coco.models import * from geographies.models import * from programs.models import * from people.models import * from videos.models import * #Village Start Dates vils = Village.objects.annotate(min_sc=Min("screening__date")) update_blocks = [] for vil in vils: if type(vil.start_date) != type( vil.min_sc) or vil.start_date != vil.min_sc: vil.start_date = vil.min_sc vil.save() update_blocks.append(vil.block.id) if not update_blocks: exit()
# coding=utf-8 ''' Created on 2015年4月25日 足球比赛按照指定的指数声音提示 http://bf.310v.com/3.html @author: Administrator ''' from splinter import Browser from bs4 import BeautifulSoup as BS import time import re import winsound import datetime from django.core.management import setup_environ import football.settings setup_environ(football.settings) from spider.models import News def get_now(): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) def spider(): browser = Browser() browser.visit('http://www.baidu.com') browser.execute_script( "window.location.href = 'http://bf.310v.com/3.html'") time.sleep(10) while True: import config