コード例 #1
0
def insertIntoGallery(
    gallery_title,
    gallery_slug,
    screenshot,
    title,
    slug,
    gallery_description="",
    gallery_tags="",
    caption="",
    tags="",
    fab_dir='%s/.fabric-bolt' % (os.path.expanduser('~/'))
):
    # Add custom fabric-bolt settings directory
    sys.path.insert(0, fab_dir)
    # Utilize django within fabfile
    # Load custom fabric-bolt settings file
    django.settings_module('settings')
    # Loads the django Models
    get_wsgi_application()
    # Once loaded we can reference them
    from photologue.models import Photo
    from photologue.models import Gallery

    file = open(screenshot, 'rb')
    data = file.read()

    # First Generate or Retrieve the Photo Model and save or update it
    try:
        photo = Photo.objects.get(slug=slug)
        photo.date_added = datetime.now()
        photo.date_taken = datetime.now()
        print("~~~ FOUND existing Screenshot ~~~")
    except Photo.DoesNotExist:
        photo = Photo(title=title, slug=slug, caption=caption, is_public=True, tags=tags,)
        print("~~~ CREATED new Screenshot ~~~")

    try:
        photo.image.save(os.path.basename(screenshot), ContentFile(data))
    except FieldError:
        # For some reason a field, 'photo,' is being passed to model as a field.
        pass
    print("~~~ SAVED Screenshot ~~~")

    # Now Create or Retrieve the named Gallery and add the photo to it.
    gallery = None
    try:
        gallery = Gallery.objects.get(title=gallery_title)
        print("~~~ FOUND existing Screenshot Gallery ~~~")
    except Gallery.DoesNotExist:
        gallery = Gallery(title=gallery_title, slug=gallery_slug, description=gallery_description, is_public=True, tags=gallery_tags,)
        gallery.save()
        print("~~~ CREATED new Screenshot Gallery ~~~")

    if gallery:
        gallery.photos.add(photo)
        print("~~~ Added Screenshot to Gallery ~~~")
        print("<a target=\"_parent\" href=\"/photologue/gallery/%s\">View Screenshot Gallery %s</a>") % (gallery_title, gallery_title)

    # Reset the syspath
    sys.path.remove(fab_dir)
コード例 #2
0
ファイル: conf.py プロジェクト: hdknr/flier
def setup(app):
    ''' SETUP '''
    from django.core.wsgi import get_wsgi_application
    get_wsgi_application()

    from app.sphinx import process_docstring
    # Register the docstring processor with sphinx
    app.connect('autodoc-process-docstring', process_docstring)
コード例 #3
0
ファイル: runtests.py プロジェクト: Debetux/django-seo2
def runtests():
    os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"

    from django.core.wsgi import get_wsgi_application
    get_wsgi_application()

    from django.core.management import call_command
    result = call_command('test', 'userapp')
    sys.exit(result)
コード例 #4
0
ファイル: wsgi.py プロジェクト: fanglansheng/grumblr
def application(environ, start_response):
    if 'DJANGO_SETTINGS_MODULE' in environ:
        os.environ['DJANGO_SETTINGS_MODULE'] = environ['DJANGO_SETTINGS_MODULE']

    for var in env_variables_to_pass:
        os.environ[var] = environ.get(var, '')
    return get_wsgi_application()(environ, start_response)
コード例 #5
0
ファイル: tg.py プロジェクト: BYU-NLP-Lab/topicalguide
def exec_list(args):
    """List the datasets and analyses."""
    import os
    os.environ['DJANGO_SETTINGS_MODULE'] = 'topicalguide.settings'
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    from visualize.api import query_datasets
    options = { 
        'datasets': '*', 'dataset_attr': ['metadata'],
        'analyses': '*', 'analysis_attr': ['metadata'],
    }
    
    datasets = query_datasets(options)
    if len(datasets) == 0:
        print('No datasets in database.')
    else:
        print('Format is as follows:')
        print("dataset-identifier (dataset's-readable-name)")
        print("\tanalysis-identifier (analysis'-readable-name)")
        print()
        
        print('Datasets:')
        for dataset, items in datasets.iteritems():
            print(dataset+" ("+items['metadata']['readable_name']+")")
            analyses = items['analyses']
            if len(analyses) == 0:
                print('\tNo analyses available.')
            else:
                for analysis, items2 in analyses.iteritems():
                    print('\t'+analysis+" ("+items2['metadata']['readable_name']+")")
