コード例 #1
0
 def __init__(self, *args, **kwds):
     unittest.TestCase.__init__(self, *args, **kwds)
     self._cookie_jar = CookieJar()
     app = self.get_app()
     validator(app)
     self._port = random.randint(50000, 60000)
     self._httpd = make_server('', self._port, app)
     self._serve_thread = threading.Thread(target=self._httpd.serve_forever)
     self._serve_thread.setDaemon(True)
     self._opener = build_opener(NoRedirectionProcessor, HTTPCookieProcessor(self._cookie_jar))
コード例 #2
0
ファイル: dvbbc.py プロジェクト: dvidalm/dvbbc
def main():
    """Run the show"""
    #Arguments parser
    parser = argparse.ArgumentParser(description="Stream live TV over HTTP to multiple viewers, using Sundtek as capture card")
    parser.add_argument("-p","--port",type=int,default=2000,help="server port")
    parser.add_argument("-c", "--channel",type=str,default=0,help="set channel")
    parser.add_argument("-D", "--dtvmode",type=str,choices=["DVBT", "DVBC", "ATSC","ISDBT"],default="ISDBT",help="set digital TV mode for device")
    args=parser.parse_args()

    #Setting dtv mode using mediaclient
    if dtvmode(args.dtvmode):

          server = Server()
          #Select channel

          channel = select_channel(server.channels,int(args.channel))
          print("Channel selected:"+channel)
          server.set_channel(channel)

          feed_thread = threading.Thread(target=server.feeder)
          feed_thread.daemon = True
          feed_thread.start()

          validator_app = validator(server.simple_app)
          httpd = make_server('', args.port, validator_app,server_class=ThreadedWSGIServer)
          try:
              print("URL: http://%s:%s/stream" % (LOCAL_IP,args.port))
              httpd.serve_forever()
          finally:
              server.cur_chan = None
              feed_thread.join()
    else:
          print("Error setting the dtv mode")
コード例 #3
0
ファイル: test_http.py プロジェクト: warvariuc/spyne
    def test_cookie_parse(self):
        STR = 'some_string'
        class RequestHeader(ComplexModel):
            some_field = String

        class SomeService(ServiceBase):
            __in_header__ = RequestHeader

            @rpc(String)
            def some_call(ctx, s):
                assert ctx.in_header.some_field == STR

        def start_response(code, headers):
            assert code == HTTP_200

        c = SimpleCookie()
        c['some_field'] = STR

        ''.join(validator(WsgiApplication(Application([SomeService], 'tns',
            in_protocol=HttpRpc(parse_cookie=True), out_protocol=HttpRpc())))({
                'SCRIPT_NAME': '',
                'QUERY_STRING': '',
                'PATH_INFO': '/some_call',
                'REQUEST_METHOD': 'GET',
                'SERVER_NAME': 'localhost',
                'SERVER_PORT': "9999",
                'HTTP_COOKIE': str(c),
                'wsgi.url_scheme': 'http',
                'wsgi.version': (1,0),
                'wsgi.input': StringIO(),
                'wsgi.errors': StringIO(),
                'wsgi.multithread': False,
                'wsgi.multiprocess': False,
                'wsgi.run_once': True,
            }, start_response))
コード例 #4
0
ファイル: __init__.py プロジェクト: jet9/jsonrpc20
def start_standalone_server(address="localhost", port=8000, app=wsgi_application):
    """Start standalone http server for processing requests"""

    validator_app = validator(app)
    httpd = make_server(address, port, app)
    LOG.info("Serving on  {0}:{1}...".format(address, port))
    httpd.serve_forever()
コード例 #5
0
ファイル: test_pyramid.py プロジェクト: knoxsp/spyne
    def testGetWsdl(self):
        """Simple test for serving of WSDL by spyne through pyramid route"""
        application = PyramidApplication(
            Application([self.HelloWorldService],
                        tns='spyne.examples.hello',
                        in_protocol=Soap11(validator='lxml'),
                        out_protocol=Soap11()))

        config = Configurator(settings={'debug_all': True})
        config.add_route('home', '/')
        config.add_view(application, route_name='home')
        wsgi_app = validator(config.make_wsgi_app())

        env = {
            'SCRIPT_NAME': '',
            'REQUEST_METHOD': 'GET',
            'PATH_INFO': '/',
            'QUERY_STRING': 'wsdl',
        }
        setup_testing_defaults(env)

        request = Request(env)
        resp = request.get_response(wsgi_app)
        self.assert_(resp.status.startswith("200 "))
        node = etree.XML(resp.body)  # will throw exception if non well formed
コード例 #6
0
ファイル: static.py プロジェクト: svevang/cross-domain-iframe
def test():
    from wsgiref.validate import validator
    app = Cling(getcwd())
    try:
        print "Serving " + getcwd() + " to http://localhost:8888"
        print "Serving " + getcwd() + " to http://localhost:8889"

        start_server = lambda port : make_server('0.0.0.0', port, validator(app)).serve_forever() 

        #start_server(8888)

        import threading
        server_1 = threading.Thread(target=start_server, name="The 8888 server",args=[8888])
        server_2 = threading.Thread(target=start_server, name="The 8889 server",args=[8889])
        server_1.start()
        server_2.start()

        print ""
        print "Point your browser at http://localhost:8888/index.html"
        server_1.join()
        server_2.join()
        
    except KeyboardInterrupt, ki:
        print ""
        print "Ciao, baby!"
        sys.exit(0)
