예제 #1
0
파일: serving.py 프로젝트: Glottotopia/aagd
def run_server(hostname='localhost', port=8080,
               docs=True,
               debug='off',
               user=None, group=None,
               threaded=True,
               **kw):
    """ Run a standalone server on specified host/port. """
    application = make_application(shared=docs)

    if port < 1024:
        if os.name == 'posix' and os.getuid() != 0:
            raise RuntimeError('Must run as root to serve port number under 1024. '
                               'Run as root or change port setting.')

    if user:
        switch_user(user, group)

    if debug == 'external':
        # no threading is better for debugging, the main (and only)
        # thread then will just terminate when an exception happens
        threaded = False

    run_simple(hostname=hostname, port=port,
               application=application,
               threaded=threaded,
               use_debugger=(debug == 'web'),
               passthrough_errors=(debug == 'external'),
               request_handler=RequestHandler,
               **kw)
예제 #2
0
def main():
    app = Main(debug=True)
    bind_address = "127.0.0.1"
    port = 5000
    run_simple(
        bind_address, port, app, use_debugger=True, use_reloader=True
    )
예제 #3
0
파일: __init__.py 프로젝트: Readon/cydra
def standalone_serve():
    """Standalone WSGI Server for debugging purposes"""
    from werkzeug import run_simple
    import logging
    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False)
    (options, args) = parser.parse_args()

    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.ERROR)

    port = 8080
    if len(args) > 0:
        port = int(args[0])

    app = create_application()

    #from werkzeugprofiler import ProfilerMiddleware
    #app = ProfilerMiddleware(app, stream=open('profile_stats.txt', 'w'), accum_count=100, sort_by=('cumulative', 'calls'), restrictions=(.1,))

    run_simple('0.0.0.0', port, app, use_reloader=True,
            use_debugger=True, #use_evalex=True,
            )
예제 #4
0
def main():
    wsgihandler = getwsgihandler(debug=True)
    bind_address = "127.0.0.1"
    port = 5000
    werkzeug.run_simple(
        bind_address, port, wsgihandler, use_debugger=True, use_reloader=True
    )
예제 #5
0
 def inner_run():
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = options.get('admin_media_path', '')
     if not path:
         admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
         if os.path.isdir(admin_media_path):
             path = admin_media_path
         else:
             path = os.path.join(django.__path__[0], 'contrib/admin/media')
     handler = WSGIHandler()
     if USE_ADMINMEDIAHANDLER:
         handler = AdminMediaHandler(handler, path)
     if USE_STATICFILES:
         use_static_handler = options.get('use_static_handler', True)
         insecure_serving = options.get('insecure_serving', False)
         if use_static_handler and (settings.DEBUG or insecure_serving):
             handler = StaticFilesHandler(handler)
     if open_browser:
         import webbrowser
         url = "http://%s:%s/" % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler, True),
                use_reloader=use_reloader, use_debugger=True, threaded=threaded)
