当前位置: 首页>>代码示例>>Python>>正文


Python server.Site类代码示例

本文整理汇总了Python中twisted.web.server.Site的典型用法代码示例。如果您正苦于以下问题:Python Site类的具体用法?Python Site怎么用?Python Site使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Site类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: startup

def startup():
	if not os.path.exists('data/firmware'):
		os.makedirs('data/firmware')
	if not os.path.exists('data/static'):
		os.makedirs('data/static')
	if not os.path.exists('data/cert'):
		os.makedirs('data/cert')
	# Check the certificate file
	host = getHost()
	validateCertHost('data/cert/key.pem', 'data/cert/cert.pem', 'data/static/thumb.txt', host)
	
	# Start up the HTTPS server
	web_port = 443
	root_handler = File('./data/static/')	
	firmware_handler = FirmwareHandler('data/firmware/')
	root_handler.putChild('firmware', firmware_handler)
	site = Site(root_handler)
	site.protocol = MyHttpChannel
	reactor.listenTCP(web_port, site)
	
	# Start up the HTTP server
	root_handler_http = File("./data/static/")
	config_handler = File("./config.html")
	root_handler_http.putChild('config.html', config_handler)
	site_http = Site(root_handler_http)
	reactor.listenTCP(8080, site_http)

	reactor.suggestThreadPoolSize(50)

	printStatus("Startup complete, running main loop...")

	# Run the main loop, this never returns:
	reactor.run()
开发者ID:jldeon,项目名称:OakSoftAP,代码行数:33,代码来源:oakupsrv.py

示例2: setup

def setup(args=None):
    """
    This is the main setup function to establish the TCP listening logic for
    the API server. This code also takes into account development or unit test mode.
    """

    # Setup API server
    api = ParadropAPIServer(reactor)
    api.putChild('internal', Base(apiinternal, allowNone=True))
    site = Site(api, timeout=None)

    # Development mode
    if(args and args.development):
        thePort = settings.PDFCD_PORT + 10000
        out.info('Using DEVELOPMENT variables')
        # Disable sending the error traceback to the client
        site.displayTracebacks = True
    elif(args and args.unittest):
        thePort = settings.PDFCD_PORT + 20000
        out.info('Running under unittest mode')
        site.displayTracebacks = True
    else:
        thePort = settings.PDFCD_PORT
        site.displayTracebacks = False
        initializeSystem()

    # Setup the port we listen on
    reactor.listenTCP(thePort, site)

    # Never return from here
    reactor.run()
开发者ID:SejalChauhan,项目名称:Paradrop,代码行数:31,代码来源:server.py

示例3: start

    def start(self):
        self.loadSites()

        ip = Utils.getIP()

        #define phishing sites
        for key in self.websites:
            self.phishingsites[key] = PhishingSite(self.config, key, self.websites[key]['path'], self.logpath, self.websites[key]['logfile'], self.websites[key]['redirecturl']).getResource()

        site_length = 0
        for key in self.phishingsites:
            if (len(key) > site_length):
                site_length = len(key)

        # if we are doing port based
        print
        for key in self.phishingsites:
            for port in range(self.MINPORT, self.MAXPORT):
                try:
                    site = Site(self.phishingsites[key], logPath=self.logpath + "/" + self.websites[key]['logfile']+".access")
                    site.logRequest = True
                    reactor.listenTCP(port, site)
                    print "Started website [%s] on [http://%s:%s]" % (('{:<%i}' % (site_length)).format(key), ip, port)
                    self.websites[key]['port'] = port
                    break
                except twisted.internet.error.CannotListenError, ex:
                    continue
开发者ID:BahtiyarB,项目名称:SPF,代码行数:27,代码来源:web.py

示例4: run_dev_server

def run_dev_server():
  global sender
  global ws_handler

  app.secret_key = "SECRET"
  app.debug = True

  ## create a Twisted Web resource for our WebSocket server
  wsFactory = BroadcastServerFactory(ws_url, debug=True, debugCodePaths=True)

  wsFactory.protocol = EchoServerProtocol
  wsFactory.setProtocolOptions(allowHixie76=True)

  wsResource = WebSocketResource(wsFactory)

  ## create a Twisted Web WSGI resource for our Flask server
  wsgiResource = WSGIResource(reactor, reactor.getThreadPool(), app)

  ## create a root resource serving everything via WSGI/Flask, but
  ## the path "/ws" served by our WebSocket stuff
  rootResource = WSGIRootResource(wsgiResource, {'ws': wsResource})

  ## create a Twisted Web Site and run everything
  site = Site(rootResource)
  site.protocol = HTTPChannelHixie76Aware

  sender = MessageSender(wsFactory)
  wsFactory.sender = sender
  ws_handler = wsFactory

  reactor.listenTCP(port, site)
  reactor.run()
开发者ID:Mononofu,项目名称:ZeroChat,代码行数:32,代码来源:main.py