コード例 #7
0
ファイル: helper.py プロジェクト: ahmadfarihan/cherrypy
    def get_app(self, app=None):
        """Obtain a new (decorated) WSGI app to hook into the origin server."""
        if app is None:
            app = cherrypy.tree

        if self.conquer:
            try:
                import wsgiconq
            except ImportError:
                warnings.warn(
                    "Error importing wsgiconq. pyconquer will not run.")
            else:
                app = wsgiconq.WSGILogger(app, c_calls=True)

        if self.validate:
            try:
                from wsgiref import validate
            except ImportError:
                warnings.warn(
                    "Error importing wsgiref. The validator will not run.")
            else:
                # wraps the app in the validator
                app = validate.validator(app)

        return app
コード例 #8
0
ファイル: main.py プロジェクト: phpmywave/phpMyWave
def main():
  from wsgiref import simple_server, validate

  logging.basicConfig(level=logging.INFO)

  parser = optparse.OptionParser(usage=USAGE)
  parser.add_option('-p', '--port', dest='port', type='int', default=8000,
                    help='Port to listen on')
  options, args = parser.parse_args()
  if len(args) == 0:
    path = os.getcwd()
  elif len(args) == 1:
    path = args[0]
  else:
    parser.print_help()
    return
  repo_path = mercurial.dispatch._findrepo(path)
  if not repo_path:
    print 'No Mercurial repository found for', path
    print
    parser.print_help()
    return
  logging.info('Mercurial repository %s', repo_path)
  app = validate.validator(downy_app(repo_path))
  httpd = simple_server.make_server('', options.port, app)
  logging.info('Serving on port %d', options.port)
  httpd.serve_forever()
コード例 #9
0
ファイル: helper.py プロジェクト: Mattsface/XenMagic
def sync_apps(profile=False, validate=False, conquer=False):
    app = cherrypy.tree
    if profile:
        app = profiler.make_app(app, aggregate=False)
    if conquer:
        try:
            import wsgiconq
        except ImportError:
            warnings.warn("Error importing wsgiconq. pyconquer will not run.")
        else:
            app = wsgiconq.WSGILogger(app)
    if validate:
        try:
            from wsgiref import validate
        except ImportError:
            warnings.warn("Error importing wsgiref. The validator will not run.")
        else:
            app = validate.validator(app)
    
    h = cherrypy.server.httpserver
    if hasattr(h, 'wsgi_app'):
        # CherryPy's wsgiserver
        h.wsgi_app = app
    elif hasattr(h, 'fcgiserver'):
        # flup's WSGIServer
        h.fcgiserver.application = app
    elif hasattr(h, 'scgiserver'):
        # flup's WSGIServer
        h.scgiserver.application = app
コード例 #10
0
 def __init__(self, app):
     self.app = app
     self.server = simple_server.WSGIServer(
         ('', 8080),
         simple_server.WSGIRequestHandler,
     )
     self.server.set_app(validate.validator(self.app))
コード例 #11
0
ファイル: helper.py プロジェクト: Juanvvc/scfs
def sync_apps(profile=False, validate=False, conquer=False):
    apps = []
    for base, app in cherrypy.tree.apps.iteritems():
        if base == "/":
            base = ""
        if profile:
            app = profiler.make_app(app, aggregate=False)
        if conquer:
            try:
                import wsgiconq
            except ImportError:
                warnings.warn("Error importing wsgiconq. pyconquer will not run.")
            else:
                app = wsgiconq.WSGILogger(app)
        if validate:
            try:
                from wsgiref import validate
            except ImportError:
                warnings.warn("Error importing wsgiref. The validator will not run.")
            else:
                app = validate.validator(app)
        apps.append((base, app))
    apps.sort()
    apps.reverse()
    for s in cherrypy.server.httpservers:
        s.mount_points = apps
コード例 #12
0
  def StartWebServer(self, port, application=None):
    """Start web server.

    Args:
      port: Port to start application on.
      application: Optional WSGI function.  If none provided will use
        tests CreateWsgiApplication method.

    Returns:
      A tuple (server, application):
        server: An instance of ServerThread.
        application: Application that web server responds with.
    """
    if not application:
      application = self.CreateWsgiApplication()
    validated_application = validate.validator(application)

    try:
      server = simple_server.make_server(
          'localhost', port, validated_application)
    except socket.error:
      # Try IPv6
      server = simple_server.make_server(
          'localhost', port, validated_application, server_class=WSGIServerIPv6)

    server = ServerThread(server)
    server.start()
    return server, application
コード例 #13
0
ファイル: server.py プロジェクト: ConnorAvery/cse491-serverz
def handle_connection(conn, port):
    request = conn.recv(1)
    
    if not request:
        print 'Error, remote client closed connection without sending anything'
        return

    count = 0
    env = {}
    while request[-4:] != '\r\n\r\n':
         request += conn.recv(1)

    request, data = request.split('\r\n',1)
    headers = {}
    for line in data.split('\r\n')[:-2]:
        k, v = line.split(': ', 1)
        headers[k.lower()] = v

    path = urlparse(request.split(' ', 3)[1])
    env['REQUEST_METHOD'] = 'GET'
    env['PATH_INFO'] = path[2]
    env['QUERY_STRING'] = path[4]
    env['CONTENT_TYPE'] = 'text/html'
    env['CONTENT_LENGTH'] = str(0)
    env['SCRIPT_NAME'] = ''
    env['SERVER_NAME'] = socket.getfqdn()
    env['SERVER_PORT'] = str(port)
    env['wsgi.version'] = (1, 0)
    env['wsgi.errors'] = stderr
    env['wsgi.multithread'] = False
    env['wsgi.multiprocess'] = False
    env['wsgi.run_once'] = False
    env['wsgi.url_scheme'] = 'http'
    env['HTTP_COOKIE'] = headers['cookie'] if 'cookie' in headers.keys() else ''

    body = ''
    if request.startswith('POST '):
        env['REQUEST_METHOD'] = 'POST'
        env['CONTENT_LENGTH'] = headers['content-length']
        env['CONTENT_TYPE'] = headers['content-type']
        while len(body) < int(headers['content-length']):
            body += conn.recv(1)

    def start_response(status, response_headers):
        conn.send('HTTP/1.0 ')
        conn.send(status)
        conn.send('\r\n')
        for pair in response_headers:
            key, header = pair
            conn.send(key + ': ' + header + '\r\n')
        conn.send('\r\n')

    env['wsgi.input'] = StringIO(body)
    my_app = make_app()
    validator_app = validator(my_app)
    result = my_app(env, start_response)
    for data in result:
        conn.send(data)
    conn.close()
