def makeService(config): # Use psyco if available try: import psyco psyco.full() except ImportError: pass configfile = yaml.load(file(config['config'], 'rb').read()) application = service.MultiService() # database dbpool = None dbconfig = configfile.get('database', {}) if dbconfig.get('enabled', True): dbpool = Database(dbconfig).pool # collector collector = None if dbpool is not None: collconfig = configfile.get('collector', {}) if collconfig.get('enabled', True): collector = CollectorService(collconfig, dbpool) collector.setServiceParent(application) # web service web = None if dbpool is not None and collector is not None: webconfig = configfile.get('web', {}) if webconfig.get('enabled', True): web = internet.TCPServer( webconfig.get('port', 8089), appserver.NevowSite(WebMainPage(webconfig, dbpool, collector)), interface=webconfig.get('interface', '127.0.0.1')) web.setServiceParent(application) # meta web service metaweb = None metawebconfig = configfile.get('metaweb', {}) if metawebconfig: metaweb = internet.TCPServer( metawebconfig.get('port', 8090), appserver.NevowSite(MetaWebMainPage(metawebconfig)), interface=metawebconfig.get('interface', '127.0.0.1')) metaweb.setServiceParent(application) if dbpool is None: reactor.callLater(0, log.msg, "Database has been disabled.") if collector is None: reactor.callLater(0, log.msg, "Collector has been disabled.") if web is None: reactor.callLater(0, log.msg, "Web service has been disabled.") if metaweb is None: reactor.callLater(0, log.msg, "MetaWeb service has been disabled.") return application
def canvas(width, height, delegate, useCGI=False): C = cookie() if useCGI: global _canvasCGIService if _canvasCGIService is None: from nevow import appserver from twisted.internet import reactor _canvasCGIService = reactor.listenTCP( 0, appserver.NevowSite(Canvas(docFactory=canvasServerMessage))) _canvasCGIService.dispatchMap = {} port = _canvasCGIService.getHost().port prefix = '/' movie_url = url.here.click('/').secure(False, port) else: movie_url = url.here port = lambda c, d: inevow.IRequest(c).transport.server.port def prefix(c, d): pre = inevow.IRequest(c).path if pre.endswith('/'): return pre return pre + '/' _hookup[C] = delegate handlerInfo = [] for handlerName in [ 'onMouseMove', 'onMouseDown', 'onMouseUp', 'onKeyDown', 'onKeyUp' ]: if getattr(delegate, handlerName, None) is not None: handlerInfo.append((handlerName, 1)) movie_url = movie_url.child('nevow_canvas_movie.swf').add('cookie', C).add( 'port', port).add('prefix', prefix) for (k, v) in handlerInfo: movie_url = movie_url.add(k, v) return tags._object( classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", codebase= "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0", width=width, height=height, id=("Canvas-", C), align="middle" )[tags.param(name="allowScriptAccess", value="sameDomain"), tags.param(name="movie", value=movie_url), tags.param(name="quality", value="high"), tags.param(name="scale", value="noscale"), tags.param(name="bgcolor", value="#ffffff"), Tag('embed')(src=movie_url, quality="high", scale="noscale", bgcolor="#ffffff", width=width, height=height, name=("Canvas-", C), align="middle", allowScriptAccess="sameDomain", type="application/x-shockwave-flash", pluginspage="http://www.macromedia.com/go/getflashplayer")]
def prepare(debug): """Bind together the webserver components. Args: debug: bool, if True run in debug mode Returns: service.Application """ application = service.Application("mes-souhaits") if debug: url = 'http://127.0.0.1:%d' % PORT else: url = 'http://mes-souhaits.net' srv = core.Service(url, debug=debug) srv.setServiceParent(application) root = pages.RootPage(srv) root.putChild('vhost', vhost.VHostMonsterResource()) site = appserver.NevowSite(root) server = internet.TCPServer(PORT, site) # pylint: disable-msg=E1101 server.setServiceParent(application) return application
def makeService(config): # Use psyco if available try: import psyco psyco.full() except ImportError: pass # configuration file configfile = yaml.load(file(config['config'], 'rb').read()) # database dbpool = Database(configfile).pool application = service.MultiService() collector = CollectorService(configfile, dbpool) collector.setServiceParent(application) web = internet.TCPServer(int(config['port']), appserver.NevowSite(MainPage(configfile, dbpool, collector)), interface=config['interface']) web.setServiceParent(application) return application
def renderResource(self, resource, path): s = appserver.NevowSite(resource) channel = DummyChannel() channel.site = s r = appserver.NevowRequest(channel, True) r.path = path return r.process()
def getResourceFor(self, root, url): r = testutil.FakeRequest() self.request = r r.postpath = url.split('/') deferred = util.maybeDeferred( appserver.NevowSite(root).getResourceFor, r) return util.deferredResult(deferred)
def main(): """Create the web-site""" s = SurveySetup() s.putChild('record', RecordFunction()) site = appserver.NevowSite(s) webServer = internet.TCPServer(8080, site) webServer.startService()
def RegisterWebsite(port): website = WebInterface() site = appserver.NevowSite(website) reactor.listenTCP(port, site) print(_('HTTP interface port :'), port) return website
def setUp(self): class Res1(Render): def renderHTTP(self, ctx): return "boring" self.site = appserver.NevowSite(Res1()) self.site.logFile = StringIO()
def getResourceFor(self, root, url): r = testutil.FakeRequest() self.request = r r.postpath = url.split('/') ctx = context.RequestContext(tag=self.request) return util.maybeDeferred( appserver.NevowSite(root).getPageContextForRequestContext, ctx)
def buildServer(self, webport, nodeurl_path, staticdir): self.webport = webport self.site = site = appserver.NevowSite(self.root) self.site.requestFactory = MyRequest self.site.remember(MyExceptionHandler(), inevow.ICanHandleException) self.staticdir = staticdir # so tests can check if staticdir: self.root.putChild("static", static.File(staticdir)) if re.search(r'^\d', webport): webport = "tcp:" + webport # twisted warns about bare "0" or "3456" s = strports.service(webport, site) s.setServiceParent(self) self._scheme = None self._portnum = None self._url = None self._listener = s # stash it so we can query for the portnum self._started = defer.Deferred() if nodeurl_path: def _write_nodeurl_file(ign): # this file will be created with default permissions line = self.getURL() + "\n" fileutil.write_atomically(nodeurl_path, line, mode="") self._started.addCallback(_write_nodeurl_file)
def startConsole(self, installSignals=True): ''' Start the console @param installSignals: True to install custom signal handlers ''' from pyscrabble.net.server import ScrabbleServerFactory self.gameFactory = ScrabbleServerFactory() from pyscrabble.net.site import ScrabbleSite self.site = appserver.NevowSite(ScrabbleSite(self.gameFactory)) reactor.listenTCP(self.g_port, self.gameFactory) reactor.listenTCP(self.w_port, self.site) if installSignals: import signal signal.signal(signal.SIGTERM, self.handleSignal) signal.signal(signal.SIGINT, self.handleSignal) if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, self.handleSignal) logger = logging.getLogger("pyscrabble.server_console") logger.info('Server running') reactor.run(installSignalHandlers=False)
def setUp(self): class Res1(Render): def renderHTTP(self, ctx): return "boring" self.site = appserver.NevowSite(Res1()) self.site.startFactory() self.addCleanup(self.site.stopFactory) self.site.logFile = BytesIO()
def tac(): global application from twisted.application import service, internet from nevow import appserver application = service.Application("simple") internet.TCPServer(8080, appserver.NevowSite( ProjectIndex())).setServiceParent(application)
def run(portnum): root = Root() root.putChild(b"tahoe.css", static.File("tahoe.css")) site = appserver.NevowSite(root) s = strports.service("tcp:%d" % portnum, site) s.startService() reactor.callLater(1.0, webbrowser.open, "http://localhost:%d/" % portnum) reactor.run()
def RegisterWebsite(port): website = WebInterface() site = appserver.NevowSite(website) listening = False reactor.listenTCP(port, site) print _("HTTP interface port :"), port return website
def getSite(config): form = AddressBookResource() form.remember(config, ILDAPConfig) realm = AddressBookRealm(form) site = appserver.NevowSite( guard.SessionWrapper( portal.Portal(realm, [checkers.AllowAnonymousAccess()]))) return site
def start_webserver(self, p_pyhouse_obj): l_site_dir = None l_site = appserver.NevowSite( web_mainpage.TheRoot(l_site_dir, p_pyhouse_obj)) l_port = p_pyhouse_obj.Computer.Web.WebPort p_pyhouse_obj.Twisted.Reactor.listenTCP(l_port, l_site) l_msg = "Port:{}, Path:{}".format(p_pyhouse_obj.Computer.Web.WebPort, l_site_dir) LOG.info("Started - {}".format(l_msg))
def addWebServer(rootService): factories = globalRegistry.factories vResource = vhost.VHostMonsterResource() webroot = pages.Root(factories) webroot.putChild(rootService.cfg.web.vhost_root, vResource) site = appserver.NevowSite(webroot) port = int(rootService.cfg.web.port) webserver = internet.TCPServer(port, site) webserver.setServiceParent(rootService)
def run(): webappConfig = WebappConfiguration() webappConfig.load() maayPortal = MaayPortal(webappConfig) website = appserver.NevowSite(guard.SessionWrapper(maayPortal)) rpcserver = server.Site(MaayRPCServer(maayPortal)) reactor.listenTCP(8080, website) reactor.listenTCP(6789, rpcserver) print "Go !" reactor.run()
def start(self): ip = self.app.cfg_setup.get("interfaces", self.app.host) site = appserver.NevowSite(web.htaccess(self.app, self.log)) # base web server - listen on primary interface and localhost self.app.reactor.listenTCP(int(self._cfg_http_port), site, interface=ip) self.app.reactor.listenTCP(int(self._cfg_http_port), site, interface="localhost")
def main(): app = App() if config.webport: try: from nevow import appserver import web site = appserver.NevowSite(web.WebInterface(pytrans=app.transportSvc)) reactor.listenTCP(config.webport, site) LogEvent(INFO, msg="Web interface activated") except: LogEvent(WARN, msg="Unable to start web interface. Either Nevow is not installed or you need a more recent version of Twisted. (>= 2.0.0.0)") reactor.run()
def deploy(db): """Creates an application service and guarded root @param db: C{AccessBroker} instance """ guardSite = createResource(db) siteRoot = Index.Page(db) #siteRoot.putChild('vhost', vhost.VHostMonsterResource()) siteRoot.putChild('auth', guardSite) site = appserver.NevowSite(siteRoot) site.context.remember(PageHelpers.TumsExceptionHandler(), inevow.ICanHandleException) return site
def startService(self): service.Service.startService(self) log.debug("monitor init") self.storage = self.broker.storage self.db = self.broker.db # some static resources self.putChild('favicon.ico', static.File('monitor/favicon.ico')) # create http service factory = appserver.NevowSite(self) fs_service = internet.TCPServer( port=self.config['server']['monitor.bind'][1], factory=factory, interface=self.config['server']['monitor.bind'][0]) fs_service.setServiceParent(self.parent)
def renderResource(uri, notFoundHandler=None): """Render a resource at some uri and return the response code and html. """ root = Root() if notFoundHandler is not None: root.remember(notFoundHandler, inevow.ICanHandleNotFound) site = appserver.NevowSite(root) ctx = context.SiteContext(tag=site) request = testutil.FakeRequest(uri=uri) ctx = context.RequestContext(parent=ctx, tag=request) def waitmore(newctx): return defer.maybeDeferred(newctx.tag.renderHTTP, newctx).addCallback(lambda html: (request.code, html)) return site.getPageContextForRequestContext(ctx).addCallback(waitmore)
def main(): parser = OptionParser() parser.add_option("--parallel", action="store_true", help="use parallel port") parser.add_option("--arduino", action="store_true", help="talk to an arduino over usb") parser.add_option("--failok", action="store_true", help="if the parport can't be opened, start anyway") parser.add_option("--channels", type="int", help="number of shiftbrites connected", default=2) parser.add_option( "--pollbuttons", action="store_true", help= "watch for remote control buttons and send them via OSC to udp localhost:10050" ) opts, args = parser.parse_args() import twisted.python #twisted.python.log.startLogging(sys.stdout) if opts.parallel: sb = ShiftbriteParallel(dummyModeOk=opts.failok, numChannels=1) elif opts.arduino: sb = ShiftbriteArduino(numChannels=opts.channels) else: raise ValueError("pick an output mode") # also make a looping task that calls update() to correct noise errors # in the LED if opts.pollbuttons: sys.path.append("../../ariremote") from oscserver import ArduinoWatcher aw = ArduinoWatcher(sb) task.LoopingCall(aw.poll).start(1.0 / 20) root = Root(sb) reactor.listenTCP(9014, appserver.NevowSite(root)) reactor.run()
def renderResourceReturnTransport(resource, path, method): """ Perform a synthetic request for the given resource. This is like L{renderResource} but with a different return value. @return: All of the bytes written to the transport as a result of the rendering. """ s = appserver.NevowSite(resource) channel = DummyChannel() channel.site = s r = appserver.NevowRequest(channel, True) r.path = path if method is not None: r.method = method d = r.process() d.addCallback(lambda ignored: channel.transport.written.getvalue()) return d
def getResourceFor(root, url): """ Perform traversal for C{url} beginning at C{root}. @param root: The L{nevow.inevow.IResource} at which to begin. @param url: The relative path string of the url of the resource to retrieve. @type url: L{bytes} @return: A L{Deferred} that fires with a L{PageContext} for the discovered resource. """ request = testutil.FakeRequest() request.postpath = url.split('/') ctx = context.RequestContext(tag=request) return util.maybeDeferred( appserver.NevowSite(root).getPageContextForRequestContext, ctx)
def test_renderPOST(self): """ A POST request with form data has the form data parsed into C{request.fields}. """ class Res(Render): def renderHTTP(self, ctx): return b'' s = appserver.NevowSite(Res()) channel = DummyChannel() channel.site = s r = appserver.NevowRequest(channel, True) r.method = b'POST' r.path = b'/' r.content = StringIO(b'foo=bar') self.successResultOf(r.process()) self.assertEquals(r.fields[b'foo'].value, b'bar')
def test_connectionLost(self): """ L{Request.finish} is not called when the connection is lost before rendering has finished. """ rendering = Deferred() class Res(Render): def renderHTTP(self, ctx): return rendering site = appserver.NevowSite(Res()) request = appserver.NevowRequest(testutil.FakeChannel(site), True) request.connectionLost(Exception("Just Testing")) rendering.callback(b"finished") self.assertFalse(request.finished, "Request was incorrectly marked as finished.")