Python django.core.wsgi.get_wsgi_application() Examples

The following are code examples for showing how to use django.core.wsgi.get_wsgi_application(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: labs-striker   Author: wikimedia   File: wsgi.py    GNU General Public License v3.0 6 votes vote down vote up
def bootstrap_env(wsgi_env, start_resp):
    """Bootstrap environment using wsgi provided environment values.

    Inspired by http://stackoverflow.com/a/32416606/8171
    """
    global application
    for key in wsgi_env.keys():
        # Pass DJANGO_* env vars to the application
        if key.startswith('DJANGO_'):
            os.environ[key] = wsgi_env[key]

    if os.environ.get('DJANGO_DEBUG', '').upper() == 'TRUE':
        striker.monitor.start()

    # Replace self in global scope with Django's handler
    application = get_wsgi_application()
    # Handle initial request
    return application(wsgi_env, start_resp) 
Example 2
Project: OnToology   Author: OnToology   File: autoncore.py    Apache License 2.0 6 votes vote down vote up
def django_setup_script():
    #################################################################
    #           TO make this app compatible with Django             #
    #################################################################
    import os
    import sys

    proj_path = (os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
    # venv_python = os.path.join(proj_path, '..', '.venv', 'bin', 'python')
    # This is so Django knows where to find stuff.
    sys.path.append(os.path.join(proj_path, '..'))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OnToology.settings")
    sys.path.append(proj_path)

    # This is so my local_settings.py gets loaded.
    os.chdir(proj_path)

    # This is so models get loaded.
    from django.core.wsgi import get_wsgi_application

    application = get_wsgi_application()

    ################################################################# 
Example 3
Project: Snarl   Author: hash3liZer   File: snarl.py    GNU General Public License v3.0 6 votes vote down vote up
def bind(self):
		application = GETWSGI()
		pull.print("^", "Binding the Server to Address: %s:%s" % (self.address, self.port), pull.DARKCYAN)
		pull.print("*", "You can Access Your Application Now!", pull.YELLOW)
		if self.debug:
			pull.linebreak(1)
			DJANGOCALL(
				'runserver', 
				"{}:{}".format(self.address, self.port),
				stdout=sys.stdout
			)
		else:
			DJANGOCALL(
				'runserver', 
				"{}:{}".format(self.address, self.port),
				'--noreload',
				stdout=self.npointer
			) 
Example 4
Project: Snarl   Author: hash3liZer   File: snarl.py    GNU General Public License v3.0 6 votes vote down vote up
def migrate(self, mig):
		if mig:
			pull.print(
				"*", "Migration Phase. Initializing File & Configurations.", pull.YELLOW
			)

			config = CONFIG()
			config.read_variables()
			config.generate_key()
			config.write()

			time.sleep( 3 )
			application = GETWSGI()

			pull.print("^", "Configuration Done. Uprnning Migrations Now. ", pull.DARKCYAN)
			DJANGOCALL('makemigrations', stdout=(sys.stdout if self.debug else self.npointer))
			pull.verbose("*", "Files Modified. Running Into Final Stage. ", self.verbose, pull.YELLOW)
			DJANGOCALL('migrate', stdout=(sys.stdout if self.debug else self.npointer))
			pull.halt("Migrations Applied Successfuly. Exiting Now!", True, pull.GREEN)

			return True
		return False 
Example 5
Project: scout_apm_python   Author: scoutapp   File: test_django.py    MIT License 6 votes vote down vote up
def app_with_scout(**settings):
    """
    Context manager that simply overrides settings. Unlike the other web
    frameworks, Django is a singleton application, so we can't smoothly
    uninstall and reinstall scout per test.
    """
    settings.setdefault("SCOUT_MONITOR", True)
    settings["SCOUT_CORE_AGENT_LAUNCH"] = False
    with override_settings(**settings):
        # Have to create a new WSGI app each time because the middleware stack
        # within it is static
        app = get_wsgi_application()
        # Run Django checks on first use
        if not getattr(app_with_scout, "startup_ran", False):
            call_command("migrate")
            call_command("check")
            app_with_scout.startup_ran = True
        yield app 
Example 6
Project: GTDWeb   Author: lanbing510   File: basehttp.py    GNU General Public License v2.0 5 votes vote down vote up
def get_internal_wsgi_application():
    """
    Loads and returns the WSGI application as configured by the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
    for Django's internal servers (runserver, runfcgi); external WSGI servers
    should just be configured to point to the correct application object
    directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), we just return
    whatever ``django.core.wsgi.get_wsgi_application`` returns.

    """
    from django.conf import settings
    app_path = getattr(settings, 'WSGI_APPLICATION')
    if app_path is None:
        return get_wsgi_application()

    try:
        return import_string(app_path)
    except ImportError as e:
        msg = (
            "WSGI application '%(app_path)s' could not be loaded; "
            "Error importing module: '%(exception)s'" % ({
                'app_path': app_path,
                'exception': e,
            })
        )
        six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
                    sys.exc_info()[2]) 
Example 7
Project: covador   Author: baverman   File: django_cbv_server.py    MIT License 5 votes vote down vote up
def main():
    httpd = simple_server.make_server('127.0.0.1', 5000, get_wsgi_application())
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass 
Example 8
Project: covador   Author: baverman   File: django_server.py    MIT License 5 votes vote down vote up
def main():
    httpd = simple_server.make_server('127.0.0.1', 5000, get_wsgi_application())
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass 
Example 9
Project: pandachaika   Author: pandabuilder   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def start(self) -> None:
        """ When the bus starts, the plugin is also started
        and we load the Django application. We then mount it on
        the CherryPy engine for serving as a WSGI application.
        We let CherryPy serve the application's static files.
        """
        from pandabackup import settings
        settings.crawler_settings = self.crawler_settings

        os.environ['DJANGO_SETTINGS_MODULE'] = self.settings_module

        from django.core.wsgi import get_wsgi_application

        def corsstaticdir(
                section: str, dir: str, root: str = '', match: str = '',
                content_types: None = None, index: str = '', debug: bool = False
        ) -> bool:
            cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
            return static.staticdir(section, dir, root, match, content_types, index, debug)

        cherrypy.tree.graft(self.wsgi_http_logger(get_wsgi_application(), self.crawler_settings))

        settings.WORKERS.start_workers(settings.CRAWLER_SETTINGS)

        tool = cherrypy._cptools.HandlerTool(corsstaticdir)
        static_handler = tool.handler(
            section="/",
            dir=os.path.split(settings.STATIC_ROOT)[1],
            root=os.path.abspath(os.path.split(settings.STATIC_ROOT)[0])
        )
        cherrypy.tree.mount(static_handler, settings.STATIC_URL)

        media_handler = tool.handler(
            section="/",
            dir=os.path.split(settings.MEDIA_ROOT)[1],
            root=os.path.abspath(os.path.split(settings.MEDIA_ROOT)[0])
        )
        cherrypy.tree.mount(media_handler, settings.MEDIA_URL) 
Example 10
Project: django-seo   Author: whyflyru   File: runtests.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def runtests():
    os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"

    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

    from django.core.management import call_command
    result = call_command('test', 'userapp')
    sys.exit(result) 
Example 11
Project: djwebsockets   Author: Extremus-io   File: wsgi.py    MIT License 5 votes vote down vote up
def get_wsgi_application():
    host = settings.WEBSOCKET_HOST
    port = settings.WEBSOCKET_PORT
    wsgihandler = django_wsgi()
    ws_server = server.WebSocketServer(host, port)
    ws_server.run_server()

    return wsgihandler 
Example 12
Project: tubespam   Author: tuliocasagrande   File: wsgi.py    MIT License 5 votes vote down vote up
def application(environ, start_response):
  for key in environ:
    if key.startswith('TS_'):
      os.environ[key] = environ[key]

  newrelic.agent.initialize(os.environ['TS_NEW_RELIC_CONFIG_FILE'],
                            os.environ['TS_NEW_RELIC_ENVIRONMENT'])
  return get_wsgi_application()(environ, start_response) 
Example 13
Project: classgrade   Author: classgrade   File: wsgi.py    MIT License 5 votes vote down vote up
def loading_app(environ, start_response):
        global real_app

        # pass the WSGI environment variables on through to os.environ
        for var in env_variables_to_pass:
            os.environ[var] = environ.get(var, '')
        real_app = get_wsgi_application()
        return real_app(environ, start_response) 
Example 14
Project: paas-tools   Author: imperodesign   File: wsgi.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.django_handler = get_wsgi_application()
        self.static_handler = static.Cling(os.path.dirname(os.path.dirname(__file__))) 
Example 15
Project: paas-tools   Author: imperodesign   File: wsgi.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.django_handler = get_wsgi_application()
        self.static_handler = static.Cling(os.path.dirname(os.path.dirname(__file__))) 
Example 16
Project: luscan-devel   Author: blackye   File: basehttp.py    GNU General Public License v2.0 5 votes vote down vote up
def get_internal_wsgi_application():
    """
    Loads and returns the WSGI application as configured by the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
    for Django's internal servers (runserver, runfcgi); external WSGI servers
    should just be configured to point to the correct application object
    directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), we just return
    whatever ``django.core.wsgi.get_wsgi_application`` returns.

    """
    from django.conf import settings
    app_path = getattr(settings, 'WSGI_APPLICATION')
    if app_path is None:
        return get_wsgi_application()
    module_name, attr = app_path.rsplit('.', 1)
    try:
        mod = import_module(module_name)
    except ImportError as e:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "could not import module '%s': %s" % (app_path, module_name, e))
    try:
        app = getattr(mod, attr)
    except AttributeError as e:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "can't find '%s' in module '%s': %s"
            % (app_path, attr, module_name, e))

    return app 