コード例 #14
0
ファイル: tests.py プロジェクト: romanvm/WsgiBoostServer
 def setUpClass(cls):
     cls._httpd = wsgi_boost.WsgiBoostHttp(threads=1)
     app = App()
     cls._httpd.set_app(validator(app))
     cls._server_thread = threading.Thread(target=cls._httpd.start)
     cls._server_thread.daemon = True
     cls._server_thread.start()
     time.sleep(0.5)
コード例 #15
0
ファイル: static.py プロジェクト: bgyss/static
def test():
    from wsgiref.validate import validator
    magics = StringMagic(title="String Test"), KidMagic(title="Kid Test")
    app = Shock('testdata/pub', magics=magics)
    try:
        make_server('localhost', 9999, validator(app)).serve_forever()
    except KeyboardInterrupt, ki:
        print "Ciao, baby!"
コード例 #16
0
ファイル: main.py プロジェクト: ke4roh/circuits
def main():
    opts, args = parse_options()

    bind = parse_bind(opts.bind)

    if opts.validate:
        application = (Application() + Root())
        app = validator(application)

        httpd = make_server(bind[0], bind[1], app)
        httpd.serve_forever()

        raise SystemExit(0)

    manager = Manager()

    opts.debug and Debugger().register(manager)

    Poller = select_poller(opts.poller.lower())
    Poller().register(manager)

    if opts.server.lower() == "base":
        BaseServer(bind).register(manager)
        HelloWorld().register(manager)
    else:
        Server(bind).register(manager)
        Root().register(manager)

    docroot = os.getcwd() if not args else args[0]

    Static(docroot=docroot, dirlisting=True).register(manager)

    opts.passwd and Authentication(passwd=opts.passwd).register(manager)

    opts.logging and Logger().register(manager)

    if opts.profile and hotshot:
        profiler = hotshot.Profile(".profile")
        profiler.start()

    if opts.debug:
        print(graph(manager, name="circuits.web"))
        print()
        print(inspect(manager))

    for i in range(opts.jobs):
        manager.start(process=True)

    manager.run()

    if opts.profile and hotshot:
        profiler.stop()
        profiler.close()

        stats = hotshot.stats.load(".profile")
        stats.strip_dirs()
        stats.sort_stats("time", "calls")
        stats.print_stats(20)
コード例 #17
0
 def StartServer(self, app):
   self.validated = validate.validator(app)
   self.port = test_util.pick_unused_port()
   self.server = simple_server.make_server('localhost',
                                           self.port,
                                           self.validated)
   self.server_thread = webapp_test_util.ServerThread(self.server)
   self.server_thread.start()
   self.server_thread.wait_until_running()
コード例 #18
0
ファイル: webapp_test_util.py プロジェクト: alimills/stacks
 def StartWebServer(self, port):
   """Start web server."""
   application = webapp.WSGIApplication(self.DEFAULT_MAPPING, True)
   validated_application = validate.validator(application)
   server = simple_server.make_server('localhost', port, validated_application)
   server = ServerThread(server)
   server.start()
   server.wait_until_running()
   return server, application
コード例 #19
0
 def StartWebServer(self, port):
   """Start web server."""
   application = self.CreateWsgiApplication()
   validated_application = validate.validator(application)
   server = simple_server.make_server('localhost', port, validated_application)
   server = ServerThread(server)
   server.start()
   server.wait_until_running()
   return server, application
コード例 #20
0
ファイル: APIserver.py プロジェクト: hellasgrid/snf-occi
 def __init__(self):
     """
     Initialization of the WSGI OCCI application for synnefo
     """
     global ENABLE_VOMS, VOMS_DB
     ENABLE_VOMS = VOMS_CONFIG['enable_voms']
     super(MyAPP,self).__init__(registry=snfRegistry())
     self._register_backends()
     VALIDATOR_APP = validator(self)
コード例 #21
0
ファイル: static.py プロジェクト: GunioRobot/gcli
def test():
    from wsgiref.validate import validator
    app = Cling(getcwd())
    try:
        print "Serving " + getcwd() + " to http://localhost:9999"
        make_server('localhost', 9999, validator(app)).serve_forever()
    except KeyboardInterrupt, ki:
        print ""
        print "Ciao, baby!"
コード例 #22
0
ファイル: test_wsgiref.py プロジェクト: Orav/kbengine
    def test_wsgi_input(self):
        def bad_app(e, s):
            e["wsgi.input"].read()
            s("200 OK", [("Content-Type", "text/plain; charset=utf-8")])
            return [b"data"]

        out, err = run_amock(validator(bad_app))
        self.assertTrue(out.endswith(b"A server error occurred.  Please contact the administrator."))
        self.assertEqual(err.splitlines()[-2], "AssertionError")
コード例 #23
0
ファイル: test_web.py プロジェクト: mgax/Board
def wsgi_get(app, url):
    environ = {'PATH_INFO': url, 'QUERY_STRING': '', 'SCRIPT_NAME': ''}
    wsgiref.util.setup_testing_defaults(environ)
    response = dict()
    def start_response(status, headers):
        response.update({'status': status, 'headers': headers})
    ret = validator(app)(environ, start_response)
    response['body'] = ''.join(ret)
    ret.close()
    return response
