コード例 #1
0
def main():
    """
    Create a WSGIGateway application and serve it.
    """
    # register class on the AMF namespace so that it is passed marshaled
    register_classes()

    # use a dict in leiu of sqlite or an actual database to store users
    # re passwords: plain-text in a production would be bad
    users = {
        'lenards': User('lenards', 'f00f00', '*****@*****.**'),
        'lisa': User('lisa', 'h1k3r', '*****@*****.**'),
    }

    # our gateway will have two services
    services = {
        'echo': EchoService,
        'user': UserService(users)
    }

    # setup our server
    application = WSGIGateway(services, logger=logging)
    httpd = simple_server.WSGIServer(host_info,
                simple_server.WSGIRequestHandler)
    httpd.set_app(application)
    
    try:
        # open for business
        print "Running Simple PyAMF gateway on http://%s:%d" % (
            host_info[0], host_info[1])
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
コード例 #2
0
ファイル: __init__.py プロジェクト: rdoh/soledad
 def make_server(host_port, application):
     assert application, "forgot to override make_app(_with_state)?"
     srv = simple_server.WSGIServer(host_port, _RequestHandler)
     # patch the value in if it's None
     if getattr(application, 'base_url', 1) is None:
         application.base_url = "http://%s:%s" % srv.server_address
     srv.set_app(application)
     return srv
コード例 #3
0
def before_all(context):
    context.server = simple_server.WSGIServer(("", 5000), WSGIRequestHandler)
    context.server.set_app(app)
    context.pa_app = threading.Thread(target=context.server.serve_forever)
    context.pa_app.start()

    context.browser = webdriver.Chrome(options=chrome_options, executable_path=CHROME_DRIVER)
    context.browser.set_page_load_timeout(time_to_wait=200)
コード例 #4
0
 def make_server(host_port, handler, state):
     app = http_app.HTTPApp(state)
     application = oauth_middleware.OAuthMiddleware(app, None)
     application.get_oauth_data_store = lambda: tests.testingOAuthStore
     srv = simple_server.WSGIServer(host_port, handler)
     # patch the value in
     application.base_url = "http://%s:%s" % srv.server_address
     srv.set_app(application)
     return srv
コード例 #5
0
 def make_server(host_port, handler, state):
     application = http_app.HTTPApp(state)
     srv = simple_server.WSGIServer(host_port, handler)
     srv.set_app(application)
     #srv = httpserver.WSGIServerBase(application,
     #                                host_port,
     #                                handler
     #                                )
     return srv
コード例 #6
0
def before_all(context):
    context.server = simple_server.WSGIServer(("", 5000), WSGIRequestHandler)
    app = create_app(os.getenv('APP_CONFIG') or 'testing')
    context.server.set_app(app)
    context.pa_app = threading.Thread(target=context.server.serve_forever)
    context.pa_app.start()

    context.browser = webdriver.Chrome(options=chrome_options)
    context.browser.set_page_load_timeout(time_to_wait=200)
コード例 #7
0
ファイル: serve_webapps.py プロジェクト: writefaruq/zamboni
def main():
    p = optparse.OptionParser(usage="%prog\n\n" + __doc__)
    p.add_option("--port", help="Port to run server on.  Default: %default",
                 default=8090, type=int)
    (options, args) = p.parse_args()
    logging.basicConfig(level=logging.DEBUG,
                        format='[%(asctime)s] %(message)s')
    log.info("starting webserver at http://localhost:%s/", options.port)
    httpd = simple_server.WSGIServer(('', options.port),
                                     simple_server.WSGIRequestHandler)
    httpd.set_app(fileapp)
    httpd.serve_forever()
コード例 #8
0
def run_server(options):
    from wsgiref import simple_server

    httpd = simple_server.WSGIServer(
        (options.iface, options.port),
        simple_server.WSGIRequestHandler,
    )

    httpd.set_app(get_app(options))

    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
コード例 #9
0
ファイル: wsgirunner.py プロジェクト: Python3pkg/PyModel
def main():
    (options, args) = parse_args()
    if not args:
        print_help()
        exit()
    app_module = args[0]
    app = __import__(app_module)
    application = app.application
    print("Running %s at http://localhost:%s/" \
        % (app_module, options.port))
    httpd = simple_server.WSGIServer(('', options.port),
                                     simple_server.WSGIRequestHandler)
    httpd.set_app(application)
    httpd.serve_forever()