コード例 #6
0
ファイル: wsgi.py プロジェクト: grahame/ealgis
def application(environ, start):

    # copy any vars into os.environ
    for key in environ:
        os.environ[key] = str(environ[key])

    return get_wsgi_application()(environ, start)
コード例 #7
0
 def setUpClass(cls):
     # Keep a record of the original lazy storage instance so we can
     # restore it afterwards. We overwrite this in the setUp method so
     # that any new settings get picked up.
     if not hasattr(cls, '_originals'):
         cls._originals = {'staticfiles_storage': storage.staticfiles_storage}
     # Make a temporary directory and copy in test files
     cls.tmp = tempfile.mkdtemp()
     settings.STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
     settings.STATICFILES_DIRS = [os.path.join(cls.tmp, 'static')]
     settings.STATIC_ROOT = os.path.join(cls.tmp, 'static_root')
     settings.WHITENOISE_ROOT = os.path.join(cls.tmp, 'root')
     for path, contents in TEST_FILES.items():
         path = os.path.join(cls.tmp, path.lstrip('/'))
         try:
             os.makedirs(os.path.dirname(path))
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
         with open(path, 'wb') as f:
             f.write(contents)
     # Collect static files into STATIC_ROOT
     call_command('collectstatic', verbosity=0, interactive=False)
     # Initialize test application
     django_app = get_wsgi_application()
     cls.application = DjangoWhiteNoise(django_app)
     cls.server = TestServer(cls.application)
     super(DjangoWhiteNoiseTest, cls).setUpClass()
コード例 #8
0
def main():
    
    os.environ['DJANGO_SETTINGS_MODULE'] = 'YoYoProject.settings' # path to your settings module
    #application = django.core.handlers.wsgi.WSGIHandler()
    wsgi_app  = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(wsgi_app)
    
    
    settings = dict(
            #template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True,
        )
    
    tornado_app = tornado.web.Application(
        [
            (r'/hello-tornado', YYTornadoHandler),
            (r'/WebSocket/([a-zA-Z0-9]*)$', YYWebSocketHandler),
            ('.*', tornado.web.FallbackHandler, dict(fallback=container)),
        ], **settings)
    
   #container = tornado.wsgi.WSGIContainer(tornado_app)
    http_server = tornado.httpserver.HTTPServer(tornado_app)
    http_server.listen(options.port)
    
    print "start tornado with django at %d" %options.port
    tornado.ioloop.IOLoop.instance().start()
コード例 #9
0
ファイル: django.py プロジェクト: johnwheeler/Zappa
def get_django_wsgi(settings_module):
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)

    import django
    django.setup()

    return get_wsgi_application()
コード例 #10
0
 def setUpClass(cls):
     # Make a temporary directory and copy in test files
     cls.tmp = tempfile.mkdtemp()
     settings.STATICFILES_DIRS = [os.path.join(cls.tmp, 'static')]
     settings.WHITENOISE_USE_FINDERS = True
     settings.WHITENOISE_AUTOREFRESH = True
     for path, contents in TEST_FILES.items():
         path = os.path.join(cls.tmp, path.lstrip('/'))
         try:
             os.makedirs(os.path.dirname(path))
         except OSError as e:
             if e.errno != errno.EEXIST:
                 raise
         with open(path, 'wb') as f:
             f.write(contents)
     # Clear cache to pick up new settings
     try:
         finders.get_finder.cache_clear()
     except AttributeError:
         finders._finders.clear()
     # Initialize test application
     django_app = get_wsgi_application()
     cls.application = DjangoWhiteNoise(django_app)
     cls.server = TestServer(cls.application)
     super(UseFindersTest, cls).setUpClass()