コード例 #24
0
ファイル: test_web.py プロジェクト: mgax/Board
    def test_list_children(self):
        k1 = model.Note({'-name-': 'kidone'})
        k2 = model.Note({'-name-': 'kidtwo'})
        note = model.Note(children=[k1, k2])

        req = test_request({'PATH_INFO': '/children'})
        res = req.get_response(validator(note.get_delegate().wsgi))
        data = check_json_response(res)
        self.assertEqual(data, {'children': ['http://example.com/c:kidone',
                                             'http://example.com/c:kidtwo']})
コード例 #25
0
ファイル: test_web.py プロジェクト: lost-theory/cork
def wsgi_test(app, path='/', query_string=''):
    env = {'PATH_INFO': path, 'SCRIPT_NAME': '', 'QUERY_STRING': query_string}
    setup_testing_defaults(env)
    output = {}
    def start_response(status, headers, exc_info=None):
        output.update(status=status, headers=headers, exc_info=exc_info)
    body = validator(app)(env, start_response)
    output['body'] = ''.join(body)
    body.close()
    return output
コード例 #26
0
ファイル: test_wsgiref.py プロジェクト: van7hu/fanca
    def test_simple_validation_error(self):
        def bad_app(environ, start_response):
            start_response("200 OK", ("Content-Type", "text/plain"))
            return ["Hello, world!"]

        out, err = run_amock(validator(bad_app))
        self.assertTrue(out.endswith("A server error occurred.  Please contact the administrator."))
        self.assertEqual(
            err.splitlines()[-2],
            "AssertionError: Headers (('Content-Type', 'text/plain')) must" " be of type list: <type 'tuple'>",
        )
コード例 #27
0
ファイル: wsgi_test.py プロジェクト: Exkitter/tornado
    def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
                        ("/", HelloHandler)])))
コード例 #28
0
def before_scenario(context, scenario):
    context.beer_json = context.app.config['BEER_JSON']
    if 'beerdesc' in scenario.tags:
        context.app.config['BEER_JSON'] = 'tests_json/test_beer_shortage.json'
    if 'encode' in scenario.tags:
        context.app.config['BEER_JSON'] = 'tests_json/test_beer_encode.json'
    # run app in subprocess
    # context.wsgi = make_server("", 8000, beer.app)
    context.wsgi = make_server("", 8000, validator(context.app))
    context.server = Process(target=context.wsgi.serve_forever)
    context.server.start()
コード例 #29
0
ファイル: post.py プロジェクト: JoyTeam/concurrence
def main():
    application = WSGISimpleRouter()

    from wsgiref.validate import validator

    application.map('/form', validator(show_form))
    application.map('/upload', upload_form)
    application.map('/process', process_form)

    server = WSGIServer(application)
    server.serve(('localhost', 8080))
コード例 #30
0
ファイル: rewritingproxy.py プロジェクト: iitwebdev/lectures
def main():
    options, args = parser.parse_args()
    if not args or len(args) > 1:
        parser.error('You must give one PROXY_URL')
    proxy_url = args[0]
    app = JumbleMiddleware(
        LinkRewriterMiddleware(Proxy(proxy_url), proxy_url))
    if getattr(options, 'debug', False):
        app = EvalException(app)
    app = validator(app)
    from paste.httpserver import serve
    serve(app, host=options.host, port=int(options.port))
コード例 #31
0
    def test_simple_validation_error(self):
        def bad_app(environ, start_response):
            start_response("200 OK", ('Content-Type', 'text/plain'))
            return ["Hello, world!"]

        out, err = run_amock(validator(bad_app))
        self.assertTrue(
            out.endswith(
                b"A server error occurred.  Please contact the administrator.")
        )
        self.assertEqual(
            err.splitlines()[-2],
            "AssertionError: Headers (('Content-Type', 'text/plain')) must"
            " be of type list: <class 'tuple'>")
コード例 #32
0
    def test_http_headers(self):
        DATE = datetime(year=2013, month=1, day=1)
        STR = 'hey'

        class ResponseHeader(ComplexModel):
            _type_info = {
                'Set-Cookie': String(max_occurs='unbounded'),
                'Expires': DateTime
            }

        class SomeService(ServiceBase):
            __out_header__ = ResponseHeader

            @rpc(String)
            def some_call(ctx, s):
                assert s is not None
                ctx.out_header = ResponseHeader(**{
                    'Set-Cookie': STR,
                    'Expires': DATE
                })

        def start_response(code, headers):
            assert dict(headers)['Set-Cookie'] == STR
            assert dict(headers)['Expires'] == 'Tue, 01 Jan 2013 00:00:00 GMT'

        ret = ''.join(
            validator(
                WsgiApplication(
                    Application(
                        [SomeService],
                        'tns',
                        in_protocol=HttpRpc(),
                        out_protocol=HttpRpc())))({
                            'SCRIPT_NAME': '',
                            'QUERY_STRING': '&s=' + STR,
                            'PATH_INFO': '/some_call',
                            'REQUEST_METHOD': 'GET',
                            'SERVER_NAME': 'localhost',
                            'SERVER_PORT': "9999",
                            'wsgi.url_scheme': 'http',
                            'wsgi.version': (1, 0),
                            'wsgi.input': StringIO(),
                            'wsgi.errors': StringIO(),
                            'wsgi.multithread': False,
                            'wsgi.multiprocess': False,
                            'wsgi.run_once': True,
                        }, start_response))

        assert ret == ''
