예제 #1
0
    def test_superuser_required_mixin_not_supersuer(self):
        """Test for mixin requiring a superuser when user isn't a superuser."""
        self.client.login(username=self.username, password=self.password)

        with self.assertRaises(PermissionDenied):
            request = WSGIHandler()
            request.user = self.user

            mixin = SuperuserRequiredViewMixin()
            mixin.dispatch(request)
예제 #2
0
 def load(self):
     handler = WSGIHandler()
     try:
         from whitenoise.django import DjangoWhiteNoise
     except ImportError:
         pass
     else:
         handler = DjangoWhiteNoise(handler)
         media_root, media_prefix = self.get_media_root_and_prefix()
         handler.add_files(media_root, prefix=media_prefix)
     return handler
예제 #3
0
    def test_staff_required_mixin_is_staff(self, dispatch):
        """Test for mixin requiring a staff user when user is staff."""
        dispatch.return_value = 'worked'
        self.client.login(username=self.username, password=self.password)
        self.user.is_staff = True

        request = WSGIHandler()
        request.user = self.user

        mixin = StaffRequiredViewMixin()
        actual_return = mixin.dispatch(request)

        self.assertEqual(actual_return, dispatch.return_value)
예제 #4
0
def benchmark():

    req_factory = RequestFactory()
    handler = WSGIHandler()
    handler.load_middleware()

    with_middleware_time = time()
    handler.get_response(req_factory.get('/'))
    with_middleware_time = time() - with_middleware_time

    no_middleware_time = time()
    index(req_factory.get('/'))
    no_middleware_time = time() - no_middleware_time

    return with_middleware_time - no_middleware_time
예제 #5
0
 def render_jade_with_json(self, jade_template_path, json_file_path,
                           template_path_base, base_file):
     logger.debug('Working with jade template %s', jade_template_path)
     tmpl = loader.get_template(jade_template_path)
     if settings.DEBUG:
         logger.debug('Template is: %s',
                      process(open(os.path.join(self.template_path,
                                                jade_template_path)).read()))
     # We need to simulate request middleware but without short-circuiting
     # the response
     request_factory = RequestFactory()
     req = request_factory.get('/%s/%s.html' % (template_path_base,
                                                base_file),
                               data={})
     handler = WSGIHandler()
     handler.load_middleware()
     for middleware_method in handler._request_middleware:
         middleware_method(req)
     # Render the template with a RequestContext
     ctx = RequestContext(req, json.load(open(json_file_path)))
     return tmpl.render(ctx)
예제 #6
0
 def mock(self, base_file_name, path, template_path):
     html_template_path = os.path.join(self.app.replace('.', '/'),
                                       '%s.html' % (base_file_name,))
     json_file_path = os.path.join(path, '%s.json' % (base_file_name,))
     tmpl = loader.get_template(html_template_path)
     # We need to simulate request middleware but without short-circuiting
     # the response
     request_factory = RequestFactory()
     req = request_factory.get('/%s' % (html_template_path,),
                               data={})
     handler = WSGIHandler()
     handler.load_middleware()
     for middleware_method in handler._request_middleware:
         middleware_method(req)
     # Render the template with a RequestContext
     ctx = RequestContext(
         req,
         json.load(open(json_file_path),
                   object_hook=lambda d: DictWithSpecialUnicode(d)))
     logger.debug('Updating context with base context %s', self.base_context)
     ctx.update(self.base_context)
     return tmpl.render(ctx)
예제 #7
0
def benchmark():
    req_factory = RequestFactory()
    handler = WSGIHandler()
    
    # Try first with Django's default middleware
    settings.MIDDLEWARE_CLASSES = global_settings.MIDDLEWARE_CLASSES
    handler.load_middleware()

    with_middleware_time = time()
    handler.get_response(req_factory.get('/'))
    with_middleware_time = time() - with_middleware_time

    # Now try the same process, but this time without any middleware.
    settings.MIDDLEWARE_CLASSES = []
    handler.load_middleware()

    no_middleware_time = time()
    handler.get_response(req_factory.get('/'))
    no_middleware_time = time() - no_middleware_time

    return with_middleware_time - no_middleware_time
예제 #8
0
def setup():
    global req_factory, handler_default_middleware, handler_no_middleware
    req_factory = RequestFactory()
    
    settings.MIDDLEWARE_CLASSES = global_settings.MIDDLEWARE_CLASSES
    handler_default_middleware = WSGIHandler()
    handler_default_middleware.load_middleware()
    
    settings.MIDDLEWARE_CLASSES = []
    handler_no_middleware = WSGIHandler()
    handler_no_middleware.load_middleware()
예제 #9
0
def setup():
    global req_factory, handler_default_middleware, handler_no_middleware
    req_factory = RequestFactory()

    use_MIDDLEWARE_setting = True
    try:
        settings.MIDDLEWARE = global_settings.MIDDLEWARE
    except AttributeError:
        settings.MIDDLEWARE_CLASSES = global_settings.MIDDLEWARE_CLASSES
        use_MIDDLEWARE_setting = False
    handler_default_middleware = WSGIHandler()
    handler_default_middleware.load_middleware()

    if use_MIDDLEWARE_setting:
        settings.MIDDLEWARE = []
    else:
        settings.MIDDLEWARE_CLASSES = []
    handler_no_middleware = WSGIHandler()
    handler_no_middleware.load_middleware()
예제 #10
0
"""
WSGI config for beefun project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/
"""

import os, sys, django
from django.core.wsgi import get_wsgi_application
from django.core.handlers.wsgi import WSGIHandler
import importlib

importlib.reload(sys)

# sys.setdefaultencoding('utf-8')

os.environ.setdefault(
    "DJANGO_SETTINGS_MODULE",
    "beefun.settings")  #变量testproject.settings为django项目下的settings

django.setup()  #避免在虚拟环境下找不到django的app