Example 17
Project: geekcloud   Author: Tangxzh317   File: run_server.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    from django.core.wsgi import get_wsgi_application
    import tornado.wsgi
    wsgi_app = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(wsgi_app)
    setting = {
        'cookie_secret': 'DFksdfsasdfkasdfFKwlwfsdfsa1204mx',
        'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
        'static_path': os.path.join(os.path.dirname(__file__), 'static'),
        'debug': False,
    }
    tornado_app = tornado.web.Application(
        [
            (r'/ws/monitor', MonitorHandler),
            (r'/ws/terminal', WebTerminalHandler),
            (r'/ws/kill', WebTerminalKillHandler),
            (r'/ws/exec', ExecHandler),
            (r"/static/(.*)", tornado.web.StaticFileHandler,
             dict(path=os.path.join(os.path.dirname(__file__), "static"))),
            ('.*', tornado.web.FallbackHandler, dict(fallback=container)),
        ], **setting)

    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port, address=IP)

    tornado.ioloop.IOLoop.instance().start() 
Example 18
Project: ODM2ControlledVocabularies   Author: ODM2   File: wsgi.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def application(environ, start_response):
    os.environ['DJANGO_SETTINGS_MODULE'] = environ.get('DJANGO_SETTINGS_MODULE', '')
    return get_wsgi_application()(environ, start_response) 