コード例 #10
0
 def run(config, *args, **kwargs):
     try:
         self.httpd = simple_server.WSGIServer((interface, port),
                                               handler_cls)
         self.httpd.set_app(app)
     except Exception as exc:
         start_flag.put(False)
         start_flag.put(exc)
         raise
     else:
         start_flag.put(True)
     try:
         self.httpd.serve_forever()
     finally:
         self.httpd.server_close()
コード例 #11
0
def run(config):
    config.check_writeable_uid_directory(config.appdatahome)

    port = config['port'] or 8080
    interface = config['interface']

    app = CubicWebWSGIApplication(config)
    handler_cls = simple_server.WSGIRequestHandler
    httpd = simple_server.WSGIServer((interface, port), handler_cls)
    httpd.set_app(app)
    repo = app.appli.repo
    try:
        LOGGER.info('starting http server on %s', config['base-url'])
        httpd.serve_forever()
    finally:
        repo.shutdown()
コード例 #12
0
def before_all(context):
    print("Executing before all")
    context.app = create_app('testing')
    context.app_context = context.app.app_context()
    context.app_context.push()
    db.drop_all()
    db.create_all()
    context.server = simple_server.WSGIServer(("", 5000), WSGIRequestHandler)
    context.server.set_app(context.app)
    context.pa_app = threading.Thread(target=context.server.serve_forever)
    context.pa_app.start()
    context.url = "http://localhost:5000"
    context.client = context.app.test_client(use_cookies=True)
    context.browser = webdriver.Chrome('dependencies/chromedriver')
    context.browser.maximize_window()
    context.browser.implicitly_wait(20)
コード例 #13
0
def run(port=9991):
    """Start WSGI server."""

    from wsgiref import simple_server
    httpd = simple_server.WSGIServer(
        ('', port),
        simple_server.WSGIRequestHandler,
    )
    httpd.set_app(server)
    try:
        print "Starting server. Point your web browser to 'http://127.0.0.1:%s'." % port
        httpd.serve_forever()
    except KeyboardInterrupt:
        if options.concatenate: os.remove(options.concatmapfile)
        print "Shutting down server."
        sys.exit(0)
コード例 #14
0
def before_all(context):
    context.server = simple_server.WSGIServer(
        ("", 7777), WSGIRequestHandler)  #create WSGIServer instance
    context.server.set_app(
        app)  #set the app that will be called on getting requests
    context.appthread = threading.Thread(
        target=context.server.serve_forever
    )  #create thread to call the function server_forever()
    context.appthread.start()  #start the thread

    context.service = Service(
        "./applications/geckodriver")  #include the geckodriver
    context.browser = webdriver.Firefox(
        service=context.service)  #initiate the firefox browser object
    context.browser.set_page_load_timeout(
        5000)  #set the time out of the browser
コード例 #15
0
def run(port=8080, threading=False, config=None):
    from wsgiref import simple_server
    if threading:
        from SocketServer import ThreadingMixIn

        class myServer(ThreadingMixIn, simple_server.WSGIServer):
            pass
        httpd = myServer(('', port), simple_server.WSGIRequestHandler,)
    else:
        httpd = simple_server.WSGIServer(
            ('', port), simple_server.WSGIRequestHandler,
            )
    httpd.set_app(wsgiApp)
    try:
        print "Listening on port %s" % port
        httpd.serve_forever()
    except KeyboardInterrupt:
        print "Shutting down."
コード例 #16
0
def before_all(context):
    app.config.update(
        SECRET_KEY=
        '\x1fSU\xe5\xb2.F\x03\xacm\x9fy-\x04\xbb0\xa8\xf0\x96q\x94\xbb\xb0n',
        SQLALCHEMY_DATABASE_URI=
        'mysql+pymysql://root:[email protected]:3306/tesop_test',
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
    )
    with app.app_context():
        reset_db(
            os.path.join(
                os.path.join(os.path.dirname(__file__), 'test_data.json')))
    context.server = simple_server.WSGIServer(("", 5000), WSGIRequestHandler)
    context.server.set_app(app)
    context.pa_app = threading.Thread(target=context.server.serve_forever)
    context.pa_app.start()
    context.browser = webdriver.Chrome(options=chrome_options,
                                       executable_path=CHROME_DRIVER)
    context.browser.set_page_load_timeout(time_to_wait=200)
コード例 #17
0
def before_all(context):
    """
    before all tests are started a setup for the test context is needed:
        - run http server
        - setup navigation helpers
        - setup selenium webdriver
    """
    use_fixture(fixture_database_setup, context)

    context.port = random.randint(5000, 5500)
    context.server = simple_server.WSGIServer(("0.0.0.0", context.port), \
                                               simple_server.WSGIRequestHandler)
    context.server.set_app(app)
    context.pa_app = threading.Thread(target=context.server.serve_forever)
    context.pa_app.start()

    context.route = NavigationHelpers(base_url=("http://127.0.0.1:%d" %
                                                context.port))
    context.browser = get_browser_driver()