예제 #6
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(),)
            print "Development server is running at http://%s:%s/" % (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:
                base_handler = WSGIHandler
            else:
                base_handler = DevServerHandler

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

            try:
                handler = AdminMediaHandler(base_handler(), admin_media_path)
                if use_werkzeug:
                    run_simple(
                        addr,
                        int(port),
                        DebuggedApplication(handler, True),
                        use_reloader=use_reloader,
                        use_debugger=True,
                    )
                else:
                    run(addr, int(port), handler, 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)
예제 #7
0
def profile_run():
    from werkzeug import run_simple
    from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
    print "* Profiling"
    f = open('./profiler.log', 'w')
    profiled_app = ProfilerMiddleware(app, MergeStream(sys.stderr, f))
    run_simple('localhost', 5000, profiled_app,
        use_reloader=True, use_debugger=True)
예제 #8
0
파일: rdebug.py 프로젝트: amitu/dutils
 def handle(self, **options):
     if import_excpetion:
         print "Get werkzeug module form http://werkzeug.pocoo.org/download"
         raise SystemExit
     run_simple(
         options["ip"], int(options["port"]), 
         DebuggedApplication(WSGIHandler(), True)
     )
예제 #9
0
def development_server():
    app_path = os.path.basename(__file__)

    werkzeug.run_simple('', 8000,
        util.wrap_static(application, app_path,
            index='wakaba.html',
            not_found_handler=app.not_found),
        use_reloader=True, use_debugger=config.DEBUG)
예제 #10
0
파일: tubes.py 프로젝트: mcaudy/tubes
def run(handler, host='0.0.0.0', port=8000, use_reloader=False,
        use_debugger=False, use_evalex=True, extra_files=None,
        reloader_interval=1, threaded=False, processes=1, request_handler=None,
        passthrough_errors=False):
    '''create a server instance and run it'''
    werkzeug.run_simple(host, port, handler, use_reloader, use_debugger,
            use_evalex, extra_files, reloader_interval, threaded, processes,
            request_handler, handler.static_paths, passthrough_errors)
예제 #11
0
def main():
    logging.basicConfig(level=logging.INFO)
    import yaml

    config = yaml.load(open("config.yaml", "r"))
    app = RESTfulWebService(config)
    from werkzeug import run_simple

    run_simple(config.get("server", "140.134.26.21"), config.get("port", 7788), app)
예제 #12
0
파일: debugger.py 프로젝트: areski/cwf
 def run(self):
     """Start the debugger"""
     def setup_func():
         self.setup_500()
         self.setup_path(self.project)
     app = self.setup_app()
     run_simple(self.host, self.port, app
         , use_debugger=True, use_reloader=True, setup_func=setup_func
         )
예제 #13
0
def profile_run():
    print "* Profiling"
    f = open('./profiler.log', 'w')
    profiled_app = ProfilerMiddleware(app, MergeStream(sys.stderr, f))
    run_simple(app.config['SERVER_LISTEN'],
               app.config['SERVER_PORT'],
               profiled_app,
               use_reloader=app.config['DEBUG'],
               use_debugger=app.config['DEBUG'])
예제 #14
0
def debug(host='0.0.0.0', port=8976):
    """ """
    # This is only needed for Django versions < [7537]:
    def null_technical_500_response(request, exc_type, exc_value, tb):
        raise exc_type, exc_value, tb
    from django.views import debug
    debug.technical_500_response = null_technical_500_response

    os.environ['DJANGO_SETTINGS_MODULE'] = 'agenda.production'

    run_simple(host, port, DebuggedApplication(WSGIHandler(), True))
예제 #15
0
 def inner_run():
     from django.conf import settings
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = admin_media_path or django.__path__[0] + '/contrib/admin/media'
     handler = AdminMediaHandler(WSGIHandler(), path)
     run_simple(addr, int(port), DebuggedApplication(handler, True), 
                use_reloader=use_reloader, use_debugger=True)            
예제 #16
0
파일: app.py 프로젝트: cloudappsetup/kalapy
def simple_server(host='127.0.0.1', port=8080, use_reloader=False):
    """Run a simple server for development purpose.

    :param host: host name
    :param post: port number
    :param use_reloader: whether to reload the server if any of the loaded
                         module changed.
    """
    from werkzeug import run_simple
    # create a wsgi application
    app = Application()
    run_simple(host, port, app, use_reloader=use_reloader, use_debugger=app.debug)
예제 #17
0
        def inner_run():
            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
            print "Development server is running at http://%s:%s/" % (addr, port)
            print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
            print "Quit the server with %s." % quit_command
            path = options.get('admin_media_path', '')
            if not path:
                admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
                if os.path.isdir(admin_media_path):
                    path = admin_media_path
                else:
                    path = os.path.join(django.__path__[0], 'contrib/admin/media')
            handler = WSGIHandler()
            if USE_ADMINMEDIAHANDLER:
                handler = AdminMediaHandler(handler, path)
            if USE_STATICFILES:
                use_static_handler = options.get('use_static_handler', True)
                insecure_serving = options.get('insecure_serving', False)
                if use_static_handler and (settings.DEBUG or insecure_serving):
                    handler = StaticFilesHandler(handler)
            if open_browser:
                import webbrowser
                url = "http://%s:%s/" % (addr, port)
                webbrowser.open(url)
            if cert_path:
                try:
                    from werkzeug.serving import make_ssl_devcert
                    ssl_context = make_ssl_devcert(cert_path, host='localhost')
                    run_simple(
                        addr,
                        int(port),
                        DebuggedApplication(handler, True),
                        use_reloader=use_reloader,
                        use_debugger=True,
                        threaded=threaded,
                        ssl_context=ssl_context
                    )
                except ImportError:
                    raise CommandError("""Werkzeug 0.8.2 or later is required
to use runserver_plus with ssl support.  Please
visit http://werkzeug.pocoo.org/download""")
            else:
                run_simple(
                    addr,
                    int(port),
                    DebuggedApplication(handler, True),
                    use_reloader=use_reloader,
                    use_debugger=True,
                    threaded=threaded
                )
예제 #18
0
파일: cli.py 프로젝트: dequis/wakarimasen
def http(application, host='', port=8000):
    """
    $0 http [host [port]]

    Defaults to listening on all interfaces, port 8000
    """

    app_path = os.path.basename(sys.argv[0])

    werkzeug.run_simple(host, int(port),
        util.wrap_static(application, app_path,
            index='wakaba.html'),
        use_reloader=True, use_debugger=config.DEBUG)
def development(addr, port, application):
    from werkzeug import run_simple

    run_simple(
        addr,
        port,
        application,
        use_reloader=True,
        extra_files=None,
        reloader_interval=1,
        threaded=False,
        processes=1,
        request_handler=None,
    )
예제 #20
0
파일: scripts.py 프로젝트: burhan/solace
    def run(self):
        from werkzeug import run_simple
        def wsgi_app(*a):
            from solace.application import application
            return application(*a)

        # werkzeug restarts the interpreter with the same arguments
        # which would print "running runserver" a second time.  Because
        # of this we force distutils into quiet mode.
        import sys
        sys.argv.insert(1, '-q')

        run_simple(self.host, int(self.port), wsgi_app,
                   use_reloader=not self.no_reloader,
                   use_debugger=not self.no_debugger)
예제 #21
0
파일: app.py 프로젝트: Davmuz/flask
    def run(self, host=None, port=None, **options):
        """Runs the application on a local development server.  If the
        :attr:`debug` flag is set the server will automatically reload
        for code changes and show a debugger in case an exception happened.

        If you want to run the application in debug mode, but disable the
        code execution on the interactive debugger, you can pass
        ``use_evalex=False`` as parameter.  This will keep the debugger's
        traceback screen active, but disable code execution.

        .. admonition:: Keep in Mind

           Flask will suppress any server error with a generic error page
           unless it is in debug mode.  As such to enable just the
           interactive debugger without the code reloading, you have to
           invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
           Setting ``use_debugger`` to `True` without being in debug mode
           won't catch any exceptions because there won't be any to
           catch.

        :param host: the hostname to listen on.  set this to ``'0.0.0.0'``
                     to have the server available externally as well.
        :param port: the port of the webserver
        :param options: the options to be forwarded to the underlying
                        Werkzeug server.  See :func:`werkzeug.run_simple`
                        for more information.
        """
        from werkzeug import run_simple
        if 'debug' in options:
            self.debug = options.pop('debug')
        options.setdefault('use_reloader', self.debug)
        options.setdefault('use_debugger', self.debug)
        return run_simple(host or self.host, port or self.port, self, **options)
예제 #22
0
파일: serve.py 프로젝트: amitu/amitu-dutils
def runserver(ip, port, settings_module=None, debug=False):
    if settings_module: os.environ["DJANGO_SETTINGS_MODULE"] = settings_module
    from django.core.handlers.wsgi import WSGIHandler

    app = WSGIHandler()

    if debug: app = DebuggedApplication(app, True)

    print "Started http server on %s:%s." % (ip, port)
    if debug: print "This is DEBUG server, HIGHLY INSECURE!"
    print "Hit ^C to exit."

    try:
        run_simple(ip, port, app)
    except KeyboardInterrupt:
        print "Shutting down gracefully."
예제 #23
0
파일: __init__.py 프로젝트: akuendig/cydra
def standalone_serve():
    """Standalone WSGI Server for debugging purposes"""
    from werkzeug import run_simple
    import sys

    port = 8080
    if len(sys.argv) > 1:
        port = int(sys.argv[1])

    app = TracWrapper()

    #from werkzeugprofiler import ProfilerMiddleware
    #app = ProfilerMiddleware(app, stream=open('profile_stats.txt', 'w'), accum_count=100, sort_by=('cumulative', 'calls'), restrictions=(.1,))

    run_simple('0.0.0.0', port, app, use_reloader=True,
            use_debugger=False, #use_evalex=True,
            )
예제 #24
0
파일: debugger.py 프로젝트: delfick/cwf
 def run(self):
     """Start the debugger"""
     def setup_func():
         self.setup_500()
         self.setup_path(self.project)
     app = self.setup_app()
     try:
         run_simple(self.host, self.port, app
             , use_debugger=True, use_reloader=True, setup_func=setup_func
             )
     except TypeError as error:
         if error.message == "run_simple() got an unexpected keyword argument 'setup_func'":
             import traceback
             import sys
             traceback.print_exc()
             sys.exit("Please support https://github.com/mitsuhiko/werkzeug/issues/220")
         raise
예제 #25
0
파일: commands.py 프로젝트: neithere/tool
    def serve(args):
        """ Runs development server for your application. Wrapper for Werkzeug's
        run_simple_ function.

        Note that without ``nodebug`` this will wrap the application into
        `werkzeug.debug.DebuggedApplication` without touching the application's
        WSGI stack, i.e. this middleware will *not* be visible in the output of
        :func:`tool.debug.print_wsgi_stack`. The reason is simple: this command
        only serves the application but does not configure it; therefore it should
        not modify the internals of the object being served.

        .. _run_simple: http://werkzeug.pocoo.org/documentation/dev/serving.html#werkzeug.run_simple
        """
        run_simple(
            application = application,
            hostname = args.host,
            port = args.port,
            use_reloader = not args.noreload,
            use_debugger = not args.nodebug,
        )
예제 #26
0
 def inner_run():
     from django.conf import settings
     print 'Validating models...'
     self.validate(display_num_errors=True)
     print '\nDjango version %s, using settings %r' \
         % (django.get_version(), settings.SETTINGS_MODULE)
     print 'Development server is running at http://%s:%s/' \
         % (addr, port)
     print 'Using the Werkzeug debugger (http://werkzeug.pocoo.org/)'
     print 'Quit the server with %s.' % quit_command
     path = admin_media_path or django.__path__[0] \
         + '/contrib/admin/media'
     handler = AdminMediaHandler(WSGIHandler(), path)
     if open_browser:
         import webbrowser
         url = 'http://%s:%s/' % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler,
                True), use_reloader=use_reloader,
                use_debugger=True)