コード例 #33
0
def roulette_server(count=1):
    """
    This application validates the interface used by the roulette application;
    it decorates the various APIs with assert statements to provide some diagnostic
    information.
    """
    wheel = American()
    roulette = Roulette(wheel)
    debug = validator(roulette)
    httpd = make_server('', 8080, debug)
    if count is None:
        httpd.serve_forever()
    else:
        for c in range(count):
            httpd.handle_request()
コード例 #34
0
    def StartWebServer(self, port):
        """Start web server."""
        protocols = wsgi_util.Protocols()
        protocols.add_protocol(protojson, 'json', 'application/json')

        application = wsgi_service.service_app(webapp_test_util.TestService,
                                               protocols=protocols)
        validated_application = validate.validator(application)

        other_application = wsgi_service.service_app(
            webapp_test_util.TestService.new_factory('initialized'),
            protocols=protocols)
        other_validated_application = validate.validator(other_application)

        applications = app_mapping([
            ('/my/service', validated_application),
            ('/my/other_service', other_validated_application),
        ])

        server = simple_server.make_server('localhost', port, applications)
        server = webapp_test_util.ServerThread(server)
        server.start()
        server.wait_until_running()
        return server, application
コード例 #35
0
def main():
    try:
        from wsgiref.simple_server import make_server
        from wsgiref.validate import validator
        if port[0] == 0:
            port[0] = get_open_port()

        wsgi_application = WsgiApplication(soap11_application)
        server = make_server(host, port[0], validator(wsgi_application))

        logger.info('Starting interop server at %s:%s.' % ('0.0.0.0', port[0]))
        logger.info('WSDL is at: /?wsdl')
        server.serve_forever()

    except ImportError:
        print("Error: example server code requires Python >= 2.5")
コード例 #36
0
    def get_app(self, app=None):
        """Obtain a new (decorated) WSGI app to hook into the origin server."""
        if app is None:
            app = cherrypy.tree

        if self.validate:
            try:
                from wsgiref import validate
            except ImportError:
                warnings.warn(
                    'Error importing wsgiref. The validator will not run.')
            else:
                # wraps the app in the validator
                app = validate.validator(app)

        return app
コード例 #37
0
def run(filepath, wsgiapp, host, port, reload, interval, static, static_root,
        static_dirs, lineprof, lineprof_file, validate):
    """
    Runs a development server for WSGI Application.

    Usage:

        $ wsgicli run hello.py app -h 0.0.0.0 -p 5000

        $ wsgicli run hello.py app --reload

        $ wsgicli run hello.py app --static --static-root /static/ --static-dirs ./static/

        $ wsgicli run hello.py app --lineprof
    """
    module = SourceFileLoader('module', filepath).load_module()
    app = getattr(module, wsgiapp)

    if static:
        from wsgi_static_middleware import StaticMiddleware
        app = StaticMiddleware(app,
                               static_root=static_root,
                               static_dirs=static_dirs)

    if validate:
        from wsgiref.validate import validator
        app = validator(app)

    if lineprof:
        # Caution: wsgi-lineprof is still pre-alpha. Except breaking API Changes.
        from wsgi_lineprof.middleware import LineProfilerMiddleware
        from wsgi_lineprof.filters import FilenameFilter, TotalTimeSorter

        if lineprof_file:
            # Now wsgi-lineprof is now supported only 1 file checking.
            lineprof_file = lineprof_file[0]
        else:
            lineprof_file = filepath.split(
                '/')[-1] if '/' in filepath else filepath
        filters = [FilenameFilter(lineprof_file), TotalTimeSorter()]
        app = LineProfilerMiddleware(app, filters=filters)

    if reload:
        run_live_reloading_server(interval, app=app, host=host, port=port)
    else:
        run_server(app=app, host=host, port=port)
コード例 #38
0
    def get_fps(self, device_id, package_name):
        """

        :param device_id:
        :param package_name:
        :return: 60
        """
        _adb = "adb -s %s shell dumpsys gfxinfo %s" % (device_id, package_name)
        results = os.popen(_adb).read().strip()
        frames = [x for x in results.split('\n') if validator(x)]
        frame_count = len(frames)
        jank_count = 0
        vsync_overtime = 0
        render_time = 0
        for frame in frames:
            time_block = re.split(r'\s+', frame.strip())
            if len(time_block) == 3:
                try:
                    render_time = float(time_block[0]) + float(
                        time_block[1]) + float(time_block[2])
                except Exception as e:
                    render_time = 0
            '''
            当渲染时间大于16.67,按照垂直同步机制,该帧就已经渲染超时
            那么,如果它正好是16.67的整数倍,比如66.68,则它花费了4个垂直同步脉冲,减去本身需要一个,则超时3个
            如果它不是16.67的整数倍,比如67,那么它花费的垂直同步脉冲应向上取整,即5个,减去本身需要一个,即超时4个,可直接算向下取整

            最后的计算方法思路:
            执行一次命令,总共收集到了m帧(理想情况下m=128),但是这m帧里面有些帧渲染超过了16.67毫秒,算一次jank,一旦jank,
            需要用掉额外的垂直同步脉冲。其他的就算没有超过16.67,也按一个脉冲时间来算(理想情况下,一个脉冲就可以渲染完一帧)

            所以FPS的算法可以变为:
            m / (m + 额外的垂直同步脉冲) * 60
            '''
            if render_time > 16.67:
                jank_count += 1
                if render_time % 16.67 == 0:
                    vsync_overtime += int(render_time / 16.67) - 1
                else:
                    vsync_overtime += int(render_time / 16.67)

        _fps = int(frame_count * 60 / (frame_count + vsync_overtime))
        # writeInfo(_fps, PATH("../info/" + devices + "_fps.pickle"))

        # return (frame_count, jank_count, fps)
        return _fps