Example 19
Project: Zappa   Author: Miserlou   File: django_zappa.py    MIT License 5 votes vote down vote up
def get_django_wsgi(settings_module):
    from django.core.wsgi import get_wsgi_application
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)

    import django

    if django.VERSION[0] <= 1 and django.VERSION[1] < 7:
        # call django.setup only for django <1.7.0
        # (because setup already in get_wsgi_application since that)
        # https://github.com/django/django/commit/80d74097b4bd7186ad99b6d41d0ed90347a39b21
        django.setup()

    return get_wsgi_application() 
Example 20
Project: server   Author: sgr-smile2015   File: run_server.py    GNU General Public License v2.0 5 votes vote down vote up
def main():
    from django.core.wsgi import get_wsgi_application
    import tornado.wsgi
    wsgi_app = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(wsgi_app)
    setting = {
        'cookie_secret': 'DFksdfsasdfkasdfFKwlwfsdfsa1204mx',
        'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
        'static_path': os.path.join(os.path.dirname(__file__), 'static'),
        'debug': False,
    }
    tornado_app = tornado.web.Application(
        [
            (r'/ws/monitor', MonitorHandler),
            (r'/ws/terminal', WebTerminalHandler),
            (r'/kill', WebTerminalKillHandler),
            (r'/ws/exec', ExecHandler),
            (r"/static/(.*)", tornado.web.StaticFileHandler,
             dict(path=os.path.join(os.path.dirname(__file__), "static"))),
            ('.*', tornado.web.FallbackHandler, dict(fallback=container)),
        ], **setting)

    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port, address=IP)

    tornado.ioloop.IOLoop.instance().start() 
Example 21
Project: scouting-app   Author: ArcticWarriors   File: __temp_retrofil_matchresults.py    MIT License 5 votes vote down vote up
def reload_django(event_code, database_path):

    from django.core.wsgi import get_wsgi_application

    with open('../ScoutingWebsite/database_path.py', 'w') as f:
        f.write("database_path = '" + database_path + "/%s.sqlite3'" % event_code)

    os.environ["DJANGO_SETTINGS_MODULE"] = "ScoutingWebsite.settings"
    proj_path = os.path.abspath("..")
    sys.path.append(proj_path)
    _ = get_wsgi_application() 
Example 22
Project: scouting-app   Author: ArcticWarriors   File: load_django.py    MIT License 5 votes vote down vote up
def load_django():
    os.environ["DJANGO_SETTINGS_MODULE"] = "ScoutingWebsite.settings"
    proj_path = os.path.abspath("..")
    sys.path.append(proj_path)
    _ = get_wsgi_application() 
Example 23
Project: django-wechat-api   Author: crazy-canux   File: basehttp.py    GNU General Public License v3.0 5 votes vote down vote up
def get_internal_wsgi_application():
    """
    Loads and returns the WSGI application as configured by the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
    for Django's internal servers (runserver, runfcgi); external WSGI servers
    should just be configured to point to the correct application object
    directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), we just return
    whatever ``django.core.wsgi.get_wsgi_application`` returns.

    """
    from django.conf import settings
    app_path = getattr(settings, 'WSGI_APPLICATION')
    if app_path is None:
        return get_wsgi_application()

    try:
        return import_string(app_path)
    except ImportError as e:
        msg = (
            "WSGI application '%(app_path)s' could not be loaded; "
            "Error importing module: '%(exception)s'" % ({
                'app_path': app_path,
                'exception': e,
            })
        )
        six.reraise(ImproperlyConfigured, ImproperlyConfigured(msg),
                    sys.exc_info()[2])