예제 #27
0
파일: server.py 프로젝트: szarak/pygnite
def dev(app, host='127.0.0.1', port='6060', **kwds):
    """
    Launches dev server.

    :param app: Application.
    :param host: Hostname.
    :param port: Port.
    :param auto_reload: If True check files changes and reload server if occured.
    """

    from werkzeug import run_simple
    return run_simple(host, port, app, use_reloader=kwds.get('auto_reload', True))
예제 #28
0
	def run(self, host="localhost", port=3044, **options):
		"""run muxi application~:root URL:~http://muxihost:304"""
		from werkzeug import run_simple
		if 'debug' in options:
			self.debug = options.pop('debug')
		if self.static_path is not None:
			options['static_files'] = {
					self.static_path:(self.package_name, 'static')
					}
			options.setdefault('use_reloader', self.debug)
		options.setdefault('use_debugger', self.debug)
		return run_simple(host, port, self, **options)
예제 #29
0
 def inner_run():
     from django.conf import settings
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = admin_media_path or django.__path__[0] + '/contrib/admin/media'
     handler = AdminMediaHandler(WSGIHandler(), path)
     if StaticFilesHandler is not None:
         use_static_handler = options.get('use_static_handler', True)
         insecure_serving = options.get('insecure_serving', False)
         if (settings.DEBUG and use_static_handler or
                 (use_static_handler and insecure_serving)):
             handler = StaticFilesHandler(handler)
     if open_browser:
         import webbrowser
         url = "http://%s:%s/" % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler, True),
                use_reloader=use_reloader, use_debugger=True, threaded=threaded)
예제 #30
0
def run_server(hostname='', port=8080,
               docs=True,
               debug='off',
               user=None, group=None,
               threaded=True,
               **kw):
    app = flask.Flask(__name__)
    app.register_blueprint(easy_attach_page, url_prefix='/easy_attach')
    app.register_blueprint(sqlrun_page, url_prefix='/sqlrun')
    """ Run a standalone server on specified host/port. """
    application = make_application(shared=docs)
    application = DispatcherMiddleware(application, {
        '/': application,
      	'/__moinfbp': app,
    })


    if port < 1024:
        if os.name == 'posix' and os.getuid() != 0:
            raise RuntimeError('Must run as root to serve port number under 1024. '
                               'Run as root or change port setting.')

    if user:
        switch_user(user, group)

    if debug == 'external':
        # no threading is better for debugging, the main (and only)
        # thread then will just terminate when an exception happens
        threaded = False

    run_simple(hostname=hostname, port=port,
               application=application,
               threaded=threaded,
               use_debugger=(debug == 'web'),
               passthrough_errors=(debug == 'external'),
               request_handler=RequestHandler,
               **kw)
예제 #31
0
    def run(self, host='localhost', port=5000, **options):
        """Runs the application on a local development server.  If the
        :attr:`debug` flag is set the server will automatically reload
        for code changes and show a debugger in case an exception happened.

        :param host: the hostname to listen on.  set this to ``'0.0.0.0'``
                     to have the server available externally as well.
        :param port: the port of the webserver
        :param options: the options to be forwarded to the underlying
                        Werkzeug server.  See :func:`werkzeug.run_simple`
                        for more information.
        """
        from werkzeug import run_simple
        if 'debug' in options:
            self.debug = options.pop('debug')
        options.setdefault('use_reloader', self.debug)
        options.setdefault('use_debugger', self.debug)
        return run_simple(host, port, self, **options)