application = WSGIHandler(
)  #实例化一个WSGI application用作接受nginx服务器传递的envrion、start_response参数
예제 #11
0
 def get_wsgi_handler(self):
     return StaticFilesHandler(WSGIHandler())
예제 #12
0
# absolute path to the myproject directory
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
# absolute path to myproject/src
PROJECT_SRC_PATH = os.path.join(PROJECT_PATH, PROJECT_SRC_NAME)
# absolute path to the myproject/src/apps directory
PROJECT_APPS_PATH = os.path.join(PROJECT_SRC_PATH, 'apps')
# lop off myproject name, get the environment name

os.environ['DJANGO_SETTINGS_MODULE'] = '%s.conf.settings' % PROJECT_SRC_NAME
os.environ['PYTHON_EGG_CACHE'] = '/tmp'

# check that the project module can be imported.
try:
    __import__(PROJECT_SRC_NAME)
except ImportError:
    # couldn't import the project, place it on the python path and try again.
    sys.path.insert(0, PROJECT_PATH)

    try:
        __import__(PROJECT_SRC_NAME)
    except ImportError:
        sys.stderr.write("Error: Can't import the \"%s\" project module." %
                         PROJECT_SRC_NAME)

sys.path.insert(0, PROJECT_SRC_PATH)
sys.path.insert(0, PROJECT_APPS_PATH)

# finally.. define the WSGI handler as the entry point to the application
application = Sentry(WSGIHandler())
예제 #13
0
        def inner_run():
            # Flag the server as active
            from devserver import settings
            import devserver
            settings.DEVSERVER_ACTIVE = True
            settings.DEBUG = True

            from django.conf import settings
            from django.utils import translation

            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (
                django.get_version(), settings.SETTINGS_MODULE)
            print "Running django-devserver %s" % (devserver.get_version(), )
            if use_werkzeug:
                server_type = 'werkzeug'
            else:
                server_type = 'django'
            print "%s %s server is running at http://%s:%s/" % (
                options['use_forked'] and 'Forked'
                or 'Threaded', server_type, addr, port)
            print "Quit the server with %s." % quit_command

            # django.core.management.base forces the locale to en-us. We should
            # set it up correctly for the first request (particularly important
            # in the "--noreload" case).
            translation.activate(settings.LANGUAGE_CODE)

            if int(options['verbosity']) < 1:
                app = WSGIHandler()
            else:
                app = DevServerHandler()

            if wsgi_app:
                print "Using WSGI application %r" % wsgi_app
                if os.path.exists(os.path.abspath(wsgi_app)):
                    # load from file
                    app = imp.load_source(
                        'wsgi_app', os.path.abspath(wsgi_app)).application
                else:
                    try:
                        app = __import__(wsgi_app, {}, {},
                                         ['application']).application
                    except (ImportError, AttributeError):
                        raise

            if options['use_forked']:
                mixin = SocketServer.ForkingMixIn
            else:
                mixin = SocketServer.ThreadingMixIn

            middleware = getattr(settings, 'DEVSERVER_WSGI_MIDDLEWARE', [])
            for middleware in middleware:
                module, class_name = middleware.rsplit('.', 1)
                app = getattr(__import__(module, {}, {}, [class_name]),
                              class_name)(app)

            if 'django.contrib.staticfiles' in settings.INSTALLED_APPS and use_static_files:
                from django.contrib.staticfiles.handlers import StaticFilesHandler
                app = StaticFilesHandler(app)
            else:
                app = AdminMediaHandler(app, admin_media_path)

            if options['use_dozer']:
                from dozer import Dozer
                app = Dozer(app)

            try:
                if use_werkzeug:
                    run_simple(addr,
                               int(port),
                               DebuggedApplication(app, True),
                               use_reloader=False,
                               use_debugger=True)
                else:
                    run(addr, int(port), app, mixin)
            except WSGIServerException, e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    13: "You don't have permission to access that port.",
                    98: "That port is already in use.",
                    99: "That IP address can't be assigned-to.",
                }
                try:
                    error_text = ERRORS[e.args[0].args[0]]
                except (AttributeError, KeyError):
                    error_text = str(e)
                sys.stderr.write(
                    self.style.ERROR("Error: %s" % error_text) + '\n')
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)
예제 #14
0
#-*- coding:utf-8 -*-

import os
import sys

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

path = os.path.dirname(
    os.path.abspath(__file__)) + '/Warrentech_FontCenter_Web'
if path not in sys.path:
    sys.path.insert(1, path)

from django.core.handlers.wsgi import WSGIHandler
from bae.core.wsgi import WSGIApplication

application = WSGIApplication(WSGIHandler())
예제 #15
0
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013 Dariusz Suchojad <dsuch at zato.io>

Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""

# stdlib
import os, sys
from wsgiref.simple_server import make_server

# Django
from django.core.handlers.wsgi import WSGIHandler

settings_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, settings_dir)

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

app = WSGIHandler()
make_server('127.0.0.1', 8188, app).serve_forever()
예제 #16
0
    def run(self):
        self.lock.acquire()
        pidfile = os.path.join(tempfile.gettempdir(), 'lettuce-django.pid')
        if os.path.exists(pidfile):
            pid = open(pidfile).read()
            if pid:
                pid = int(pid)
                try:
                    os.kill(pid, 9)

                except OSError:
                    pass

                finally:
                    os.unlink(pidfile)
        open(pidfile, 'w').write(str(os.getpid()))

        self.configure_mail_queue()

        connector = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        if self.threading:
            httpd_cls = type(str('WSGIServer'),
                             (socketserver.ThreadingMixIn, WSGIServer), {})
        else:
            httpd_cls = WSGIServer

        try:
            s = connector.connect((self.address, self.port))
            self.lock.release()
            os.kill(os.getpid(), 9)
        except socket.error:
            pass

        finally:
            self.lock.release()

        try:
            server_address = (self.address, self.port)
            httpd = httpd_cls(server_address, MutedRequestHandler)

        except socket.error:
            raise LettuceServerException(
                "the port %d already being used, could not start " \
                "django's builtin server on it" % self.port,
            )

        handler = WSGIHandler()
        if self.should_serve_admin_media():
            if not AdminMediaHandler:
                raise LettuceServerException(
                    "AdminMediaHandler is not available in this version of "
                    "Django. Please set LETTUCE_SERVE_ADMIN_MEDIA = False "
                    "in your Django settings.")
            admin_media_path = ''
            handler = AdminMediaHandler(handler, admin_media_path)

        if self.should_serve_static_files():
            handler = StaticFilesHandler(handler)

        httpd.set_app(handler)

        global keep_running
        while keep_running:
            call_hook('before', 'handle_request', httpd, self)
            httpd.handle_request()
            call_hook('after', 'handle_request', httpd, self)
            try:
                self.lock.release()
            except ValueError:
                pass