コード例 #18
0
ファイル: test_wsgiext.py プロジェクト: zeph/temper-exporter
def test_SilentRequestHandler(capsys, status, expected):
    s = simple_server.WSGIServer(('', 0), SRH)
    s.set_app(functools.partial(app, status))
    t = threading.Thread(target=functools.partial(s.serve_forever,
                                                  poll_interval=0.1),
                         daemon=True)
    t.start()

    try:
        with request.urlopen('http://{}:{}/'.format(*s.server_address)) as r:
            pass
    except error.HTTPError as e:
        pass

    s.shutdown()
    t.join()
    s.server_close()

    out, err = capsys.readouterr()
    assert err == expected
コード例 #19
0
def main():
    global document_root
    p = optparse.OptionParser(usage="%prog")
    p.add_option("--port",
                 help="Port to run server on.  Default: %default",
                 default=8090,
                 type=int)
    p.add_option(
        "--directory",
        help="Directory to serve files from. Defaults to working directory.",
        default=os.getcwd())
    (options, args) = p.parse_args()
    document_root = options.directory
    logging.basicConfig(level=logging.DEBUG,
                        format='[%(asctime)s] %(message)s')
    log.info("starting test server on port %s", options.port)
    log.info("serving files in %s", options.directory)
    httpd = simple_server.WSGIServer(('', options.port),
                                     simple_server.WSGIRequestHandler)
    httpd.set_app(fileapp)
    httpd.serve_forever()
コード例 #20
0
ファイル: agent.py プロジェクト: knitmesh/ironic-python-agent
    def serve_ipa_api(self):
        """Serve the API until an extension terminates it."""
        if netutils.is_ipv6_enabled():
            # Listens to both IP versions, assuming IPV6_V6ONLY isn't enabled,
            # (the default behaviour in linux)
            simple_server.WSGIServer.address_family = socket.AF_INET6
        server = simple_server.WSGIServer((self.listen_address.hostname,
                                           self.listen_address.port),
                                          simple_server.WSGIRequestHandler)
        server.set_app(self.api)

        if not self.standalone and self.api_url:
            # Don't start heartbeating until the server is listening
            self.heartbeater.start()

        while self.serve_api:
            try:
                server.handle_request()
            except BaseException as e:
                msg = "Failed due to an unknown exception. Error %s" % e
                LOG.exception(msg)
                raise errors.IronicAPIError(msg)
        LOG.info('shutting down')
コード例 #21
0
ファイル: server.py プロジェクト: Coding-Squad/givabit
    parser = OptionParser()
    parser.add_option("-p",
                      "--port",
                      default=8000,
                      dest="port",
                      help="port number [default: %default]")
    parser.add_option("--host",
                      default="localhost",
                      dest="host",
                      help="host address [default: %default]")
    (options, args) = parser.parse_args()

    port = int(options.port)

    httpd = simple_server.WSGIServer(
        (options.host, port),
        simple_server.WSGIRequestHandler,
    )

    def app(environ, start_response):
        if environ['PATH_INFO'] == '/crossdomain.xml':
            fn = os.path.join(os.getcwd(), os.path.dirname(__file__),
                              'crossdomain.xml')

            fp = open(fn, 'rt')
            buffer = fp.readlines()
            fp.close()

            start_response('200 OK',
                           [('Content-Type', 'application/xml'),
                            ('Content-Length', str(len(''.join(buffer))))])
コード例 #22
0
ファイル: wsgi_server.py プロジェクト: rwarren/amfast
                      dest="port",
                      help="port number to serve")
    parser.add_option("-d",
                      default="localhost",
                      dest="domain",
                      help="domain to serve")
    parser.add_option("-l",
                      action="store_true",
                      dest="log_debug",
                      help="log debugging output")
    (options, args) = parser.parse_args()

    amfast.log_debug = options.log_debug

    channel_set = WsgiChannelSet()
    rpc_channel = WsgiChannel('amf')
    channel_set.mapChannel(rpc_channel)
    utils.setup_channel_set(channel_set)

    server = simple_server.WSGIServer((options.domain, int(options.port)),
                                      simple_server.WSGIRequestHandler)

    server.set_app(channel_set)

    try:
        print "Serving on %s:%s" % (options.domain, options.port)
        print "Press ctrl-c to halt."
        server.serve_forever()
    except KeyboardInterrupt:
        pass