예제 #32
0
def start_app(title, base_path, debug: bool, host, port):
    global app, dash_app, dispatcher
    try:
        lang = locale.getlocale()[0].split("_")[0]
        locale.setlocale(locale.LC_TIME, ".".join(locale.getlocale())) #make sure LC_TIME is set
        locale_url = [f"https://cdn.plot.ly/plotly-locale-{lang}-latest.js"]
    except (IndexError, locale.Error):
        locale_url = None
        logger.warning("Can't get language")
    app = Flask(__name__)
    app.config["DEBUG"] = debug
    if base_path == "/":
        application = DispatcherMiddleware(app)
        requests_pathname_prefix = None
    else:
        application = DispatcherMiddleware(Flask('dummy_app'), {base_path: app})
        requests_pathname_prefix = base_path + "/"
    dash_app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP], external_scripts=locale_url, title=title,
                         server=app, requests_pathname_prefix=requests_pathname_prefix)
    # keep this line
    import web.views
    return run_simple(host, port, application, use_reloader=False, use_debugger=debug)
            <input type="submit" value="Login">
        </form>''' % error,
                    mimetype='text/html')


def index(request):
    return Response('''
        <title>Logged in</title>
        <h1>Logged in</h1>
        <p>Logged in as %s
        <p><a href="/?do=logout">Logout</a>
    ''' % escape(request.user),
                    mimetype='text/html')


@AppRequest.application
def application(request):
    if request.args.get('do') == 'logout':
        request.logout()
        response = redirect('.')
    elif request.logged_in:
        response = index(request)
    else:
        response = login_form(request)
    request.session.save_cookie(response)
    return response


if __name__ == '__main__':
    run_simple('localhost', 4000, application)
예제 #34
0
""" A simple Werkzeug web server for running the Skills Labeller API in a
container or dev/test mode.

"""

import os
from werkzeug import run_simple
from api import app

# Environment configuration
API_PORT = os.getenv('API_PORT', 8080)
API_HOST = os.getenv('API_HOSTNAME', 'skilloracle')
API_DEBUG = os.getenv('API_DEBUG', 0)

if __name__ == '__main__':
    if API_DEBUG == 1:
        reloader = True
        debugger = True
    else:
        reloader = False
        debugger = False

    run_simple(API_HOST,
               API_PORT,
               app,
               use_reloader=reloader,
               use_debugger=debugger)
예제 #35
0
def run(bind_address='0.0.0.0', port=8008):
    """Run the webapp in a simple server process."""
    from werkzeug import run_simple
    print "* Starting on %s:%s" % (bind_address, port)
    run_simple(bind_address, port, webapp(), use_reloader=False, threaded=True)
예제 #36
0
from molten import App
from wsgicors import CORS

from readit import settings
from readit.books.routes import routes as book_routes
from readit.db import db_init

from readit.users.routes import routes as user_routes
from readit.components import UserComponent

routes = book_routes + user_routes

app = App(routes=routes, components=[UserComponent()])

if __name__ == "__main__":
    import werkzeug

    options = {
        "hostname": settings.Server.host,
        "port": settings.Server.port,
        "use_debugger": True,
        "use_reloader": True,
    }
    db_init()
    cors_app = CORS(app, headers="*", methods="*", origin="*", maxage="86400")
    werkzeug.run_simple(application=cors_app, **options)
예제 #37
0
def run(host, port):

    run_simple(hostname=host, port=port, application=app)
예제 #38
0
def run(config):
    return run_simple(**config)
예제 #39
0
    if options.cache_force and not options.caching:
        options.caching = True

    #parser.error("Caching must be turned on with '--caching' flag for liteserv.py to accept '--cache-path' option")
    #http_setup = options.host, options.port
    #httpd = simple_server.WSGIServer(http_setup, WSGIRequestHandler)
    #httpd.set_app(application)

    from tilelite import Server
    application = Server(mapfile, CONFIG)
    application.absorb_options(strip_opts(options.__dict__))
                
    try:
        from werkzeug import run_simple
        print_url(options)
        run_simple(options.host, options.port, application, threaded=options.threaded, processes=options.num_processes)
    except:
        if options.num_processes > 1:
            sys.exit('The werkzeug python server must be installed to run multi-process\n')
        sys.stderr.write('Note: werkzeug is not installed so falling back to built-in python wsgiref server.\n')
        sys.stderr.write('Install werkzeug from http://werkzeug.pocoo.org/\n\n')
        
        from wsgiref import simple_server
        # below code was for testing multi-threaded rendering
        # which only works if we copy a map object per thread
        # so avoid this and only run multiprocess...
        #from SocketServer import ThreadingMixIn
        #class myServer(ThreadingMixIn, simple_server.WSGIServer):
        #    pass 
        #httpd = myServer(('',options.port), simple_server.WSGIRequestHandler,)
        #httpd.set_app(application)
예제 #40
0
    text = request.form['text']
    f1.save(request.stat_folder + '/file1.bin')
    f2.save(request.stat_folder + '/file2.bin')
    file(request.stat_folder + '/text.txt', 'w').write(text.encode('utf-8'))
    return Response('Done.')


def upload_file(request):
    return Response('''
    <h1>Upload File</h1>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="file" name="file1"><br>
        <input type="file" name="file2"><br>
        <textarea name="text"></textarea><br>
        <input type="submit" value="Send">
    </form>
    ''', mimetype='text/html')


def application(environ, start_responseonse):
    request = Request(environ)
    if request.method == 'POST':
        response = stats(request)
    else:
        response = upload_file(request)
    return response(environ, start_responseonse)


if __name__ == '__main__':
    run_simple('localhost', 5000, application, use_debugger=True)
예제 #41
0
 def run(self):
     run_simple('0.0.0.0', 80, app, threaded=True, use_reloader=False)
예제 #42
0
def launch_server_werkzeug(host, port, app):
    """use werkzeug's simple multiprocess multithreaded server"""
    from werkzeug import run_simple
    logging.info("Starting Werkzeug server, listening on port %s", port)
    run_simple(host, port, app, threaded=True)
예제 #43
0
    def inner_run(self, options):
        if not HAS_WERKZEUG:
            raise CommandError(
                "Werkzeug is required to use runserver_plus.  Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)"
            )

        # Set colored output
        if settings.DEBUG:
            try:
                set_werkzeug_log_color()
            except Exception:  # We are dealing with some internals, anything could go wrong
                if self.show_startup_messages:
                    print(
                        "Wrapping internal werkzeug logger for color highlighting has failed!"
                    )

        class WSGIRequestHandler(_WSGIRequestHandler):
            def make_environ(self):
                environ = super().make_environ()
                if not options['keep_meta_shutdown_func']:
                    del environ['werkzeug.server.shutdown']
                return environ

        threaded = options['threaded']
        use_reloader = options['use_reloader']
        open_browser = options['open_browser']
        quit_command = 'CONTROL-C' if sys.platform != 'win32' else 'CTRL-BREAK'
        reloader_interval = options['reloader_interval']
        reloader_type = options['reloader_type']
        self.extra_files = set(options['extra_files'])

        self.nopin = options['nopin']

        if self.show_startup_messages:
            print("Performing system checks...\n")

        try:
            check_errors(
                self.check)(display_num_errors=self.show_startup_messages)
            check_errors(self.check_migrations)()
            handler = check_errors(self.get_handler)(**options)
        except Exception as exc:
            self.stderr.write("Error occurred during checks: %r" % exc,
                              ending="\n\n")
            handler = self.get_error_handler(exc, **options)

        if USE_STATICFILES:
            use_static_handler = options['use_static_handler']
            insecure_serving = options['insecure_serving']
            if use_static_handler and (settings.DEBUG or insecure_serving):
                handler = StaticFilesHandler(handler)

        if options["cert_path"] or options["key_file_path"]:
            if not HAS_OPENSSL:
                raise CommandError(
                    "Python OpenSSL Library is "
                    "required to use runserver_plus with ssl support. "
                    "Install via pip (pip install pyOpenSSL).")

            certfile, keyfile = self.determine_ssl_files_paths(options)
            dir_path, root = os.path.split(certfile)
            root, _ = os.path.splitext(root)
            try:
                if os.path.exists(certfile) and os.path.exists(keyfile):
                    ssl_context = (certfile, keyfile)
                else:  # Create cert, key files ourselves.
                    ssl_context = make_ssl_devcert(os.path.join(
                        dir_path, root),
                                                   host='localhost')
            except ImportError:
                if self.show_startup_messages:
                    print(
                        "Werkzeug version is less than 0.9, trying adhoc certificate."
                    )
                ssl_context = "adhoc"
        else:
            ssl_context = None

        bind_url = "%s://%s:%s/" % ("https" if ssl_context else "http",
                                    self.addr if not self._raw_ipv6 else
                                    '[%s]' % self.addr, self.port)

        if self.show_startup_messages:
            print("\nDjango version %s, using settings %r" %
                  (django.get_version(), settings.SETTINGS_MODULE))
            print("Development server is running at %s" % (bind_url, ))
            print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)")
            print("Quit the server with %s." % quit_command)

        if open_browser:
            webbrowser.open(bind_url)

        if use_reloader and settings.USE_I18N:
            self.extra_files |= set(
                filter(lambda filename: str(filename).endswith('.mo'),
                       gen_filenames()))

        if getattr(settings, 'RUNSERVER_PLUS_EXTRA_FILES', []):
            self.extra_files |= set(settings.RUNSERVER_PLUS_EXTRA_FILES)

        # Werkzeug needs to be clued in its the main instance if running
        # without reloader or else it won't show key.
        # https://git.io/vVIgo
        if not use_reloader:
            os.environ['WERKZEUG_RUN_MAIN'] = 'true'

        # Don't run a second instance of the debugger / reloader
        # See also: https://github.com/django-extensions/django-extensions/issues/832
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            if self.nopin:
                os.environ['WERKZEUG_DEBUG_PIN'] = 'off'
            handler = DebuggedApplication(handler, True)

        runserver_plus_started.send(sender=self)
        run_simple(
            self.addr,
            int(self.port),
            handler,
            use_reloader=use_reloader,
            use_debugger=True,
            extra_files=self.extra_files,
            exclude_patterns=WERKZEUG_EXCLUDE_PATTERNS,
            reloader_interval=reloader_interval,
            reloader_type=reloader_type,
            threaded=threaded,
            request_handler=WSGIRequestHandler,
            ssl_context=ssl_context,
        )
예제 #44
0
# http://www.ibm.com/developerworks/aix/library/au-zodb/
# http://www.zodb.org/en/latest/tutorial.html
# pip install ZODB
#
# https://www.jetbrains.com/pycharm/
#
# Python 2.7.11
#
# Python O.O.:
# http://www.tutorialspoint.com/python/python_classes_objects.htm
#
# PyInstaller:
# https://github.com/pyinstaller/pyinstaller
#
# Flask
# http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

from flask import Flask

#from app import app
# app.run(debug=True)

def import_on_first_request(environ,start_response):
    from app import app
    app.debug=True
    return app(environ,start_response)

from werkzeug import run_simple
run_simple('localhost',5000,import_on_first_request)
예제 #45
0
    def __init__(self, server_name):
        self.server_name = server_name

    def dispath_request(self, request):
        print(request.path, request.method)
        name = request.args.get("name") if request.args.get(
            "name") else "undefined"
        return Response("hello," + name)

    def wsgi_app(self, environ, start_response):
        request = Request(environ)
        response = self.dispath_request(request)
        return response(environ, start_response)

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)


def create_app(server_name='There is no'):
    app = Shortly(server_name)

    return app


if __name__ == '__main__':
    app = create_app("ubuntu")
    run_simple('localhost',
               8080,
               application=app,
               use_debugger=True,
               use_reloader=True)
예제 #46
0
 def serve(self, host, port, **options):
     werkzeug.run_simple(host, port, self, **options)
예제 #47
0
    def inner_run(self, *args, **options):
        # 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

        shutdown_message = options.get('shutdown_message', '')
        use_werkzeug = options.get('use_werkzeug', False)
        quit_command = (sys.platform
                        == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
        wsgi_app = options.get('wsgi_app', None)

        if use_werkzeug:
            try:
                from werkzeug import run_simple, DebuggedApplication
            except ImportError as e:
                self.stderr.write(
                    "WARNING: Unable to initialize werkzeug: %s\n" % e)
                use_werkzeug = False
            else:
                from django.views import debug
                debug.technical_500_response = null_technical_500_response

        self.stdout.write("Validating models...\n\n")
        self.check(display_num_errors=True)
        self.check_migrations()
        self.stdout.write(
            ("Django version %(version)s, using settings %(settings)r\n"
             "Running django-devserver %(devserver_version)s\n"
             "%(server_model)s %(server_type)s server is running at http://%(addr)s:%(port)s/\n"
             "Quit the server with %(quit_command)s.\n") % {
                 "server_type": use_werkzeug and 'werkzeug' or 'Django',
                 "server_model": options['use_forked'] and 'Forked'
                 or 'Threaded',
                 "version": self.get_version(),
                 "devserver_version": devserver.get_version(),
                 "settings": settings.SETTINGS_MODULE,
                 "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr,
                 "port": self.port,
                 "quit_command": 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)

        app = self.get_handler(*args, **options)
        if wsgi_app:
            self.stdout.write("Using WSGI application %r\n" % 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 options['use_dozer']:
            from dozer import Dozer
            app = Dozer(app)

        try:
            if use_werkzeug:
                run_simple(self.addr,
                           int(self.port),
                           DebuggedApplication(app, True),
                           use_reloader=False,
                           use_debugger=True)
            else:
                run(self.addr, int(self.port), app, mixin, ipv6=self.use_ipv6)

        except wsgi_server_exc_cls as e:
            # Use helpful error messages instead of ugly tracebacks.
            ERRORS = {
                errno.EACCES: "You don't have permission to access that port.",
                errno.EADDRINUSE: "That port is already in use.",
                errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
            }
            if not isinstance(e, socket.error):  # Django < 1.6
                ERRORS[13] = ERRORS.pop(errno.EACCES)
                ERRORS[98] = ERRORS.pop(errno.EADDRINUSE)
                ERRORS[99] = ERRORS.pop(errno.EADDRNOTAVAIL)

            try:
                if not isinstance(e, socket.error):  # Django < 1.6
                    error_text = ERRORS[e.args[0].args[0]]
                else:
                    error_text = ERRORS[e.errno]
            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)

        except KeyboardInterrupt:
            if shutdown_message:
                self.stdout.write("%s\n" % shutdown_message)
            sys.exit(0)
예제 #48
0
 def serve(self, host, port, **options):
     wsgi = ASGItoWSGIAdapter(self)
     werkzeug.run_simple(host, port, wsgi, **options)
예제 #49
0
if __name__ == '__main__':

    parser = optparse.OptionParser(
        usage="""python nikserv.py <mapfile.xml> [options]
    
    Usage:
        $ python nikserv.py /path/to/mapfile.xml
    """)

    #parser.add_option('-b', '--bbox', dest='bbox_projected')

    (options, args) = parser.parse_args()
    import sys
    if len(args) < 1:
        if not mapfile:
            sys.exit('\nPlease provide the path to a mapnik mml or xml \n')
    else:
        mapfile = args[0]

    # set up for optional command line args from nik2img
    #for k,v in vars(options).items():
    #  if v != None:
    #   kwargs[k] = v

    #print kwargs

    application = z.DebuggedApplication(application, evalex=True)

    #call('open http://localhost:8000/ -a safari',shell=True)
    z.run_simple('localhost', 8000, application)
예제 #50
0
파일: run.py 프로젝트: lamyj/dicomifier.ws
#########################################################################
# Dicomifier.ws - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the MIT license. Refer to the 
# LICENSE.txt file or to https://opensource.org/licenses/MIT for details.
#########################################################################

import werkzeug
import dicomifier_ws

werkzeug.run_simple(
    "127.0.0.1", 5000, dicomifier_ws.Application.instance(), 
    use_debugger=True, use_reloader=True)
예제 #51
0
def test_port_is_int():
    with pytest.raises(TypeError, match="port must be an integer"):
        run_simple("127.0.0.1", "5000", None)
예제 #52
0
from app import App

application = App.createApp()

if __name__ == '__main__':
    from werkzeug import run_simple
    run_simple('localhost',
               5000,
               application,
               use_reloader=True,
               use_debugger=True,
               use_evalex=True)
예제 #53
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
An auto-reloading standalone wiki server, useful for development.
"""

import hatta
import werkzeug
from werkzeug.middleware.profiler import ProfilerMiddleware

if __name__ == "__main__":
    config = hatta.WikiConfig()
    config.parse_args()
    #    config.parse_files()
    wiki = hatta.Wiki(config)

    application = wiki.application

    # application = ProfilerMiddleware(application)

    host = config.get('interface', 'localhost')
    port = int(config.get('port', 8080))
    werkzeug.run_simple(host, port, application, use_reloader=True)
예제 #54
0
import io

from flask import Flask
from flask import render_template
from werkzeug import run_simple

app = Flask(__name__)


@app.route('/', methods=['GET'])
def index():
    return render_template('index.html', show_result=False)


if __name__ == "__main__":
    run_simple('localhost', 5001, app, use_reloader=True, use_debugger=True)
예제 #55
0
    def inner_run(self, options):
        import django

        try:
            from werkzeug import run_simple, DebuggedApplication
            from werkzeug.serving import WSGIRequestHandler as _WSGIRequestHandler

            # Set colored output
            if settings.DEBUG:
                try:
                    set_werkzeug_log_color()
                except Exception:  # We are dealing with some internals, anything could go wrong
                    if self.show_startup_messages:
                        print("Wrapping internal werkzeug logger for color highlighting has failed!")
                    pass

        except ImportError:
            raise CommandError("Werkzeug is required to use runserver_plus.  Please visit http://werkzeug.pocoo.org/ or install via pip. (pip install Werkzeug)")

        class WSGIRequestHandler(_WSGIRequestHandler):
            def make_environ(self):
                environ = super(WSGIRequestHandler, self).make_environ()
                if not options.get('keep_meta_shutdown_func'):
                    del environ['werkzeug.server.shutdown']
                return environ

        threaded = options.get('threaded', True)
        use_reloader = options.get('use_reloader', True)
        open_browser = options.get('open_browser', False)
        cert_path = options.get("cert_path")
        quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
        extra_files = options.get('extra_files', None) or []
        reloader_interval = options.get('reloader_interval', 1)
        reloader_type = options.get('reloader_type', 'auto')

        self.nopin = options.get('nopin', False)

        if self.show_startup_messages:
            print("Performing system checks...\n")
        if hasattr(self, 'check'):
            self.check(display_num_errors=self.show_startup_messages)
        else:
            self.validate(display_num_errors=self.show_startup_messages)
        try:
            self.check_migrations()
        except ImproperlyConfigured:
            pass
        handler = get_internal_wsgi_application()
        if USE_STATICFILES:
            use_static_handler = options.get('use_static_handler', True)
            insecure_serving = options.get('insecure_serving', False)
            if use_static_handler and (settings.DEBUG or insecure_serving):
                handler = StaticFilesHandler(handler)
        if cert_path:
            """
            OpenSSL is needed for SSL support.

            This will make flakes8 throw warning since OpenSSL is not used
            directly, alas, this is the only way to show meaningful error
            messages. See:
            http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/
            for more information on python imports.
            """
            try:
                import OpenSSL  # NOQA
            except ImportError:
                raise CommandError("Python OpenSSL Library is "
                                   "required to use runserver_plus with ssl support. "
                                   "Install via pip (pip install pyOpenSSL).")

            dir_path, cert_file = os.path.split(cert_path)
            if not dir_path:
                dir_path = os.getcwd()
            root, ext = os.path.splitext(cert_file)
            certfile = os.path.join(dir_path, root + ".crt")
            keyfile = os.path.join(dir_path, root + ".key")
            try:
                from werkzeug.serving import make_ssl_devcert
                if os.path.exists(certfile) and \
                        os.path.exists(keyfile):
                            ssl_context = (certfile, keyfile)
                else:  # Create cert, key files ourselves.
                    ssl_context = make_ssl_devcert(
                        os.path.join(dir_path, root), host='localhost')
            except ImportError:
                if self.show_startup_messages:
                    print("Werkzeug version is less than 0.9, trying adhoc certificate.")
                ssl_context = "adhoc"

        else:
            ssl_context = None

        bind_url = "%s://%s:%s/" % (
            "https" if ssl_context else "http", self.addr if not self._raw_ipv6 else '[%s]' % self.addr, self.port)

        if self.show_startup_messages:
            print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE))
            print("Development server is running at %s" % (bind_url,))
            print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)")
            print("Quit the server with %s." % quit_command)

        if open_browser:
            import webbrowser
            webbrowser.open(bind_url)

        if use_reloader and settings.USE_I18N:
            extra_files.extend(filter(lambda filename: filename.endswith('.mo'), gen_filenames()))

        # Werkzeug needs to be clued in its the main instance if running
        # without reloader or else it won't show key.
        # https://git.io/vVIgo
        if not use_reloader:
            os.environ['WERKZEUG_RUN_MAIN'] = 'true'

        # Don't run a second instance of the debugger / reloader
        # See also: https://github.com/django-extensions/django-extensions/issues/832
        if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
            if self.nopin:
                os.environ['WERKZEUG_DEBUG_PIN'] = 'off'
            handler = DebuggedApplication(handler, True)

        run_simple(
            self.addr,
            int(self.port),
            handler,
            use_reloader=use_reloader,
            use_debugger=True,
            extra_files=extra_files,
            reloader_interval=reloader_interval,
            reloader_type=reloader_type,
            threaded=threaded,
            request_handler=WSGIRequestHandler,
            ssl_context=ssl_context,
        )
예제 #56
0
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option(
            '--werkzeug',
            action='store_true',
            dest='use_werkzeug',
            default=False,
            help='Tells Django to use the Werkzeug interactive debugger.'),
        make_option(
            '--forked',
            action='store_true',
            dest='use_forked',
            default=False,
            help='Use forking instead of threading for multiple web requests.'
        ),
        make_option('--dozer',
                    action='store_true',
                    dest='use_dozer',
                    default=False,
                    help='Enable the Dozer memory debugging middleware.'),
        make_option(
            '--wsgi-app',
            dest='wsgi_app',
            default=None,
            help='Load the specified WSGI app as the server endpoint.'),
    )
    if any(map(lambda app: app in settings.INSTALLED_APPS, STATICFILES_APPS)):
        option_list += make_option(
            '--nostatic',
            dest='use_static_files',
            action='store_false',
            default=True,
            help=
            'Tells Django to NOT automatically serve static files at STATIC_URL.'
        ),

    help = "Starts a lightweight Web server for development which outputs additional debug information."
    args = '[optional port number, or ipaddr:port]'

    # Validation is called explicitly each time the server is reloaded.
    requires_model_validation = False

    def run_from_argv(self, argv):
        parser = self.create_parser(argv[0], argv[1])
        default_args = getattr(settings, 'DEVSERVER_ARGS', None)
        if default_args:
            options, args = parser.parse_args(default_args)
        else:
            options = None

        options, args = parser.parse_args(argv[2:], options)

        handle_default_options(options)
        self.execute(*args, **options.__dict__)

    def handle(self, addrport='', *args, **options):
        if args:
            raise CommandError('Usage is runserver %s' % self.args)

        if not addrport:
            addr = getattr(settings, 'DEVSERVER_DEFAULT_ADDR', '127.0.0.1')
            port = getattr(settings, 'DEVSERVER_DEFAULT_PORT', '8000')
            addrport = '%s:%s' % (addr, port)

        return super(Command, self).handle(addrport=addrport, *args, **options)

    def get_handler(self, *args, **options):
        if int(options['verbosity']) < 1:
            handler = WSGIHandler()
        else:
            handler = DevServerHandler()

        # AdminMediaHandler is removed in Django 1.5
        # Add it only when it avialable.
        try:
            from django.core.servers.basehttp import AdminMediaHandler
        except ImportError:
            pass
        else:
            handler = AdminMediaHandler(handler, options['admin_media_path'])

        if 'django.contrib.staticfiles' in settings.INSTALLED_APPS and options[
                'use_static_files']:
            from django.contrib.staticfiles.handlers import StaticFilesHandler
            handler = StaticFilesHandler(handler)

        return handler

    def inner_run(self, *args, **options):
        # 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

        shutdown_message = options.get('shutdown_message', '')
        use_werkzeug = options.get('use_werkzeug', False)
        quit_command = (sys.platform
                        == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
        wsgi_app = options.get('wsgi_app', None)

        if use_werkzeug:
            try:
                from werkzeug import run_simple, DebuggedApplication
            except ImportError, e:
                self.stderr.write(
                    "WARNING: Unable to initialize werkzeug: %s\n" % e)
                use_werkzeug = False
            else:
                from django.views import debug
                debug.technical_500_response = null_technical_500_response

        self.stdout.write("Validating models...\n\n")
        self.validate(display_num_errors=True)
        self.stdout.write(
            ("Django version %(version)s, using settings %(settings)r\n"
             "Running django-devserver %(devserver_version)s\n"
             "%(server_model)s %(server_type)s server is running at http://%(addr)s:%(port)s/\n"
             "Quit the server with %(quit_command)s.\n") % {
                 "server_type": use_werkzeug and 'werkzeug' or 'Django',
                 "server_model": options['use_forked'] and 'Forked'
                 or 'Threaded',
                 "version": self.get_version(),
                 "devserver_version": devserver.get_version(),
                 "settings": settings.SETTINGS_MODULE,
                 "addr": self._raw_ipv6 and '[%s]' % self.addr or self.addr,
                 "port": self.port,
                 "quit_command": 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)

        app = self.get_handler(*args, **options)
        if wsgi_app:
            self.stdout.write("Using WSGI application %r\n" % 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 options['use_dozer']:
            from dozer import Dozer
            app = Dozer(app)

        try:
            if use_werkzeug:
                run_simple(self.addr,
                           int(self.port),
                           DebuggedApplication(app, True),
                           use_reloader=False,
                           use_debugger=True)
            else:
                run(self.addr,
                    int(self.port),
                    app,
                    mixin,
                    ipv6=options['use_ipv6'])

        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)
예제 #57
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from werkzeug import run_simple

from pyamf.remoting.gateway.wsgi import WSGIGateway

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s')


def echo(data):
    return data


services = {'echo': echo}
gw = WSGIGateway(services, logger=logging, debug=True)

run_simple('localhost', 8080, gw, use_reloader=True)
예제 #58
0
class Shortly(object):
    def __init__(self, config):
        self.redis = redis.Redis(config['redis_host'], config['redis_port'])

    def dispatch_request(self, request):
        return Response('Hello World')

    def wsgi_app(self, environ, start_response):
        request = Request(environ)
        response = self.dispatch_request(request)
        return response(environ, start_response)

    def __call__(self, environ, start_response):
        return self.wsgi_app(environ, start_response)


def create_app(redis_host='localhost', redis_port=6379, with_static=True):
    app = Shortly({'redis_host': redis_host, 'redis_port': redis_port})
    if with_static:
        app.wsgi_app = SharedDataMiddleware(
            app.wsgi_app,
            {'/static': os.path.join(os.path.dirname(__file__), 'static')})
    return app


if __name__ == '__main__':
    from werkzeug import run_simple
    app = create_app()
    run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True)
예제 #59
0
파일: runserver.py 프로젝트: pitdeer/kro
        def inner_run():
            print("Validating models...")
            try:
                self.check(display_num_errors=True)
            except AttributeError:
                self.validate(display_num_errors=True)
            print("\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE))
            print("Development server is running at %s" % (bind_url,))
            print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)")
            print("Quit the server with %s." % quit_command)
            path = options.get('admin_media_path', '')
            if not path:
                admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
                if os.path.isdir(admin_media_path):
                    path = admin_media_path
                else:
                    path = os.path.join(django.__path__[0], 'contrib/admin/media')
            handler = WSGIHandler()
            if USE_ADMINMEDIAHANDLER:
                handler = AdminMediaHandler(handler, path)
            if USE_STATICFILES:
                use_static_handler = options.get('use_static_handler', True)
                insecure_serving = options.get('insecure_serving', False)
                if use_static_handler and (settings.DEBUG or insecure_serving):
                    handler = StaticFilesHandler(handler)
            if open_browser:
                import webbrowser
                webbrowser.open(bind_url)
            if cert_path:
                """
                OpenSSL is needed for SSL support.

                This will make flakes8 throw warning since OpenSSL is not used
                directly, alas, this is the only way to show meaningful error
                messages. See:
                http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/
                for more information on python imports.
                """
                try:
                    import OpenSSL  # NOQA
                except ImportError:
                    raise CommandError("Python OpenSSL Library is "
                                       "required to use runserver_plus with ssl support. "
                                       "Install via pip (pip install pyOpenSSL).")

                dir_path, cert_file = os.path.split(cert_path)
                if not dir_path:
                    dir_path = os.getcwd()
                root, ext = os.path.splitext(cert_file)
                certfile = os.path.join(dir_path, root + ".crt")
                keyfile = os.path.join(dir_path, root + ".key")
                try:
                    from werkzeug.serving import make_ssl_devcert
                    if os.path.exists(certfile) and \
                            os.path.exists(keyfile):
                                ssl_context = (certfile, keyfile)
                    else:  # Create cert, key files ourselves.
                        ssl_context = make_ssl_devcert(
                            os.path.join(dir_path, root), host='localhost')
                except ImportError:
                    print("Werkzeug version is less than 0.9, trying adhoc certificate.")
                    ssl_context = "adhoc"

            else:
                ssl_context = None
            run_simple(
                self.addr,
                int(self.port),
                DebuggedApplication(handler, True),
                use_reloader=use_reloader,
                use_debugger=True,
                threaded=threaded,
                ssl_context=ssl_context
            )
예제 #60
0
#!/usr/bin/python2 -B
# -*- coding: utf-8 -*-
import env

from werkzeug import run_simple
from app.application import Application

app = Application(debug=True)
bind_address = "127.0.0.1"
port = 5000
run_simple(bind_address, port, app, use_debugger=True, use_reloader=True)