コード例 #11
0
ファイル: tests.py プロジェクト: EmadMokhtar/django
    def test_get_wsgi_application(self):
        """
        get_wsgi_application() returns a functioning WSGI callable.
        """
        application = get_wsgi_application()

        environ = self.request_factory._base_environ(
            PATH_INFO="/",
            CONTENT_TYPE="text/html; charset=utf-8",
            REQUEST_METHOD="GET"
        )

        response_data = {}

        def start_response(status, headers):
            response_data["status"] = status
            response_data["headers"] = headers

        response = application(environ, start_response)

        self.assertEqual(response_data["status"], "200 OK")
        self.assertEqual(
            set(response_data["headers"]),
            {('Content-Length', '12'), ('Content-Type', 'text/html; charset=utf-8')})
        self.assertIn(bytes(response), [
            b"Content-Length: 12\r\nContent-Type: text/html; charset=utf-8\r\n\r\nHello World!",
            b"Content-Type: text/html; charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!"
        ])
コード例 #12
0
def import_crash_csv(dir,file):
    application = get_wsgi_application()
    from capstone.models import Crash
    file_name = os.path.join(dir, file)
    with open(file_name, "rU") as infile:
        reader = csv.reader(infile)
        next(reader, None)  # skip the headers
        crash_list = []
        for row in reader:
            if not row or len(row) < 20:
                continue
            crn, year, month, day, hour, intersect_type, collision_type, \
            fatal_count, injury_count, sev_inj_count,maj_inj_count, \
            mcycle_death_count, mcycle_sev_inj_count, \
            bicycle_death_count, bicycle_sev_inj_count, ped_death_count, \
            ignore, max_severity_level, lat, lng = row
            crash = Crash(crn=crn, year=year, month=month, day=day, hour=hour, intersect_type=intersect_type,
                          collision_type=collision_type, fatal_count=fatal_count, injury_count=injury_count,
                          sev_inj_count=sev_inj_count,maj_inj_count=maj_inj_count, mcycle_death_count=mcycle_death_count,
                          mcycle_sev_inj_count=mcycle_sev_inj_count,bicycle_death_count=bicycle_death_count, bicycle_sev_inj_count=bicycle_sev_inj_count,
                          ped_death_count=ped_death_count, max_severity_level=max_severity_level, lat=lat, lng=lng)
            crash_list.append(crash)
            print row
        Crash.objects.bulk_create(crash_list)
    print "Load data complete"
コード例 #13
0
ファイル: run_server.py プロジェクト: Astraeux/jumpserver
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()
コード例 #14
0
def main():
    os.environ['DJANGO_SETTINGS_MODULE'] = 'haldir.settings'
    sys.path.append('./haldir')

    parse_command_line()

    wsgi_app = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(wsgi_app)

    settings = {
        'debug': True,
        'autoreload': True,
        # 'static_path': '/tmp/org.au9ustine.haldir/static'
    }
    
    tornado_app = tornado.web.Application(
    [
        (r'/hello-tornado', HelloHandler),
        (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': '/tmp/org.au9ustine.haldir/static'}),
        (r'.*', tornado.web.FallbackHandler, dict(fallback=container)),
    ], **settings)
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port)
    
    tornado.ioloop.IOLoop.instance().start()
コード例 #15
0
ファイル: wsgi.py プロジェクト: grangerp/test_presentation
def application(environ, start_response):
    """
    Grap Environement vars and return class Django WSGI application.
    """
    if 'VIRTUALENV_PATH' in environ.keys():
        os.environ['VIRTUALENV_PATH'] = environ['VIRTUALENV_PATH']

    if 'DJANGO_SETTINGS_MODULE' in environ.keys():
        os.environ['DJANGO_SETTINGS_MODULE'] = \
            environ['DJANGO_SETTINGS_MODULE']

    ROOT = os.path.dirname(__file__)
    VIRTUALENV_PATH = os.environ['VIRTUALENV_PATH']

    version = 'python%s' % sys.version[0:3]

    site_packages = os.path.join(
        VIRTUALENV_PATH, 'lib', version, 'site-packages')
    site.addsitedir(site_packages)

    sys.path.append(ROOT)

    activate_this = os.path.join(
        VIRTUALENV_PATH, 'bin', 'activate_this.py')
    activate_env = os.path.expanduser(activate_this)
    execfile(activate_env, dict(__file__=activate_env))

    from django.core.wsgi import get_wsgi_application
    _wsgi_application = get_wsgi_application()
    return _wsgi_application(environ, start_response)