예제 #17
0
def make_wsgi(req):
    # twisted.web2 can not insert 'PATH_INFO' into environment.
    os.environ["PATH_INFO"] = req.path
    os.environ["SCRIPT_URL"] = req.path

    return wsgi.WSGIResource(AdminMediaHandler(WSGIHandler()))
예제 #18
0
파일: myserver.py 프로젝트: gitGNU/gnu_nutr
# web_nutrition: a web based nutrition and diet analysis program.
# Copyright (C) 2008 Edgar Denny

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from wsgiref.simple_server import make_server
from django.core.handlers.wsgi import WSGIHandler
httpd = make_server('', 8000, WSGIHandler())
httpd.serve_forever()
예제 #19
0
    def run(self):
        super(Service, self).run()

        self.amqp_tx_forwarder = AmqpTxForwarder(self.queues)
        self.amqp_rx_forwarder = AmqpRxForwarder(self.queues)

        # This thread listens to an AMQP queue and appends incoming messages
        # to queues for retransmission to agents
        tx_svc_thread = ServiceThread(self.amqp_tx_forwarder)
        # This thread listens to local queues and appends received messages
        # to an AMQP queue
        rx_svc_thread = ServiceThread(self.amqp_rx_forwarder)
        rx_svc_thread.start()
        tx_svc_thread.start()

        # FIXME: this TERMINATE_ALL format could in principle
        # be passed back from the agent (but it should never
        # originate there), affecting sessions for other agents.

        # At restart, message receiving services to clear out any
        # existing session state (from a previous instance of this
        # service).
        for plugin in ['action_runner']:
            self.queues.receive({
                'fqdn': None,
                'type': 'SESSION_TERMINATE_ALL',
                'plugin': plugin,
                'session_id': None,
                'session_seq': None,
                'body': None
            })

        # This thread services session management RPCs, so that other
        # services can explicitly request a session reset
        session_rpc_thread = ServiceThread(HttpAgentRpc(self))
        session_rpc_thread.start()

        # Hook up the request handler
        MessageView.queues = self.queues
        MessageView.sessions = self.sessions
        MessageView.hosts = self.hosts
        ValidatedClientView.valid_certs = self.valid_certs

        # The thread for generating HostOfflineAlerts
        host_checker_thread = ServiceThread(
            HostStatePoller(self.hosts, self.sessions))
        host_checker_thread.start()

        # The main thread serves incoming requests to exchanges messages
        # with agents, until it is interrupted (gevent handles signals for us)
        self.server = gevent.wsgi.WSGIServer(('', HTTP_AGENT_PORT),
                                             WSGIHandler())
        self.server.serve_forever()

        session_rpc_thread.stop()
        tx_svc_thread.stop()
        rx_svc_thread.stop()
        host_checker_thread.stop()
        session_rpc_thread.join()
        tx_svc_thread.join()
        tx_svc_thread.join()
        host_checker_thread.join()
예제 #20
0
def lambda_handler(event, context):
    """
    An AWS Lambda function which parses specific API Gateway input into a WSGI request,
    feeds it to Django, procceses the Django response, and returns that 
    back to the API Gateway.

    """

    # Django requires settings and an explicit call to setup()
    # if being used from inside a python context.
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zappa_settings")
    import django
    django.setup()
    from django.conf import settings

    # This is a normal HTTP request
    if event.get('method', None):

        # If we just want to inspect this,
        # return this event instead of processing the request
        # https://your_api.aws-api.com/?event_echo=true
        event_echo = getattr(settings, "EVENT_ECHO", True)
        if event_echo:
            if 'event_echo' in event['params'].values():
                return {
                    'Content': str(event) + '\n' + str(context),
                    'Status': 200
                }

        # This doesn't matter, but Django's handler requires it.
        def start(a, b):
            return

        # Create the environment for WSGI and handle the request
        environ = create_wsgi_request(event, script_name=settings.SCRIPT_NAME)
        handler = WSGIHandler()
        response = handler(environ, start)

        # Prepare the special dictionary which will be returned to the API GW.
        returnme = {'Content': response.content}

        # Pack the WSGI response into our special dictionary.
        for item in response.items():
            returnme[item[0]] = item[1]
        returnme['Status'] = response.status_code

        # Parse the WSGI Cookie and pack it.
        cookie = response.cookies.output()
        if ': ' in cookie:
            returnme['Set-Cookie'] = response.cookies.output().split(': ')[1]

        # To ensure correct status codes, we need to
        # pack the response as a deterministic B64 string and raise it
        # as an error to match our APIGW regex.
        # The DOCTYPE ensures that the page still renders in the browser.
        if response.status_code in [400, 401, 403, 500]:
            content = response.content
            content = "<!DOCTYPE html>" + str(
                response.status_code) + response.content
            b64_content = base64.b64encode(content)
            raise Exception(b64_content)
        # Internal are changed to become relative redirects
        # so they still work for apps on raw APIGW and on a domain.
        elif response.status_code in [301, 302]:
            location = returnme['Location']
            location = '/' + location.replace("http://zappa/", "")
            raise Exception(location)
        else:
            return returnme

    # This is a management command invocation.
    elif event.get('command', None):
        from django.core import management

        # Couldn't figure out how to get the value into stdout with StringIO..
        # Read the log for now. :[]
        management.call_command(*event['command'].split(' '))
        return {}