コード例 #23
0
    '''
    Перенаправляет запросы по строке после доменного имени.
    Хранит информацию о времени изменения модуля и делает повторный импорт, если модуль
    из словаря modules был изменён.
    '''
    environ['server_start_time'] = server_start_time
    dw = re.search('^\/([^/]+)?', environ['PATH_INFO']).group(1) or 'mu'
    if dw in modules:
        start_response('200 OK', [('Content-type', 'text/html')]) if dw!='static' else start_response('200 OK', [('Content-type', 'text/css')])
        f1, filename1, desc1 = imp.find_module('apps')
        apps_module = imp.load_module('apps', f1, filename1, desc1)
        f2, filename2, desc2 = imp.find_module(dw,apps_module.__path__)
        mtime = os.stat(filename2)[8]
        if mtime != modules[dw]['mtime']:
            modules[dw]['mtime'] = mtime
            module = imp.load_module(modules[dw]['name'], f2, filename2, desc2)
        else:
            module = sys.modules[dw]
        return module.main(environ, start_response)

    else:
        return ['Не понял задачи:-(<br>Проверьте адрес:{0}'.format(environ['PATH_INFO']).encode('utf-8')]


application = app
if __name__ == '__main__':
    server = simple_server.WSGIServer(('', 7070), simple_server.WSGIRequestHandler,)
    server.set_app(app)
    webbrowser.open('http://localhost:7070')
    server.serve_forever()
    
コード例 #24
0
    Just return data back to the client.
    """
    return data


services = {'echo': echo, 'echo.echo': echo}

if __name__ == '__main__':
    import os
    from pyamf.remoting.gateway.wsgi import WSGIGateway
    from wsgiref import simple_server

    gw = WSGIGateway(services)

    httpd = simple_server.WSGIServer(
        ('localhost', 8000),
        simple_server.WSGIRequestHandler,
    )

    def app(environ, start_response):
        if environ['PATH_INFO'] == '/crossdomain.xml':
            fn = os.path.join(os.getcwd(), os.path.dirname(__file__),
                              'crossdomain.xml')

            fp = open(fn, 'rt')
            buffer = fp.readlines()
            fp.close()

            start_response('200 OK',
                           [('Content-Type', 'application/xml'),
                            ('Content-Length', str(len(''.join(buffer))))])
コード例 #25
0
 def make_server(host_port, handler, state):
     srv = simple_server.WSGIServer(host_port, handler)
     srv.set_app(self.app)
     return srv
コード例 #26
0
ファイル: __main__.py プロジェクト: epochblue/feedify
from . import __version__ as version
from .handler import FeedifyHandler

feeds_file_cache = Path('.feeds')
if not feeds_file_cache.is_dir():
    feeds_file_cache.mkdir(0o755)

parser = argparse.ArgumentParser(description='feedify: a command line website-to-RSS application.')
parser.add_argument('--config', dest='config_file', type=str, default='config.json',
                    help='A user-supplied configuration file.')
parser.add_argument('--user_agent', dest='user_agent', type=str, default=f'feedify/{version}',
                    help='Provide a custom user-agent')
parser.add_argument('--debug', dest='debug', action='store_true',
                    help='Run feedify in debug mode.')
parser.add_argument('--version', action='version', version='feedify {}'.format(version))
args = parser.parse_args()

config = {}
config_path = Path(args.config_file).expanduser()
if config_path.exists():
    with open(config_path, 'rb') as f:
        config = json.load(f)

config.update({
    'debug': args.debug,
    'user_agent': args.user_agent
})

server = simple_server.WSGIServer(('', 8000), partial(FeedifyHandler, config))
server.serve_forever()
コード例 #27
0
ファイル: server.py プロジェクト: Coding-Squad/givabit
                      dest="host",
                      help="host address [default: %default]")
    (options, args) = parser.parse_args()

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

    host = options.host
    port = int(options.port)

    # Start server
    print "Running SQLAlchemy AMF gateway on http://%s:%d" % (host, port)
    print "Press Ctrl-c to stop server."

    server = simple_server.WSGIServer((host, port),
                                      simple_server.WSGIRequestHandler)
    gateway = WSGIGateway(mapped_services, logger=logging)

    def app(environ, start_response):
        if environ['PATH_INFO'] == '/crossdomain.xml':
            fn = os.path.join(os.getcwd(), os.path.dirname(__file__),
                              'crossdomain.xml')

            fp = open(fn, 'rt')
            buffer = fp.readlines()
            fp.close()

            start_response('200 OK',
                           [('Content-Type', 'application/xml'),
                            ('Content-Length', str(len(''.join(buffer))))])
コード例 #28
0
ファイル: server.py プロジェクト: digigroup25/mf
def main():
    """
    Create a WSGIGateway application and serve it.
    """
    # register class on the AMF namespace so that it is passed marshaled
    register_classes()

    # use a dict in leiu of sqlite or an actual database to store users
    # re passwords: plain-text in a production would be bad
    users = {
        'lenards': User('lenards', 'f00f00', '*****@*****.**'),
        'lisa': User('lisa', 'h1k3r', '*****@*****.**'),
    }
    testmap = """