示例5: _testRender

    def _testRender(self, uri, expectedURI):
        """
        Check that a request pointing at C{uri} produce a new proxy connection,
        with the path of this request pointing at C{expectedURI}.
        """
        root = Resource()
        reactor = MemoryReactor()
        resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor)
        root.putChild("index", resource)
        site = Site(root)

        transport = StringTransportWithDisconnection()
        channel = site.buildProtocol(None)
        channel.makeConnection(transport)
        # Clear the timeout if the tests failed
        self.addCleanup(channel.connectionLost, None)

        channel.dataReceived("GET %s HTTP/1.1\r\nAccept: text/html\r\n\r\n" % (uri,))

        # Check that one connection has been created, to the good host/port
        self.assertEquals(len(reactor.tcpClients), 1)
        self.assertEquals(reactor.tcpClients[0][0], "127.0.0.1")
        self.assertEquals(reactor.tcpClients[0][1], 1234)

        # Check the factory passed to the connect, and its given path
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEquals(factory.rest, expectedURI)
        self.assertEquals(factory.headers["host"], "127.0.0.1:1234")
开发者ID:twonds,项目名称:twisted,代码行数:29,代码来源:test_proxy.py

示例6: Service

def Service(options):
    consumer = QueueConsumer(
        consumer_queue=ns.MASTER_QUEUE,
        pool_size=ns.MAX_MESSAGES,
        spec_path=ns.SPEC_PATH,
        vhost=ns.RABBITMQ_VHOST,
        username=ns.RABBITMQ_USERNAME,
        password=ns.RABBITMQ_PASSWORD,
        host=ns.RABBITMQ_HOST,
        port=ns.RABBITMQ_PORT
        )

    publisher = QueuePublisher(
        declare_strategy=1,
        spec_path=ns.SPEC_PATH,
        vhost=ns.RABBITMQ_VHOST,
        username=ns.RABBITMQ_USERNAME,
        password=ns.RABBITMQ_PASSWORD,
        host=ns.RABBITMQ_HOST,
        port=ns.RABBITMQ_PORT
        )
    resource = MasterResource()
    resource.init(consumer, publisher)
    site = Site(resource)
    site.displayTracebacks = ns.DEBUG
    return internet.TCPServer(int(options['port']), site, \
        interface=options['iface'])
开发者ID:yunmanger1,项目名称:task-mapreduce,代码行数:27,代码来源:server_master.py

示例7: webServer

    def webServer(self):
        from twisted.web.server import Site
        from twisted.web import demo, static

        self.app = Site(demo.Test()).buildProtocol("lala")
        self.app = Site(static.File(os.path.abspath("."))).buildProtocol("lala")
        self.app.transport = self
开发者ID:ayourtch,项目名称:muXTCP,代码行数:7,代码来源:tcp.py

示例8: setUp

def setUp():
    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False
    try:
        import autobahn
        import twisted
    except ImportError:
        sys.exit("Install all dependencies")
    root = Resource()
    # root.putChild(constants.WEB_DYNAMIC_BRANCH, resource)
    from autobahn.twisted.resource import WebSocketResource, HTTPChannelHixie76Aware
    from twisted.web.server import Site

    factory = BroadcastServerFactory("ws://127.0.0.1:8888", debug=debug, debugCodePaths=debug)
    #если используется proxy
    #factory.proxy={'host': '192.168.200.105', 'port': '8088'}
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    ws_resource = WebSocketResource(factory)
    root.putChild("ws", ws_resource)
    site = Site(root)
    site.protocol = HTTPChannelHixie76Aware
    listenWS(factory)
    reactor.run()
开发者ID:yavalvas,项目名称:yav_com,代码行数:27,代码来源:canvas_server.py

示例9: __init__

 def __init__(self, core):
     thread_pool = ThreadPool()
     thread_pool.start()
     reactor.addSystemEventTrigger("after", "shutdown", thread_pool.stop)
     application = get_flask_application(core)
     wsgi_resource = WSGIResource(reactor, thread_pool, application)
     Site.__init__(self, wsgi_resource)
开发者ID:ojii,项目名称:ircbotframework,代码行数:7,代码来源:http.py

示例10: __init__

 def __init__(self, logger_name, config, resource, *args, **kwargs):
     Site.__init__(self, resource, *args, **kwargs)
     if config.captcha_ip_origin_is_x_forwarded:
         self._log_formatter = proxiedLogFormatter
     else:
         self._log_formatter = combinedLogFormatter
     self.access_logger = logging.getLogger(logger_name)
开发者ID:payingattention,项目名称:synapse,代码行数:7,代码来源:homeserver.py

示例11: __init__

 def __init__(self, uri, sites=None):
     with log.enter(obj=self) as tm:
         Site.__init__(self, None, timeout=60*60*30)
         self.uri = uri
         self.wsgi = None
         self.xmlrpc = None
         self._search_web_sites(sites)
开发者ID:TigerND,项目名称:dtx-core,代码行数:7,代码来源:site.py

示例12: WebServer