예제 #21
0
import sys, os
sys.path.append(os.getcwd())
sys.path.append(os.getcwd() + '/huxley')

INTERP = os.path.join(os.getcwd(), 'env/bin/python')

if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)

sys.path.insert(0, os.path.join(os.getcwd(), 'env/bin'))
sys.path.insert(
    0, os.path.join(os.getcwd(), 'env/lib/python2.7/site-packages/django'))
sys.path.insert(0, os.path.join(os.getcwd(),
                                'env/lib/python2.7/site-packages'))

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

import django
django.setup()

from django.core.handlers.wsgi import WSGIHandler
from paste.exceptions.errormiddleware import ErrorMiddleware
application = ErrorMiddleware(WSGIHandler(), debug=True)
예제 #22
0
 def test_middleware_initialized(self):
     handler = WSGIHandler()
     self.assertIsNotNone(handler._middleware_chain)
예제 #23
0
    def start_server_servestatic(self, options):
        """
        Start CherryPy server AND serve default static files

        Want SSL support?
        a. The new (3.1 or 3.2) way: Just set server.ssl_adapter to an SSLAdapter instance.
        b. The old way (deprecated way) is to set these attributes:

           server.ssl_certificate = <filename>
           server.ssl_private_key = <filename>

           But this is the only way from the management command line
           in the future I may need to adapt this to use a server.ssl_adapter

        """
        # debug?
        # print "options:"
        from django.conf import settings
        quit_command = (sys.platform
                        == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'

        self.stdout.write("Validating models..")
        self.validate(display_num_errors=True)
        self.stdout.write(
            ("%(started_at)s\n"
             "Django version %(version)s, using settings %(settings)r\n"
             "cherrypy django_wsgiserver is running at http://%(addr)s:%(port)s/\n"
             "Quit the server with %(quit_command)s.\n") %
            {
                "started_at": datetime.now().strftime('%B %d, %Y - %X'),
                "version": self.get_version(),
                "settings": settings.SETTINGS_MODULE,
                "addr": options[
                    'host'],  # self._raw_ipv6 and '[%s]' % self.addr or self.addr,
                "port": options['port'],
                "quit_command": quit_command,
            })

        #logger.info("launching wsgiserver with the following options")
        #logger.info(pformat(options))
        if int(options['verbose']) >= 2:
            self.stdout.write("launching with the following options:\n")
            self.stdout.write(pformat(options))

        if options['daemonize'] and options['server_user'] and options[
                'server_group']:
            #ensure the that the daemon runs as specified user
            change_uid_gid(options['server_user'], options['server_group'])

        from django_wsgiserver.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher
        #from cherrypy.wsgiserver import CherryPyWSGIServer, WSGIPathInfoDispatcher

        from django.core.handlers.wsgi import WSGIHandler
        from django.conf import settings
        app = WSGIHandler()  # serve the django content
        path = {
            '/': app
        }  # well will build up the serving url routing path below

        # Now work on serving the static content
        # note as of django 1.4, ADMIN_MEDIA_PREFIX is depreciated and instead uses django.contrib.staticfiles
        # so it is not an error for ADMIN_MEDIA_PREFIX to not be defined, I will test to see if exists
        # and print a warning that adminserve is activated but it's not defined.
        # so for django 1.4 (or 1.5 ?) staticserve=True => adminserve=True
        # so the choices
        # There are basically two ways for statics to be served
        # 1. in development, one often wants each application's static files to be served from within its file structure
        #    this is what the django runserver dose
        # 2. in production usually, all the static files are collected into a common storage region (files, S3, CDN) and a good webserver
        #    serve them from there

        # deprecated
        # if options['adminserve']: # serve the admin media too
        #     # AdminMediaHandler is middleware for local use
        #     #import django.core.servers.basehttp
        #     #adminapp = django.core.servers.basehttp.AdminMediaHandler(app)
        #     # another way to serve the admin media three application
        #     if settings.__dict__.has_key('ADMIN_MEDIA_PREFIX'):
        #         import django.contrib.admin

        #         path[settings.ADMIN_MEDIA_PREFIX] = django_wsgiserver.mediahandler.StaticFileWSGIApplication(
        #             os.path.join( django.contrib.admin.__path__[0], 'media'))
        #     else:
        #         print "Warning adminserve was selected BUT ADMIN_MEDIA_PREFIX was not defined"

        if options['staticserve']:
            try:
                if not settings.STATIC_URL or not settings.STATIC_ROOT:
                    # could use misconfigured exception (what is this in django)  instead of AttributeError
                    raise AttributeError, "settings.STATIC_URL = %s, settings.STATIC_ROOT=%s" % (
                        repr(settings.STATIC_URL), repr(settings.STATIC_ROOT))
            except AttributeError, msg:
                logger.error(msg)
                logger.error("****")
                logger.error(
                    "STATIC_URL and STATIC_ROOT  must be set in settings file for staticserve option to work in django_wsgiserver"
                )
                logger.error("****")
                raise

            if options['staticserve'] != 'collectstatic':
                if settings.STATICFILES_FINDERS:  # find the apps' static files and add them to the path
                    logger.debug("see settings.STATICFILES_FINDERS")
                    logger.debug(pformat(settings.STATICFILES_FINDERS))
                    from django.contrib.staticfiles.finders import AppDirectoriesFinder
                    app_static_finder = AppDirectoriesFinder(
                        settings.INSTALLED_APPS)
                    logger.debug("app_static_finder.storages:")
                    logger.debug(pformat(app_static_finder.storages))
                    for key, val in app_static_finder.storages.items():
                        logger.debug(key, " static location:", val.location)
                        # need to decide what to do with this in terms of the fusion of the app static directories
                        app_url = key.split('.')[
                            -1] + r'/'  # I'm not sure if it needs the end '/'
                        full_static_url = os.path.join(settings.STATIC_URL,
                                                       app_url)
                        full_dir_location = os.path.join(val.location, app_url)
                        logger.debug(full_static_url, full_dir_location)
                        path[
                            full_static_url] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(
                                full_dir_location)

            if options['servestaticdirs'] and hasattr(settings,
                                                      'STATICFILES_DIRS'):
                staticlocations = process_staticfiles_dirs(
                    settings.STATICFILES_DIRS)
                # debug !!!
                logger.debug("staticlocations::")
                logger.debug(pformat(staticlocations))
                for urlprefix, root in staticlocations:
                    path[os.path.join(
                        settings.STATIC_URL, urlprefix
                    )] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(
                        root)

            # One important thing is that there are two different ways to serve the static files
            # 1. convenient: serve each app's static files (assuming they follow convention)
            # 2. do a collectstatic and serve from that node -- likely this would be done more in a "production" scenario

            if options['staticserve'] == 'collectstatic':
                # and serve the root of the STATIC_URL ? hmm !!!
                path[
                    settings.
                    STATIC_URL] = django_wsgiserver.wsgiutil.StaticFileWSGIApplication(
                        settings.STATIC_ROOT)
                logger.warning(
                    "serving all static files from %s. *** Make sure you have done a fresh collectstatic operation ***"
                    % settings.STATIC_ROOT)
예제 #24
0
파일: wsgi.py 프로젝트: triicst/JMS
def get_wsgi_application():
    django.setup()
    return WSGIHandler()
예제 #25
0
#-*- coding:utf-8 -*-

import os
import sys

path = os.path.dirname(os.path.abspath(__file__)).replace('\\',
                                                          '/') + '/urlhandler'
if path not in sys.path:
    sys.path.insert(1, path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "urlhandler.settings")

from django.core.handlers.wsgi import WSGIHandler

django_WSGI = WSGIHandler()

from queryhandler import handle_weixin_request
from settings import LUCKY_URL
from queryhandler.settings import SITE_DOMAIN, SITE_HTTP_PROTOCOL


def app(environ, start_response):
    update_site_domain(environ.get('HTTP_HOST', ''))
    if environ.get('PATH_INFO', '') == LUCKY_URL:
        result = handle_weixin_request(environ)
        status = '200 OK'
        headers = [('Content-type', 'text/html')]
        start_response(status, headers)
        #print result
        return [result.encode('utf8')]
    else:
        #status = '200 OK'
예제 #26
0
 def get_wsgi_handler(self):
     return DjangoWsgiFix(StaticFilesHandler(WSGIHandler()))
예제 #27
0
파일: runhttp.py 프로젝트: kabirh/riotvine
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            '--numthreads',
            dest='numthreads',
            default='30',
            help=
            'Specifies the number of worker threads to create. Defaults to 30 threads.'
        ),
        make_option('--daemonize',
                    dest='daemonize',
                    action='store_true',
                    help='Runs the Web server in the background.'),
        make_option(
            '--workdir',
            dest='workdir',
            default='.',
            help=
            'Work directory to change to before daemonizing. Defaults to the current directory.'
        ),
        make_option('--pidfile',
                    dest='pidfile',
                    default='',
                    help='Specifies the file in which to write the PID.'),
        make_option(
            '--urlpath',
            dest='urlpath',
            default='/',
            help=
            'Specifies the URL path prefix to which the Web server responds. Defaults to /'
        ),
        make_option(
            '--servername',
            dest='servername',
            help=
            "The string to set for WSGI's SERVER_NAME environment variable."),
    )
    help = """Runs the Django application under CherryPy's production quality Web server.

Requires CherryPy WSGIServer.

WARNING: This DOES NOT serve static media files.
"""
    args = '[optional port number, or ipaddr:port (defaults to 127.0.0.1:8000)]'

    def handle(self, addrport='', *args, **options):
        import django
        from django.core.handlers.wsgi import WSGIHandler
        if args:
            raise CommandError('Usage is runhttp %s' % self.args)
        if not addrport:
            addr = ''
            port = '8000'
        else:
            try:
                addr, port = addrport.split(':')
            except ValueError:
                addr, port = '', addrport
        if not addr:
            addr = '127.0.0.1'

        if not port.isdigit():
            raise CommandError("%r is not a valid port number." % port)

        numthreads = options.get('numthreads', '30')
        if not numthreads.isdigit():
            raise CommandError("%r is not a valid value for numthreads." %
                               numthreads)

        port = int(port)
        numthreads = int(numthreads)

        print "Starting %s threads" % numthreads

        try:
            from cherrypy.wsgiserver import CherryPyWSGIServer
            from cherrypy.wsgiserver import WSGIPathInfoDispatcher
        except ImportError:
            try:
                from wsgiserver import CherryPyWSGIServer
                from wsgiserver import WSGIPathInfoDispatcher
            except ImportError, e:
                print >> sys.stderr, "ERROR: %s" % e
                print >> sys.stderr, "  Unable to load the wsgiserver package.  In order to run django's"
                print >> sys.stderr, "  high-performance web server, you will need to get wsgiserver from"
                print >> sys.stderr, "  http://svn.cherrypy.org/trunk/cherrypy/"
                print >> sys.stderr, "  Only the wsgiserver directory and its contents are required."
                print >> sys.stderr, "  If you've already installed wsgiserver, "
                print >> sys.stderr, "  make sure it is in your PYTHONPATH."
                return False

        #print "Validating models..."
        self.validate(display_num_errors=False)

        wsgi_apps = WSGIPathInfoDispatcher([(options.get('urlpath',
                                                         '/'), WSGIHandler())])
        server = CherryPyWSGIServer(
            (addr, port),
            wsgi_apps,
            numthreads=numthreads,
            server_name=options.get('servername', None))

        daemonize = options.get('daemonize', False)

        if daemonize:
            from django.utils.daemonize import become_daemon
            workdir = options.get('workdir', '.')
            become_daemon(our_home_dir=workdir)
        else:
            print "HTTP server started on %s:%s" % (addr, port)
            print "Press Ctrl-C to stop the server."

        if options.get("pidfile", False):
            fp = open(options["pidfile"], "w")
            fp.write("%d\n" % os.getpid())
            fp.close()

        try:
            server.start()
        except (KeyboardInterrupt, SystemExit):
            server.stop()