コード例 #39
0
    def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello world!")

        class PathQuotingHandler(RequestHandler):
            def get(self, path):
                self.write(path)

        # It would be better to run the wsgiref server implementation in
        # another thread instead of using our own WSGIContainer, but this
        # fits better in our async testing framework and the wsgiref
        # validator should keep us honest
        return WSGIContainer(validator(WSGIApplication([
                        ("/", HelloHandler),
                        ("/path/(.*)", PathQuotingHandler),
                        ])))
コード例 #40
0
    def test_bytes_validation(self):
        def app(e, s):
            s("200 OK", [
                ("Content-Type", "text/plain; charset=utf-8"),
                ("Date", "Wed, 24 Dec 2008 13:29:32 GMT"),
            ])
            return [b"data"]

        out, err = run_amock(validator(app))
        self.assertTrue(err.endswith('"GET / HTTP/1.0" 200 4\n'))
        ver = sys.version.split()[0].encode('ascii')
        self.assertEqual(
            b"HTTP/1.0 200 OK\r\n"
            b"Server: WSGIServer/0.2 Python/" + ver + b"\r\n"
            b"Content-Type: text/plain; charset=utf-8\r\n"
            b"Date: Wed, 24 Dec 2008 13:29:32 GMT\r\n"
            b"\r\n"
            b"data", out)
コード例 #41
0
def get_fps(pkg_name, devices):
    _adb = "adb -s " + devices + " shell dumpsys gfxinfo %s" % pkg_name
    print(_adb)
    results = os.popen(_adb).read().strip()
    frames = [x for x in results.split('\n') if validator(x)]
    frame_count = len(frames)
    jank_count = 0
    vsync_overtime = 0
    render_time = 0
    for frame in frames:
        time_block = re.split(r'\s+', frame.strip())
        if len(time_block) == 3:
            try:
                render_time = float(time_block[0]) + float(
                    time_block[1]) + float(time_block[2])
            except Exception as e:
                render_time = 0
        '''
        当渲染时间大于16.67,按照垂直同步机制,该帧就已经渲染超时
        那么,如果它正好是16.67的整数倍,比如66.68,则它花费了4个垂直同步脉冲,减去本身需要一个,则超时3个
        如果它不是16.67的整数倍,比如67,那么它花费的垂直同步脉冲应向上取整,即5个,减去本身需要一个,即超时4个,可直接算向下取整

        最后的计算方法思路:
        执行一次命令,总共收集到了m帧(理想情况下m=128),但是这m帧里面有些帧渲染超过了16.67毫秒,算一次jank,一旦jank,
        需要用掉额外的垂直同步脉冲。其他的就算没有超过16.67,也按一个脉冲时间来算(理想情况下,一个脉冲就可以渲染完一帧)

        所以FPS的算法可以变为:
        m / (m + 额外的垂直同步脉冲) * 60
        '''
        if render_time > 16.67:
            jank_count += 1
            if render_time % 16.67 == 0:
                vsync_overtime += int(render_time / 16.67) - 1
            else:
                vsync_overtime += int(render_time / 16.67)

    _fps = int(frame_count * 60 / (frame_count + vsync_overtime))
    # if ':'in devices:
    #     devices=devices.replace(':',' ')

    # return (frame_count, jank_count, fps)
    print("-----fps------")
    print(_fps)
    return _fps
コード例 #42
0
def run_server(application, *, validate=True, **kwargs):
    with debug_loop() as loop:
        # Add a WSGI validator.
        if validate:
            application = validator(application)
        # Configure the server.
        server_config = {
            "host": "127.0.0.1",
            "port": 0,
            "loop": loop,
        }
        server_config.update(**kwargs)
        # Create the server.
        server, app = configure_server(application, **server_config)
        server_port = server.sockets[0].getsockname()[1]
        try:
            yield TestClient(server, app, server_port, loop=loop)
        finally:
            close_server(server, app, loop=loop)
コード例 #43
0
    def test_cp1252_url(self):
        def app(e, s):
            s("200 OK", [
                ("Content-Type", "text/plain"),
                ("Date", "Wed, 24 Dec 2008 13:29:32 GMT"),
            ])
            # PEP3333 says environ variables are decoded as latin1.
            # Encode as latin1 to get original bytes
            return [e["PATH_INFO"].encode("latin1")]

        out, err = run_amock(validator(app), data=b"GET /\x80%80 HTTP/1.0")
        self.assertEqual([
            b"HTTP/1.0 200 OK",
            mock.ANY,
            b"Content-Type: text/plain",
            b"Date: Wed, 24 Dec 2008 13:29:32 GMT",
            b"",
            b"/\x80\x80",
        ], out.splitlines())
コード例 #44
0
ファイル: test_http.py プロジェクト: harshil07/spyne
    def test_cookie_parse(self):
        STR = 'some_string'

        class RequestHeader(ComplexModel):
            some_field = String

        class SomeService(ServiceBase):
            __in_header__ = RequestHeader

            @rpc(String)
            def some_call(ctx, s):
                assert ctx.in_header.some_field == STR

        def start_response(code, headers):
            assert code == HTTP_200

        c = SimpleCookie()
        c['some_field'] = STR

        ''.join(
            validator(
                WsgiApplication(
                    Application(
                        [SomeService],
                        'tns',
                        in_protocol=HttpRpc(parse_cookie=True),
                        out_protocol=HttpRpc())))({
                            'SCRIPT_NAME': '',
                            'QUERY_STRING': '',
                            'PATH_INFO': '/some_call',
                            'REQUEST_METHOD': 'GET',
                            'SERVER_NAME': 'localhost',
                            'SERVER_PORT': "9999",
                            'HTTP_COOKIE': str(c),
                            'wsgi.url_scheme': 'http',
                            'wsgi.version': (1, 0),
                            'wsgi.input': StringIO(),
                            'wsgi.errors': StringIO(),
                            'wsgi.multithread': False,
                            'wsgi.multiprocess': False,
                            'wsgi.run_once': True,
                        }, start_response))