class WebServer(TCPApplication, _ConsumerMixin):
    """ Simple TCPApplication that act as a simple HTTP server """

    disconnecting = False  # Required by twisted
    connected = True
    disconnected = False

    def __init__(self):
        TCPApplication.__init__(self)
        _ConsumerMixin.__init__(self)
        self.app = Site(static.File(os.path.abspath("./stegano/sitetest"))).buildProtocol(
            "test"
        )  # Serve the given folder
        self.app.transport = (
            self
        )  # Because we define self as transport we have to implement function normally called by twisted for a transport class

    def packet_received(
        self, packet, **kwargs
    ):  # Overwrite TCPApplication packet_received to call the dataReceived of twisted
        self.lastclient = kwargs["id"]
        try:
            print ("---- Request received ----\n" + packet + "\n------------")
            self.app.dataReceived(
                packet
            )  # TODO: A chaque fois qu'on fait un read write s'assurer que la connection existe toujours etc..
        except Exception, e:
            print ("Something is wrong in the request:" + str(e))
开发者ID:RobinDavid,项目名称:pystack,代码行数:28,代码来源:webserver.py

示例13: __init__

   def __init__(self):
      root = Resource()

      ## downloads server -- client grabs patch info from here
      root.putChild('u', VirtualFile('webRoot/downloads/u'))

      ## MOST OF THE BELOW DONT WORK SO ARE COMMENTED OUT

      ## redalert3pc.sake.gamespy.com
      sakeStorageServer = Resource()
      sakeStorageServer.putChild('StorageServer.asmx', StorageServer())
      #root.putChild('SakeStorageServer', sakeStorageServer)

      ## redalert3pc.auth.pubsvs.gamespy.com -- used to auth before reporting results
      authService = Resource()
      authService.putChild('AuthService.asmx', AuthService())
      #root.putChild('AuthService', authService)

      ## redalert3pc.comp.pubsvs.gamespy.com -- used to report match results
      compSvc = Resource()
      compSvc.putChild('competitionservice.asmx', CompetitionService())
      #compSvc.putChild('CompetitionService.asmx', CompetitionService())
      root.putChild('competitionservice', compSvc)
      #root.putChild('CompetitionService', compSvc)

      ## TODO: psweb.gamespy.com -- SOAP service that serves Clan-related requests
      ## TODO: redalert3services.gamespy.com -- HTTP GET requests that serve rank icons
      ## /GetPlayerRankIcon.aspx?gp=fgErop[sap9faZeJJELRac__&pid=<pid of player> retrieves that player's rank icon
      ## /GetPlayerLadderRatings.aspx?gp=fgErop[sap9faZeJJELRac__ retrieves CSV of ladder ratings


      Site.__init__(self, root)
开发者ID:istobran,项目名称:eaEmu,代码行数:32,代码来源:webServices.py

示例14: _create_web_factory

    def _create_web_factory(self, config):

        options = config.get('options', {})

        # create Twisted Web root resource
        if '/' in config['paths']:
            root_config = config['paths']['/']
            root = self._create_resource(root_config, nested=False)
        else:
            root = Resource404(self._templates, b'')

        # create Twisted Web resources on all non-root paths configured
        self._add_paths(root, config.get('paths', {}))

        # create the actual transport factory
        transport_factory = Site(root)
        transport_factory.noisy = False

        # Web access logging
        if not options.get('access_log', False):
            transport_factory.log = lambda _: None

        # Traceback rendering
        transport_factory.displayTracebacks = options.get('display_tracebacks', False)

        # HSTS
        if options.get('hsts', False):
            if 'tls' in config['endpoint']:
                hsts_max_age = int(options.get('hsts_max_age', 31536000))
                transport_factory.requestFactory = createHSTSRequestFactory(transport_factory.requestFactory, hsts_max_age)
            else:
                self.log.warn("Warning: HSTS requested, but running on non-TLS - skipping HSTS")

        return transport_factory
开发者ID:david-e,项目名称:crossbar,代码行数:34,代码来源:router.py

示例15: setUp

def setUp():
    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        log.startLogging(sys.stdout)
        debug = True
    else:
        debug = False
    try:
        import autobahn
        import twisted
    except ImportError:
        sys.exit("Install all dependencies")
    from orm.database_init import init_db, db_session
    from apps.web import constants
    init_db()
    from pdb import set_trace
    set_trace()
    from apps.web import main_resource
    root = main_resource.Root()
    reactor.listenTCP(8000, server.Site(main_resource.Root()))
    factory = BroadcastServerFactory("ws://127.0.0.1:8011", debug=debug, debugCodePaths=debug)
    factory.protocol = BroadcastServerProtocol
    factory.setProtocolOptions(allowHixie76=True)
    ws_resource = WebSocketResource(factory)
    root.putChild("ws", ws_resource)
    site = Site(root)
    site.protocol = HTTPChannelHixie76Aware
    listenWS(factory)
    reactor.run()
开发者ID:yavalvas,项目名称:chess_autobahn,代码行数:28,代码来源:chess_server.py


注:本文中的twisted.web.server.Site类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。