예제 #28
0
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)
예제 #29
0
    def Run(self):
        # Import modules
        from cheroot import wsgi
        from subprocess import call, DEVNULL
        from win32process import DETACHED_PROCESS, CREATE_NO_WINDOW

        # Initialize django
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "freppledb.settings")
        os.environ.setdefault("FREPPLE_APP",
                              os.path.join(sys.path[0], "custom"))
        import django

        django.setup()
        from django.conf import settings
        from django.core.handlers.wsgi import WSGIHandler
        from django.contrib.staticfiles.handlers import StaticFilesHandler

        # Override the debugging settings
        settings.DEBUG = False
        settings.TEMPLATE_DEBUG = False

        # Sys.path contains the zip file with all packages. We need to put the
        # application directory into the path as well.
        sys.path += [os.environ["FREPPLE_APP"]]

        # Append all output to a unbuffered log stream
        with open(os.path.join(settings.FREPPLE_LOGDIR, "service.log"),
                  "a") as logfile:
            sys.stderr = sys.stdout = logfile
            try:
                # Using the included postgres database
                # Check if the database is running. If not, start it.
                if os.path.exists(
                        os.path.join(settings.FREPPLE_HOME, "..", "pgsql",
                                     "bin", "pg_ctl.exe")):
                    status = call(
                        [
                            os.path.join(
                                settings.FREPPLE_HOME,
                                "..",
                                "pgsql",
                                "bin",
                                "pg_ctl.exe",
                            ),
                            "--pgdata",
                            os.path.join(settings.FREPPLE_LOGDIR, "database"),
                            "--silent",
                            "status",
                        ],
                        stdin=DEVNULL,
                        stdout=DEVNULL,
                        stderr=DEVNULL,
                        creationflags=CREATE_NO_WINDOW,
                    )
                    if status:
                        print(
                            "%s\tStarting the PostgreSQL database" %
                            datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            flush=True,
                        )
                        call(
                            [
                                os.path.join(
                                    settings.FREPPLE_HOME,
                                    "..",
                                    "pgsql",
                                    "bin",
                                    "pg_ctl.exe",
                                ),
                                "--pgdata",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             "database"),
                                "--log",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             "database", "server.log"),
                                "start",
                            ],
                            stdin=DEVNULL,
                            stdout=DEVNULL,
                            stderr=DEVNULL,
                            creationflags=DETACHED_PROCESS,
                        )

                # Prepare web server
                self.server = wsgi.Server((settings.ADDRESS, settings.PORT),
                                          StaticFilesHandler(WSGIHandler()))

                # Synchronize the scenario table with the settings
                from freppledb.common.models import Scenario

                Scenario.syncWithSettings()

                # Infinite loop serving requests
                # The loop gets interrupted when the service gets ordered to shut down.
                print(
                    "%s\tfrePPLe web server listening on http://%s:%d" % (
                        datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        settings.ADDRESS,
                        settings.PORT,
                    ),
                    flush=True,
                )
                self.server.start()
                print(
                    "%s\tStopping service" %
                    datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    flush=True,
                )

                # Using the included postgres database?
                if os.path.exists(
                        os.path.join(settings.FREPPLE_HOME, "..", "pgsql",
                                     "bin", "pg_ctl.exe")):
                    # Check if the database is running. If so, stop it.
                    os.environ["PATH"] = (os.path.join(settings.FREPPLE_HOME,
                                                       "..", "pgsql", "bin") +
                                          os.pathsep + os.environ["PATH"])
                    status = call(
                        [
                            os.path.join(
                                settings.FREPPLE_HOME,
                                "..",
                                "pgsql",
                                "bin",
                                "pg_ctl.exe",
                            ),
                            "--pgdata",
                            os.path.join(settings.FREPPLE_LOGDIR, "database"),
                            "--silent",
                            "status",
                        ],
                        stdin=DEVNULL,
                        stdout=DEVNULL,
                        stderr=DEVNULL,
                        creationflags=CREATE_NO_WINDOW,
                    )
                    if not status:
                        print(
                            "%s\tShutting down the database" %
                            datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                            flush=True,
                        )
                        call(
                            [
                                os.path.join(
                                    settings.FREPPLE_HOME,
                                    "..",
                                    "pgsql",
                                    "bin",
                                    "pg_ctl.exe",
                                ),
                                "--pgdata",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             "database"),
                                "--log",
                                os.path.join(settings.FREPPLE_LOGDIR,
                                             "database", "server.log"),
                                "-w",  # Wait till it's down
                                "stop",
                            ],
                            stdin=DEVNULL,
                            stdout=DEVNULL,
                            stderr=DEVNULL,
                            creationflags=CREATE_NO_WINDOW,
                        )

                # Notify the manager
                self.stopEvent.set()

            except Exception as e:
                print(
                    "%s\tfrePPLe web server failure: %s" %
                    (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), e),
                    flush=True,
                )