コード例 #45
0
    def setUp(self):
        io = StringIO.StringIO()
        sys.stdout = io

        self.application = validate.validator(server_config.server_normal)

        # 準備データの投稿.
        app = webtest.TestApp(self.application)
        self.condition = [
                {'id': '', 'title': 'ready_post1', 'content': 'ready_post1'},
                {'id': '', 'title': 'ready_post2', 'content': 'ready_post2'}]

        for dic in self.condition:
            response = app.post('/', params='a=post&p=3&delkey=0000&name=WebTest&title={0}&content={1}'.format(dic['title'], dic['content']))
            self.assertEqual('301 Moved Permanently', response.status)
            redirect_response = response.follow()
            self.assertEqual('200 OK', redirect_response.status)
            pattern = r'<a href="/\?id=([0-9a-zA-Z]+)">{0}</a>'.format(dic['title'])
            dic['id'] = re.search(pattern, redirect_response.body).group(1)
            self.assertTrue(len(dic['id']) == 24)
コード例 #46
0
def get_fps(dev_obj, pkg_name):
	results = dev_obj.shell(f"dumpsys gfxinfo {pkg_name}")
	# print(results)
	frames = [x for x in results.split('\n') if validator(x)]
	frame_count = len(frames)
	jank_count = 0
	vsync_overtime = 0
	render_time = 0
	for frame in frames:
		time_block = re.split(r'\s+', frame.strip())
		if len(time_block) == 3:
			try:
				render_time = float(time_block[0]) + float(time_block[1]) + float(time_block[2])
			except Exception as e:
				render_time = 0

		'''
		当渲染时间大于16.67,按照垂直同步机制,该帧就已经渲染超时
		那么,如果它正好是16.67的整数倍,比如66.68,则它花费了4个垂直同步脉冲,减去本身需要一个,则超时3个
		如果它不是16.67的整数倍,比如67,那么它花费的垂直同步脉冲应向上取整,即5个,减去本身需要一个,即超时4个,可直接算向下取整

		最后的计算方法思路:
		执行一次命令,总共收集到了m帧(理想情况下m=128),但是这m帧里面有些帧渲染超过了16.67毫秒,算一次jank,一旦jank,
		需要用掉额外的垂直同步脉冲。其他的就算没有超过16.67,也按一个脉冲时间来算(理想情况下,一个脉冲就可以渲染完一帧)

		所以FPS的算法可以变为:
		m / (m + 额外的垂直同步脉冲) * 60
		'''
		if render_time > 16.67:
			jank_count += 1
			if render_time % 16.67 == 0:
				vsync_overtime += int(render_time / 16.67) - 1
			else:
				vsync_overtime += int(render_time / 16.67)

	_fps = int(frame_count * 60 / (frame_count + vsync_overtime))
	writeInfo(_fps, PATH(f"../info/{dev_obj.uuid}_fps.pickle"))

	# return (frame_count, jank_count, fps)
	print("-----fps------")
	print(_fps)
コード例 #47
0
    def test_functional(self):
        app = validator(CleaverWebUI(SampleBackend()))

        environ = {}
        setup_testing_defaults(environ)

        environ['PATH_INFO'] = '/'
        environ['REQUEST_METHOD'] = 'GET'
        environ['QUERY_STRING'] = ''

        result = {}

        def start_response(status, headers):
            result['status'] = status

        resp = app(environ, start_response)
        assert result['status'] == '200 OK'

        if hasattr(resp, 'close'):
            resp.close()
            del resp
コード例 #48
0
ファイル: endpointstest.py プロジェクト: dindinet/titan
    def _StartWebServer(self, port, application=None):
        """Start web server.

    Args:
      port: Port to start application on.
      application: Optional WSGI function.  If none provided will use
        tests CreateWsgiApplication method.

    Returns:
      A tuple (server, application):
        server: An instance of ServerThread.
        application: Application that web server responds with.
    """
        if not application:
            application = self.CreateWsgiApplication()
        validated_application = validate.validator(application)
        server = simple_server.make_server('localhost', port,
                                           validated_application)
        server = ServerThread(server)
        server.start()
        return server, application
コード例 #49
0
 def get_app(self):
     """Obtain a new (decorated) WSGI app to hook into the origin server."""
     import cherrypy
     app = cherrypy.tree
     if self.profile:
         app = profiler.make_app(app, aggregate=False)
     if self.conquer:
         try:
             import wsgiconq
         except ImportError:
             warnings.warn("Error importing wsgiconq. pyconquer will not run.")
         else:
             app = wsgiconq.WSGILogger(app, c_calls=True)
     if self.validate:
         try:
             from wsgiref import validate
         except ImportError:
             warnings.warn("Error importing wsgiref. The validator will not run.")
         else:
             app = validate.validator(app)
     
     return app
コード例 #50
0
ファイル: dvbbc.py プロジェクト: f1vefour/dvbbc
def main():
  """Run the show"""
  global cur_chan
  channels.update(set(
    l.split(':')[0] for l in open(CHAN_PATH, 'r')
  ))
  cur_chan = list(channels)[0]

  feed_thread = threading.Thread(target=feeder)
  feed_thread.daemon = True
  feed_thread.start()

  validator_app = validator(simple_app)
  httpd = make_server(
    '', 80, validator_app,
    server_class=ThreadedWSGIServer
  )
  try:
    httpd.serve_forever()
  finally:
    cur_chan = None
    feed_thread.join()