コード例 #16
0
ファイル: importd.py プロジェクト: saevarom/importd
    def _import_django(self):
        from smarturls import surl

        self.surl = surl
        from django.http import HttpResponse, Http404, HttpResponseRedirect

        self.HttpResponse = HttpResponse
        self.Http404 = Http404
        self.HttpResponseRedirect = HttpResponseRedirect
        from django.shortcuts import get_object_or_404, render_to_response

        self.get_object_or_404 = get_object_or_404
        self.render_to_response = render_to_response
        from django.conf.urls.defaults import patterns, url

        self.patterns = patterns
        self.url = url
        from django.template import RequestContext

        self.RequestContext = RequestContext
        from django.core.wsgi import get_wsgi_application

        self.wsgi_application = get_wsgi_application()
        from django import forms

        self.forms = forms
        from fhurl import RequestForm, fhurl, JSONResponse

        self.fhurl = fhurl
        self.RequestForm = RequestForm
        self.JSONResponse = JSONResponse
コード例 #17
0
ファイル: test_wsgi.py プロジェクト: Fiware/cloud.Cloto
    def test_get_wsgi_application(self):
        """
        Verify that ``get_wsgi_application`` returns a functioning WSGI callable.
        """
        application = get_wsgi_application()
        environ = RequestFactory()._base_environ(
            PATH_INFO="/info",
            CONTENT_TYPE="text/html; charset=utf-8",
            REQUEST_METHOD="GET"
            )
        response_data = {}

        def start_response(status, headers):
            response_data["status"] = status
            response_data["headers"] = headers
        response = application(environ, start_response)
        self.assertEqual(response_data["status"], "500 Internal Server Error")
        self.assertEqual(
            response_data["headers"],
            [('Content-Type', 'text/html; charset=utf-8')])
        self.assertEqual(
            bytes(response),
            b'Content-Type: text/html; charset=utf-8\r\n\r\n{\n   '
            b' "badRequest": {\n       '
            b' "message": "Server Database does not contain information server", \n '
            b'       "code": 500\n    }\n}')
コード例 #18
0
def run_tornado(addr, port):
    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Print listening address and port to command line
    if addr == '0.0.0.0':
        url_string = "the machine's local ip address"
    else:
        url_string = 'http://%s:%s' % (addr, port)
    # TODO: don't use print, use django logging
    print("Starting OpenSlides' tornado webserver listening to %(url_string)s" % {'url_string': url_string})

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    projectpr_socket_js_router = SockJSRouter(ProjectorSocketHandler, '/projector/socket')
    from openslides.core.chatbox import ChatboxSocketHandler
    chatbox_socket_js_router = SockJSRouter(ChatboxSocketHandler, '/core/chatbox')
    other_urls = [
        (r"%s(.*)" % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))]

    # Start the application
    debug = settings.DEBUG
    tornado_app = Application(projectpr_socket_js_router.urls + chatbox_socket_js_router.urls + other_urls, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()
コード例 #19
0
    def test_get_wsgi_application(self):
        """
        Verify that ``get_wsgi_application`` returns a functioning WSGI
        callable.

        """
        application = get_wsgi_application()

        environ = RequestFactory()._base_environ(
            PATH_INFO="/",
            CONTENT_TYPE="text/html; charset=utf-8",
            REQUEST_METHOD="GET"
            )

        response_data = {}

        def start_response(status, headers):
            response_data["status"] = status
            response_data["headers"] = headers

        response = application(environ, start_response)

        self.assertEqual(response_data["status"], "200 OK")
        self.assertEqual(
            response_data["headers"],
            [('Content-Type', 'text/html; charset=utf-8')])
        self.assertEqual(
            unicode(response),
            u"Content-Type: text/html; charset=utf-8\n\nHello World!")
コード例 #20
0
ファイル: run_server.py プロジェクト: lenye/jumpserver
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)

    tornado.ioloop.IOLoop.instance().start()