예제 #30
0
def runwsgi():
    sys.path.append('/var/app/weibonews/enabled/wechat/')
    sys.path.append('/var/app/weibonews/enabled/wechat/wechat')
    os.environ['DJANGO_SETTINGS_MODULE'] = 'wechat.settings'
    got_request_exception.connect(exception_printer)
    WSGIServer(('', 8088), WSGIHandler()).serve_forever()
예제 #31
0
 def __init__(self):
     self.app = WSGIHandler()
     self.factory = DjangoRequestFactory()
예제 #32
0
 def _twill_setup():
     app = StaticFilesHandler(WSGIHandler())
     twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)
예제 #33
0
"""
Alternative WSGI entry-point that uses requirements/vendor for
dependencies.

"""
import os
import sys

base_dir = os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, base_dir)

from moztrap.deploy.paths import add_vendor_lib
add_vendor_lib()

# Set default settings and instantiate application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "moztrap.settings.default")

from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
예제 #34
0
def json_serve_thread():
  from wsgiref.simple_server import make_server
  from django.core.handlers.wsgi import WSGIHandler
  http = make_server('', 8999, WSGIHandler())
  http.serve_forever()
예제 #35
0
sys.path.append("mydjangosite")
os.environ['DJANGO_SETTINGS_MODULE'] = 'mydjangosite.settings'
from django.core.handlers.wsgi import WSGIHandler