コード例 #51
0
ファイル: helper.py プロジェクト: connoryang/1v1dec
    def get_app(self, app=None):
        if app is None:
            app = cherrypy.tree
        if self.conquer:
            try:
                import wsgiconq
            except ImportError:
                warnings.warn(
                    'Error importing wsgiconq. pyconquer will not run.')
            else:
                app = wsgiconq.WSGILogger(app, c_calls=True)

        if self.validate:
            try:
                from wsgiref import validate
            except ImportError:
                warnings.warn(
                    'Error importing wsgiref. The validator will not run.')
            else:
                app = validate.validator(app)

        return app
コード例 #52
0
ファイル: GetFPS.py プロジェクト: xinxi1990/MyMonkey
    def getfps(self,activity):
        '''
        计算fps,写入文件
        :return:
        '''
        global fps
        try:
            cmd = "adb -s %s shell dumpsys gfxinfo %s" % (self.dev,self.db.packagename)
            logger.log_debug(cmd)

            result = os.popen(cmd).read().strip()

            frames = [x for x in result.split('\n') if validator(x)]
            frame_count = len(frames)
            jank_count = 0
            vsync_overtime = 0
            render_time = 0

            for frame in frames:
                time_block = re.split(r'\s+', frame.strip())
                if len(time_block) == 3:
                    try:
                        render_time = float(time_block[0]) + float(time_block[1]) + float(time_block[2])
                    except Exception as e:
                        render_time = 0

                if render_time > 16.67:
                    jank_count += 1
                    if render_time % 16.67 == 0:
                        vsync_overtime += int(render_time / 16.67) - 1
                    else:
                        vsync_overtime += int(render_time / 16.67)
            fps = int(frame_count * 60 / (frame_count + vsync_overtime))


        except Exception, e:
            logger.log_error("获取fps失败:" + str(e))
            fps = 0
コード例 #53
0
    def get_app(self, app=None):
        """Obtain a new (decorated) WSGI app to hook into the origin server."""
        if app is None:
            app = cherrypy.tree
        if self.conquer:
            try:
                import wsgiconq
            except ImportError:
                warnings.warn(
                    'Error importing wsgiconq. pyconquer will not run.')
            else:
                app = wsgiconq.WSGILogger(app, c_calls=True)

        if self.validate:
            try:
                from wsgiref import validate
            except ImportError:
                warnings.warn(
                    'Error importing wsgiref. The validator will not run.')
            else:
                app = validate.validator(app)

        return app
コード例 #54
0
ファイル: test.py プロジェクト: Victorm0612/Pruebas
    def request(self, method, path, environ=None, **kw):
        """Send a request to the application under test.

        The environment will be populated with some default keys. Additional
        keyword arguments will be interpreted as request headers.

        For example, passing x_foo=1 will add a request header "X-Foo: 1".
        """
        if environ is None:
            environ = {}
        # setup_testing_defaults() uses '127.0.0.1', but localhost is easier
        # to type when testing.
        environ.setdefault('SERVER_NAME', 'localhost')
        environ.setdefault('QUERY_STRING', '')  # silence validator warning
        setup_testing_defaults(environ)
        environ['REQUEST_METHOD'] = method
        environ['PATH_INFO'] = path
        for k, v in kw.items():
            key = k.upper()
            if key not in ('CONTENT_TYPE', 'CONTENT_LENGTH'):
                key = 'HTTP_' + key
            environ[key] = str(v)
        start_response_rv = []

        def start_response(status, headers, exc_info=None):
            # TODO handle exc_info != None
            start_response_rv.extend([status, headers])

        wsgi_app = validator(self.app)
        app_iter = wsgi_app(environ, start_response)
        try:
            body = ''.join(app_iter)
        finally:
            if hasattr(app_iter, 'close'):
                app_iter.close()
        statusline, headerlist = start_response_rv
        return wsgi_response(statusline, Headers(headerlist), body)
コード例 #55
0
    def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape( ` environ[name] `))

        form = cgi.FieldStorage(fp=environ['wsgi.input'],
                                environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (field.name,
                                                         field.value)

        yield '</table>\n' \
              '</body></html>\n'

    from wsgiref import validate
    test_app = validate.validator(test_app)
    WSGIServer(test_app, loggingLevel=logging.DEBUG).run()
コード例 #56
0
 def _makeOne(self, app, *arg, **kw):
     from wsgiref.validate import validator
     rhs = validator(app)
     retry = self._getTargetClass()(rhs, *arg, **kw)
     lhs = validator(retry)
     return lhs
コード例 #57
0
 def test_validated_hello(self):
     out, err = run_amock(validator(hello_app))
     # the middleware doesn't support len(), so content-length isn't there
     self.check_hello(out, has_length=False)
コード例 #58
0
 def test_app(environ, start_response):
     if environ.get('CONTENT_LENGTH', None) in (-1, '-1'):
         del environ['CONTENT_LENGTH']
     return validator(hello_app)(environ, start_response)
コード例 #59
0
ファイル: test_wsgi.py プロジェクト: funnydman/toxic
from wsgiref.simple_server import make_server
from wsgiref.validate import validator


# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
    status = '200 OK'  # HTTP Status
    headers = [('Content-type', 'text/plain')]  # HTTP Headers
    start_response(status, headers)

    # This is going to break because we need to return a list, and
    # the validator is going to inform us
    return b"Hello World"


# This is the application wrapped in a validator
validator_app = validator(simple_app)

with make_server('', 8020, validator_app) as httpd:
    print("Listening on port 8000....")
    httpd.serve_forever()
コード例 #60
0
 def get_app(self):
     self.app = WSGIApplication(self.get_handlers(), **self.get_app_kwargs())
     return WSGIContainer(validator(self.app))