コード例 #21
0
ファイル: basehttp.py プロジェクト: 1check1/my-first-blog
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])
コード例 #22
0
ファイル: wsgi.py プロジェクト: twistsys/basic-project
def _setup_application(environ, start_response):
    """
    Retrieve the relevant information from the WSGI environment and sets up the
    Django application.

    This function will (hopefully) be executed only once in the lifetime of the
    WSGI process, to initialize Django and reassign the 'application' variable.
    """

    # Retrieve the Deploy environment from the WSGI environment
    deploy_env = environ.get('DJANGO_DEPLOY_ENV', 'dev')
    os.environ['DJANGO_DEPLOY_ENV'] = deploy_env

    # See if Django version is 1.4 or 1.3
    import django

    if django.VERSION[1] == 4:
        # This is Django (probably) version 1.4
        from django.core.wsgi import get_wsgi_application
        application = get_wsgi_application()

    elif django.VERSION[1] == 3:
        import django.core.handlers.wsgi
        application = django.core.handlers.wsgi.WSGIHandler()

    else:
        start_response('200 OK', [('Content-Type', 'text/plain')])
        return ['Cannot determine the correct Django version\n']

    # Pass the present request to the just initialized application.
    return application(environ, start_response)
コード例 #23
0
ファイル: binscripts.py プロジェクト: rvanlaar/djangorecipe
def wsgi(settings_file, logfile=None):
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings_file)
    if logfile:
        import datetime

        class logger(object):
            def __init__(self, logfile):
                self.logfile = logfile

            def write(self, data):
                self.log(data)

            def writeline(self, data):
                self.log(data)

            def log(self, msg):
                line = '%s - %s\n' % (
                    datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'), msg)
                fp = open(self.logfile, 'a')
                try:
                    fp.write(line)
                finally:
                    fp.close()
        sys.stdout = sys.stderr = logger(logfile)

    # Run WSGI handler for the application
    from django.core.wsgi import get_wsgi_application
    return get_wsgi_application()
コード例 #24
0
ファイル: autoupdate.py プロジェクト: chyka-dev/OpenSlides
def run_tornado(addr, port, *args, **kwargs):
    """
    Starts the tornado webserver as wsgi server for OpenSlides.

    It runs in one thread.
    """
    # Save the port and the addr in a global var
    global RUNNING_HOST, RUNNING_PORT
    RUNNING_HOST = addr
    RUNNING_PORT = port

    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    sock_js_router = SockJSRouter(OpenSlidesSockJSConnection, '/sockjs')
    other_urls = [
        (r'%s(.*)' % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))]

    # Start the application
    debug = settings.DEBUG
    tornado_app = Application(sock_js_router.urls + other_urls, autoreload=debug, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()

    # Reset the global vars
    RUNNING_HOST = None
    RUNNING_PORT = None
コード例 #25
0
ファイル: basehttp.py プロジェクト: GravyHands/django
def get_internal_wsgi_application():
    """
    Load and return 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 server (runserver); external WSGI servers should just
    be configured to point to the correct application object directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), 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 err:
        raise ImproperlyConfigured(
            "WSGI application '%s' could not be loaded; "
            "Error importing module." % app_path
        ) from err
コード例 #26
0
ファイル: servers.py プロジェクト: StackIQ/stacki
	def runner():
		try:
			os.environ['DJANGO_SETTINGS_MODULE'] = 'stack.restapi.settings'
			basehttp.run('127.0.0.1', 8000, get_wsgi_application())
		except KeyboardInterrupt:
			# The signal to exit
			pass
コード例 #27
0
def main():
    os.environ['DJANGO_SETTINGS_MODULE'] = 'agilepoker.settings' # TODO: edit this
    sys.path.append('./agilepoker') # path to your project if needed



    wsgi_app = get_wsgi_application()
    container = tornado.wsgi.WSGIContainer(wsgi_app)
    settings = {
        "debug": True,
        "template_path": os.path.join(os.path.dirname(__file__), "web"),
        "static_path": os.path.join(os.path.dirname(__file__), "web"),
    }
    tornado_app = tornado.web.Application(
        [
            ('/login', LoginHandler),
            (r"/", MainHandler),
            ('/save', SaveGameHandler),
            (r'/channel', WebSocketHandler),
            ('.*', tornado.web.FallbackHandler, dict(fallback=container)),
        ], **settings)

    signal.signal(signal.SIGINT, signal_handler)
    server = tornado.httpserver.HTTPServer(tornado_app)
    server.listen(options.port)
    tornado.ioloop.PeriodicCallback(try_exit, 100).start()
    logger.info('Startin Tornado')
    tornado.ioloop.IOLoop.instance().start()
    print 'Tornado flush'
コード例 #28
0
ファイル: basehttp.py プロジェクト: Aliced3645/django
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
コード例 #29
0
ファイル: __init__.py プロジェクト: Betriebsrat/ecm
def run_server(instance_dir, address, port, access_log=False):

    # workaround on osx, disable kqueue
    if sys.platform == "darwin":
        os.environ['EVENT_NOKQUEUE'] = "1"

    sys.path.insert(0, instance_dir)

    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

    # This application object is used by any WSGI server configured to use this
    # file. This includes Django's development server, if the WSGI_APPLICATION
    # setting points here.
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()

    from gevent import monkey
    monkey.patch_all(dns=False)
    from gevent.pywsgi import WSGIServer

    if access_log:
        logfile = 'default'
    else:
        logfile = file(os.devnull, 'a+')

    server = WSGIServer((address, port), application, log=logfile)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.stop()
コード例 #30
0
ファイル: dj.py プロジェクト: noeldvictor/burlap
def load_django_settings():
    """
    Loads Django settings for the current site and sets them so Django internals can be run.
    """

    #TODO:remove this once bug in django-celery has been fixed
    os.environ['ALLOW_CELERY'] = '0'

    #os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dryden_site.settings")

    # In Django >= 1.7, fixes the error AppRegistryNotReady: Apps aren't loaded yet
    try:
        from django.core.wsgi import get_wsgi_application
        application = get_wsgi_application()
    except ImportError:
        pass

    # Load Django settings.
    settings = get_settings()
    try:
        from django.contrib import staticfiles
        from django.conf import settings as _settings
        for k,v in settings.__dict__.iteritems():
            setattr(_settings, k, v)
    except ImportError:
        pass
        
    return settings
コード例 #31
0
ファイル: wsgi.py プロジェクト: TonyGu423/Moviea-Django
"""
WSGI config for moviea_django 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.7/howto/deployment/wsgi/
"""

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moviea_django.settings")

from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
コード例 #32
0
 def __init__(self):
     self.django_handler = get_wsgi_application()
     self.static_handler = static.Cling(
         os.path.dirname(os.path.dirname(__file__)))
コード例 #33
0
"""
WSGI config for crime 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.11/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise


os.environ.setdefault("DJANGO_SETTINGS_MODULE", "crime.settings")

# pylint: disable=invalid-name
application = DjangoWhiteNoise(get_wsgi_application())
コード例 #34
0
ファイル: wsgi.py プロジェクト: umarmughal824/micromasters
"""
WSGI config for ui app.

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/
"""
import os

from django.core.wsgi import get_wsgi_application
from dj_static import Cling

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "micromasters.settings")

application = Cling(get_wsgi_application())  # pylint: disable=invalid-name
コード例 #35
0
def _setup_env():
    sys.path.insert(0, LS_PATH)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                          "label_studio.core.settings.label_studio")
    application = get_wsgi_application()
コード例 #36
0
"""
WSGI config for dept_mgment 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.9/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dept_mgment.settings")

application = get_wsgi_application()