# Twisted Application Framework setup:
application = service.Application('twisted-django')

# WSGI container for Django, combine it with twisted.web.Resource:
# XXX this is the only 'ugly' part: see the 'getChild' method in twresource.Root
# The MultiService allows to start Django and Twisted server as a daemon.

multi = service.MultiService()
pool = threadpool.ThreadPool()
tps = ThreadPoolService(pool)
tps.setServiceParent(multi)
resource = wsgi.WSGIResource(reactor, tps.pool, WSGIHandler())
root = twresource.Root(resource)

# Servce Django media files off of /media:
mediasrc = static.File(os.path.join(os.path.abspath("."),
                                    "mydjangosite/media"))
staticsrc = static.File(
    os.path.join(os.path.abspath("."), "mydjangosite/static"))
root.putChild("media", mediasrc)
root.putChild("static", staticsrc)

# The cool part! Add in pure Twisted Web Resouce in the mix
# This 'pure twisted' code could be using twisted's XMPP functionality, etc:
root.putChild("google", twresource.GoogleResource())

# Serve it up:
예제 #36
0
    def get_app(self):
        from django.contrib.staticfiles.handlers import StaticFilesHandler
        from django.core.handlers.wsgi import WSGIHandler

        app = StaticFilesHandler(WSGIHandler())
        return app
예제 #37
0
    def handle(self, **options):
        # Determine the port number
        if 'port' in options:
            port = int(options['port'] or settings.PORT)
        else:
            port = settings.PORT

        # Determine the number of threads
        if 'threads' in options:
            threads = int(options['threads'] or 25)
            if threads < 1:
                raise Exception("Invalid number of threads: %s" % threads)
        else:
            threads = 25

        # Determine the IP-address to listen on:
        # - either as command line argument
        # - either 0.0.0.0 by default, which means all active IPv4 interfaces
        address = 'address' in options and options['address'] or '0.0.0.0'

        # Validate the address and port number
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((address, port))
            s.close()
        except socket.error as e:
            raise Exception("Invalid address '%s' and/or port '%s': %s" %
                            (address, port, e))

        # Print a header message
        hostname = socket.getfqdn()
        print('Starting frePPLe %s web server\n' % VERSION)
        print(
            'To access the server, point your browser to either of the following URLS:'
        )
        if address == '0.0.0.0':
            print('    http://%s:%s/' % (hostname, port))
            for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
                print('    http://%s:%s/' % (ip, port))
        else:
            print('    http://%s:%s/' % (address, port))
        print(
            '\nThree users are created by default: "admin", "frepple" and "guest" (the default password is equal to the user name)\n'
        )
        print('Quit the server with CTRL-C.\n')

        # Start a separate thread that will check for updates
        # We don't wait for it to finish
        CheckUpdates().start()

        # Run the WSGI server
        server = CherryPyWSGIServer((address, port),
                                    StaticFilesHandler(WSGIHandler()),
                                    numthreads=threads)
        # Want SSL support? Just set these attributes apparently, but I haven't tested or verified this
        #  server.ssl_certificate = <filename>
        #  server.ssl_private_key = <filename>
        try:
            server.start()
        except KeyboardInterrupt:
            server.stop()