<graph version="1.1">
 <node id="1">
    <data>
     <Task>
       <actualHours>NaN</actualHours>
       <assignedTo/>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>0</done>
       <estimatedHours>NaN</estimatedHours>
       <name>test</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
    <relations>
     <relation targetNodeId="2" type="child"/>
     <relation targetNodeId="3" type="child"/>
    </relations>
 </node>
 <node id="2">
    <data>
     <Task>
       <actualHours>0.1</actualHours>
       <assignedTo>V</assignedTo>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>1</done>
       <estimatedHours>0.2</estimatedHours>
       <name>task2</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
 </node>
 <node id="3">
    <data>
     <Task>
       <actualHours>NaN</actualHours>
       <assignedTo/>
       <committed>false</committed>
       <complexity>0</complexity>
       <date>null</date>
       <description/>
       <done>0</done>
       <estimatedHours>NaN</estimatedHours>
       <name>task3</name>
       <priority>0</priority>
       <reviewed>false</reviewed>
     </Task>
    </data>
 </node>
</graph>
"""
    maps = [
        Map('1', "first Map", "2012-01-16", testmap, 0, 0),
        Map('2', "second Map", "2012-01-16", testmap, 0, 0),
        Map('3', "third Map", "2012-01-16", testmap, 0, 0),
        Map('4', "forth Map", "2012-01-16", testmap, 0, 0),
    ]
    # our gateway will have two services
    services = {
        'echo': EchoService,
        'user': UserService(users),
        'map': MapService(maps)
    }

    # setup our server
    application = WSGIGateway(services, logger=logging)
    httpd = simple_server.WSGIServer(host_info,
                                     simple_server.WSGIRequestHandler)
    httpd.set_app(application)

    try:
        # open for business
        print "Running Simple PyAMF gateway on http://%s:%d" % (host_info[0],
                                                                host_info[1])
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
コード例 #29
0
    else:
        language_code = get_best_language(
            environ.get('HTTP_ACCEPT_LANGUAGE', 'en-US'))

    location = "{0}/{1}{2}".format(req.host_url, language_code, req.path_qs)

    start_response('302 Found',
                   [('Content-type', 'text/html; charset=utf-8'),
                    ('Cache-Control', 'private, s-maxage=0, max-age=604800'),
                    ('Vary', 'Accept-Language'), ('Location', location)])

    return ''


if __name__ == '__main__':
    # This runs when script is started directly from commandline.
    try:
        # Create a simple WSGI server and run the application.
        from wsgiref import simple_server
        print(
            "Running test application - point your browser at http://localhost:8000/ ..."
        )
        httpd = simple_server.WSGIServer(('', 8000),
                                         simple_server.WSGIRequestHandler)
        httpd.set_app(application)
        httpd.serve_forever()
    except ImportError:
        # wsgiref not installed, just output html to stdout
        for content in application({}, lambda status, headers: None):
            print(content)
コード例 #30
0
	        resp = redirect(environ)
		
	elif path.startswith("/test/"):
		resp = test_handler(environ)
	else:
		resp = error(environ, "Path not supported")
	
	start_response(resp["status"], resp["headers"])
	if resp.has_key("body"):
		return resp["body"]
	else:
		return ""


if __name__ == "__main__":
        #initialize the graph
	if not os.path.exists('message_board.db'):
		message_board_to_sioc.load_data('message_board.sql','message_board.db')

	serverlocation = server_addr + ":" + str(server_port)

        #change the MB namespace to the base URI for this server
	message_board_to_sioc.MB = Namespace("http://" + serverlocation + "/")
	sg=message_board_to_sioc.message_board_to_sioc('message_board.db')

	httpd=simple_server.WSGIServer((server_addr, server_port),simple_server.WSGIRequestHandler)
	httpd.set_app(application)
	print "Serving on: " + serverlocation + "..."
	httpd.serve_forever()