예제 #38
0
def start():
    #NOTE bots is always on PYTHONPATH!!! - otherwise it will not start.
    #********command line arguments**************************
    configdir = 'config'
    for arg in sys.argv[1:]:
        if not arg:
            continue
        if arg.startswith('-c'):
            configdir = arg[2:]
            if not configdir:
                print 'Configuration directory indicated, but no directory name.'
                sys.exit(1)
        elif arg in ["?", "/?"] or arg.startswith('-'):
            showusage()
        else:
            showusage()
    
    #init general: find locating of bots, configfiles, init paths etc.***********************
    botsinit.generalinit(configdir)

    #init cherrypy; only needed for webserver. *********************************************
    cherrypy.config.update({'global': { 'tools.staticdir.root': botsglobal.ini.get('directories','botspath'),
                                        'server.socket_host' : "0.0.0.0",       #to what IP addresses should be server. 0.0.0.0: all. See cherrypy docs
                                        'server.socket_port': botsglobal.ini.getint('webserver','port',8080),
                                        'server.environment': botsglobal.ini.get('webserver','environment','development'),    # development production
                                        'log.screen': False,
                                        #~ 'log.error_file': '',    #set later to rotating log file
                                        #~ 'log.access_file': '',    #set later to rotating log file
                                        }})
    conf = {'/': {'tools.staticdir.on' : True,'tools.staticdir.dir' : 'media' }}
            #~ '/favicon.ico': {'tools.staticfile.on': True,'tools.staticfile.filename': '/home/hje/botsup-django/bots/media/images/favicon.ico'}}
    cherrypy.tree.graft(AdminMediaHandler(WSGIHandler()), '/')
    myroot = Root()
    myappl = cherrypy.tree.mount(myroot, '/media', conf)    #myappl is needed to set logging 



    botsglobal.logger = logging.getLogger('webserver')
    botsglobal.logger.setLevel(logging.DEBUG)
    h = logging.handlers.TimedRotatingFileHandler(botslib.join(botsglobal.ini.get('directories','logging'),'webserver.log'),when='midnight', backupCount=10)
    fileformat = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s : %(message)s",'%Y%m%d %H:%M:%S')
    h.setFormatter(fileformat)
    # add rotating file handler to main logger
    botsglobal.logger.addHandler(h)
    



    # Make RotatingFileHandler for the error log.
    #~ h = logging.handlers.TimedRotatingFileHandler(botslib.join(botsglobal.ini.get('directories','logging'),'webserver.log'),when='midnight', backupCount=10)
    #~ fileformat = logging.Formatter("%(asctime)s %(levelname)-8s %(name)s : %(message)s",'%Y%m%d %H:%M:%S')
    #~ h.setLevel(logging.INFO)
    #~ h.setFormatter(fileformat)
    #~ myappl.log.error_log.addHandler(h)

    # MakeRotatingFileHandler for the access log.
    #~ h = logging.handlers.TimedRotatingFileHandler(os.path.normpath(os.path.join(botsglobal.ini.get('directories','botspath'), 'botssys/logging/webserver.log')),when='midnight', backupCount=10)
    #~ h.setLevel(logging.DEBUG)
    #~ myappl.log.access_log.addHandler(h)
    #~ botsglobal.logger = myappl.log.access_log 
    
    #write start info to cherrypy log********************************************
    botsglobal.logger.info(_(u'Bots web server started.'))
    botsglobal.logger.info(_(u'Python version: "%s".'),sys.version)
    botsglobal.logger.info(_(u'Django version: "%s".'),django.VERSION)
    
    #start cherrypy *********************************************************************
    cherrypy.engine.start()
    cherrypy.engine.block()
예제 #39
0
    def __init__(self):
        WSGIHandler.__init__(self)

        import settings as cust_settings

        settings.configure(cust_settings)
예제 #40
0
    def run(self, parameters):
        #cherrypy.engine.unsubscribe('graceful', cherrypy.log.reopen_files)

        logging.config.dictConfig(OmniDB.settings.LOGGING)
        #cherrypy.log.error_log.propagate = False
        cherrypy.log.access_log.propagate = False
        self.mount_static(OmniDB.settings.STATIC_URL,
                          OmniDB.settings.STATIC_ROOT)

        cherrypy.tree.graft(WSGIHandler())

        port = parameters['listening_port']
        num_attempts = 0

        print('''Starting OmniDB server...''', flush=True)
        logger.info('''Starting OmniDB server...''')
        print('''Checking port availability...''', flush=True)
        logger.info('''Checking port availability...''')

        while not check_port(port) or num_attempts >= 20:
            print("Port {0} is busy, trying another port...".format(port),
                  flush=True)
            logger.info(
                "Port {0} is busy, trying another port...".format(port))
            port = random.randint(1025, 32676)
            num_attempts = num_attempts + 1

        if num_attempts < 20:

            v_cherrypy_config = {
                'server.socket_host': parameters['listening_address'],
                'server.socket_port': port,
                'engine.autoreload_on': False,
                'log.screen': False,
                'log.access_file': '',
                'log.error_file': ''
            }

            if parameters['is_ssl']:
                import ssl
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.options |= ssl.OP_NO_TLSv1
                ssl_ctx.options |= ssl.OP_NO_TLSv1_1
                ssl_ctx.load_cert_chain(parameters['ssl_certificate_file'],
                                        parameters['ssl_key_file'])
                v_cherrypy_config['server.ssl_module'] = 'builtin'
                v_cherrypy_config['server.ssl_certificate'] = parameters[
                    'ssl_certificate_file']
                v_cherrypy_config['server.ssl_private_key'] = parameters[
                    'ssl_key_file']
                v_cherrypy_config['server.ssl_context'] = ssl_ctx

            cherrypy.config.update(v_cherrypy_config)

            print("Starting server {0} at {1}:{2}{3}.".format(
                OmniDB.settings.OMNIDB_VERSION,
                parameters['listening_address'], str(port),
                OmniDB.settings.PATH),
                  flush=True)
            logger.info("Starting server {0} at {1}:{2}.".format(
                OmniDB.settings.OMNIDB_VERSION,
                parameters['listening_address'], str(port)))

            # Startup
            startup.startup_procedure()

            cherrypy.engine.start()

            if not app_version:
                print("Open OmniDB in your favorite browser", flush=True)
                if platform.system() != 'Windows':
                    print("Press Ctrl+C to exit", flush=True)
            else:
                #Sending response to electron app
                print(
                    "http://localhost:{0}/login/?user=admin&pwd=admin&token={1}"
                    .format(str(port), OmniDB.custom_settings.APP_TOKEN),
                    flush=True)

            cherrypy.engine.block()
            cherrypy.engine.exit()
        else:
            print('Tried 20 different ports without success, closing...',
                  flush=True)
            logger.info('Tried 20 different ports without success, closing...')
예제 #41
0
def benchmark_request(middleware_classes):
    settings.MIDDLEWARE_CLASSES = middleware_classes
    req_factory = RequestFactory()
    handler = WSGIHandler()
    handler.load_middleware()
    handler.get_response(req_factory.get('/'))
예제 #42
0
파일: server.py 프로젝트: eveiga/cdmaker
import os
from wsgiref.simple_server import make_server
from django.core.handlers.wsgi import WSGIHandler
from django.core.servers.basehttp import AdminMediaHandler

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

httpd = make_server('', 8000, AdminMediaHandler(WSGIHandler()))
httpd.serve_forever()