twisted.web.static.File

Here are the examples of the python api twisted.web.static.File taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

84 Examples 7

Example 1

View license
    def __init__(self, services_factory, provider=None, disclaimer_banner=None, authenticator=None):
        BaseResource.__init__(self, services_factory)
        self._static_folder = _get_static_folder()
        self._startup_folder = _get_startup_folder()
        self._disclaimer_banner = disclaimer_banner
        self._provider = provider
        self._authenticator = authenticator or Authenticator(provider)
        self._bootstrap_user_services = BootstrapUserServices(services_factory, provider)

        self.putChild('startup-assets', File(self._startup_folder))
        with open(os.path.join(self._startup_folder, 'Interstitial.html')) as f:
            self.interstitial = f.read()

Example 2

View license
    def initialize(self, provider=None, disclaimer_banner=None, authenticator=None):
        self._child_resources.add('sandbox', SandboxResource(self._static_folder))
        self._child_resources.add('assets', File(self._static_folder))
        self._child_resources.add('keys', KeysResource(self._services_factory))
        self._child_resources.add(AttachmentsResource.BASE_URL, AttachmentsResource(self._services_factory))
        self._child_resources.add('contacts', ContactsResource(self._services_factory))
        self._child_resources.add('features', FeaturesResource(provider))
        self._child_resources.add('tags', TagsResource(self._services_factory))
        self._child_resources.add('mails', MailsResource(self._services_factory))
        self._child_resources.add('mail', MailResource(self._services_factory))
        self._child_resources.add('feedback', FeedbackResource(self._services_factory))
        self._child_resources.add('user-settings', UserSettingsResource(self._services_factory))
        self._child_resources.add('users', UsersResource(self._services_factory))
        self._child_resources.add(LoginResource.BASE_URL,
                                  LoginResource(self._services_factory, provider, disclaimer_banner=disclaimer_banner, authenticator=authenticator))
        self._child_resources.add(LogoutResource.BASE_URL, LogoutResource(self._services_factory))

        self._mode = MODE_RUNNING

Example 3

Project: wolverine
Source File: web.py
View license
    @classmethod
    def setup(cls):
        r = cls()
        r.putChild('subscribe', pubsub.SubscribeResource())
        r.putChild('publish', pubsub.PublishResource())
        #r.putChild('stream', stream.StreamResource())
        r.putChild('style.css', static.File(sibpath(__file__, 'static/styles.css')))
        return r

Example 4

Project: mamba-framework
Source File: resource.py
View license
    def add_paths(self, paths):
        """Add a new path to the list of paths

        :param path: the paths to add
        :type path: list
        """

        for path in paths:
            self.paths.append(static.File(path))

Example 5

Project: mamba-framework
Source File: page.py
View license
    def insert_stylesheets(self):
        """Insert stylesheets into the HTML
        """

        for name, style in self._styles_manager.get_styles().iteritems():
            if style.less:
                self.containers['styles'].putChild(
                    name, LessResource(style.path)
                )
                continue

            self.containers['styles'].putChild(name, static.File(style.path))

Example 6

Project: mamba-framework
Source File: page.py
View license
    def insert_scripts(self):
        """Insert scripts to the HTML
        """

        for name, script in self._scripts_manager.get_scripts().iteritems():
            self.containers['scripts'].putChild(name, static.File(script.path))

Example 7

Project: scrapy
Source File: test_engine.py
View license
def start_test_site(debug=False):
    root_dir = os.path.join(tests_datadir, "test_site")
    r = static.File(root_dir)
    r.putChild(b"redirect", util.Redirect(b"/redirected"))
    r.putChild(b"redirected", static.Data(b"Redirected here", "text/plain"))

    port = reactor.listenTCP(0, server.Site(r), interface="127.0.0.1")
    if debug:
        print("Test server running at http://localhost:%d/ - hit Ctrl-C to finish." \
            % port.getHost().port)
    return port

Example 8

Project: scrapy
Source File: test_webclient.py
View license
    def setUp(self):
        name = self.mktemp()
        os.mkdir(name)
        FilePath(name).child("file").setContent(b"0123456789")
        r = static.File(name)
        r.putChild(b"redirect", util.Redirect(b"/file"))
        r.putChild(b"wait", ForeverTakingResource())
        r.putChild(b"error", ErrorResource())
        r.putChild(b"nolength", NoLengthResource())
        r.putChild(b"host", HostHeaderResource())
        r.putChild(b"payload", PayloadResource())
        r.putChild(b"broken", BrokenDownloadResource())
        r.putChild(b"encoding", EncodingResource())
        self.site = server.Site(r, timeout=None)
        self.wrapper = WrappingFactory(self.site)
        self.port = self._listen(self.wrapper)
        self.portno = self.port.getHost().port

Example 9

Project: downpour
Source File: echoServer.py
View license
    def __init__(self, reactor, path='.', port=8080):
        # Make a root resource, and add children to it for
        # each of the types of requests we plan to service
        root = static.File(os.path.abspath(path))
        root.indexNames = ['index.html', 'index.txt', 'index.asis']
        root.processors = {
            '.asis' : CleanASIS
        }
        root.putChild('echo', Echo())
        # Initialize and listen
        server.Site.__init__(self, root)
        reactor.listenTCP(port, self)

Example 10

Project: tahoe-lafs
Source File: run.py
View license
def run(portnum):
    root = Root()
    root.putChild("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()

Example 11

Project: flumotion
Source File: cortado.py
View license
    def _addChildren(self):
        self.putChild("cortado.jar",
                      File(self._cortado_filename,
                           'application/x-java-archive'))

        self.putChild(self._index_name,
                      self._index_content)
        self.putChild('', self._index_content)

Example 12

Project: Coherence
Source File: base.py
View license
    def getChild(self, name, request):
        self.debug('SimpleRoot getChild %s, %s', name, request)
        if name == 'oob':
            """ we have an out-of-band request """
            return static.File(self.coherence.dbus.pinboard[request.args['key'][0]])

        if name == '':
            return self

        # at this stage, name should be a device UUID
        try:
            return self.coherence.children[name]
        except:
            self.warning("Cannot find device for requested name: %s", name)
            request.setResponseCode(404)
            return static.Data('<html><p>No device for requested UUID: %s</p></html>' % name, 'text/html')

Example 13

Project: Coherence
Source File: test_utils.py
View license
    def setUp(self):
        name = self.mktemp()
        os.mkdir(name)
        FilePath(name).child("file").setContent("0123456789")
        r = static.File(name)
        self.site = server.Site(r, timeout=None)
        self.wrapper = policies.WrappingFactory(self.site)
        self.port = self._listen(self.wrapper)
        self.portno = self.port.getHost().port

Example 14

Project: Coherence
Source File: basics.py
View license
    def getChild(self, name, request):
        self.info('DeviceHttpRoot %s getChild %s', name, request)
        ch = None
        if ch is None:
            p = util.sibpath(__file__, name)
            if os.path.exists(p):
                ch = static.File(p)
        self.info('DeviceHttpRoot ch  %s', ch)
        return ch

Example 15

Project: autobahn-testsuite
Source File: broadcast.py
View license
def startServer(wsuri, webport, sslKey = None, sslCert = None, debug = False):
   factory = BroadcastServerFactory(wsuri, debug)
   if sslKey and sslCert:
      sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
   else:
      sslContext = None
   listenWS(factory, sslContext)

   if webport:
      webdir = File(pkg_resources.resource_filename("autobahntestsuite", "web/broadcastserver"))
      web = Site(webdir)
      reactor.listenTCP(webport, web)

   return True

Example 16

Project: autobahn-testsuite
Source File: testee.py
View license
def startServer(wsuri, webport = None, sslKey = None, sslCert = None, debug = False):
   factory = TesteeServerFactory(wsuri, debug)
   if sslKey and sslCert:
      sslContext = ssl.DefaultOpenSSLContextFactory(sslKey, sslCert)
   else:
      sslContext = None
   listenWS(factory, sslContext)

   if webport:
      webdir = File(pkg_resources.resource_filename("autobahntestsuite", "web/echoserver"))
      web = Site(webdir)
      reactor.listenTCP(webport, web)

   return True

Example 17

Project: sylkserver
Source File: web.py
View license
    @app.route('/<string:room_uri>/screensharing_img/<string:filename>')
    def screensharing_image(self, request, room_uri, filename):
        try:
            room = self.conference._rooms[room_uri]
        except KeyError:
            return NoResource('Room not found')
        images_path = os.path.join(ConferenceConfig.screensharing_images_dir, room.uri)
        return File(os.path.join(images_path, os.path.basename(filename)))

Example 18

Project: deluge
Source File: test_core.py
View license
    def __init__(self):
        Resource.__init__(self)
        self.putChild('cookie', CookieResource())
        self.putChild('partial', PartialDownload())
        self.putChild('redirect', RedirectResource())
        self.putChild('ubuntu-9.04-desktop-i386.iso.torrent',
                      File(common.get_test_data_file('ubuntu-9.04-desktop-i386.iso.torrent')))

Example 19

Project: deluge
Source File: test_web_api.py
View license
    @defer.inlineCallbacks
    def test_download_torrent_from_url(self):
        filename = 'ubuntu-9.04-desktop-i386.iso.torrent'
        self.deluge_web.top_level.putChild(filename, File(common.get_test_data_file(filename)))
        url = 'http://localhost:%d/%s' % (self.webserver_listen_port, filename)
        res = yield self.deluge_web.web_api.download_torrent_from_url(url)
        self.assertTrue(res.endswith(filename))

Example 20

Project: e2openplugin-OpenWebif
Source File: BQE.py
View license
	def __init__(self, session, path = ""):
		BaseController.__init__(self, path)
		self.session = session
		self.putChild("web", BQEWebController(session))
		self.putChild("api", BQEApiController(session))
		self.putChild('tmp', static.File('/tmp'))
		self.putChild('uploadrestore', BQEUploadFile(session))

Example 21

Project: e2openplugin-OpenWebif
Source File: ipkg.py
View license
	def CallOPKListGZ(self, request):
		tmpFilename = "/tmp/opkg-list.gz"
		if path.exists(tmpFilename):
			remove(tmpFilename)
		lines = popen('/usr/bin/opkg list | gzip > %s' % tmpFilename).readlines()
		request.setHeader("Content-Disposition:", "attachment;filename=\"%s\"" % (tmpFilename.split('/')[-1]))
		rfile = static.File(tmpFilename, defaultType = "application/octet-stream")
		return rfile.render(request)

Example 22

Project: muXTCP
Source File: tcp.py
View license
    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

Example 23

Project: ibid
Source File: http.py
View license
    def __init__(self, name):
        IbidSourceFactory.__init__(self, name)
        root = Plugin(name)
        root.putChild('', Index(name))
        root.putChild('message', Message(name))
        root.putChild('static', static.File(locate_resource('ibid', 'static')))
        root.putChild('RPC2', XMLRPC())
        root.putChild('SOAP', SOAP())
        self.site = server.Site(root)

Example 24

Project: shinysdr
Source File: app.py
View license
def _make_static_resource(pathname):
    r = static.File(pathname,
        defaultType='text/plain',
        ignoredExts=['.html'])
    r.contentTypes['.csv'] = 'text/csv'
    r.indexNames = ['index.html']
    return r

Example 25

Project: shinysdr
Source File: app.py
View license
def _make_static_resource(pathname):
    r = static.File(pathname,
        defaultType='text/plain',
        ignoredExts=['.html'])
    r.contentTypes['.csv'] = 'text/csv'
    r.indexNames = ['index.html']
    return r

Example 26

Project: makina-states.pack1
Source File: nx_extract.py
View license
   def __init__(self):
      Resource.__init__(self)
      #twisted will handle static content for me
      self.putChild('bootstrap', File('./bootstrap'))
      self.putChild('js', File('./js'))
      #make the correspondance between the path and the object to call
      self.page_handler = {'/' : Index, '/graphs': GraphView, '/get_rules': GenWhitelist, '/map': WootMap}

Example 27

Project: makina-states.pack1
Source File: nx_extract.py
View license
   def __init__(self):
      Resource.__init__(self)
      #twisted will handle static content for me
      self.putChild('bootstrap', File('./bootstrap'))
      self.putChild('js', File('./js'))
      #make the correspondance between the path and the object to call
      self.page_handler = {'/' : Index, '/graphs': GraphView, '/get_rules': GenWhitelist, '/map': WootMap}

Example 28

Project: nagcat
Source File: nagios_api.py
View license
    def __init__(self, nagios_cfg):
        resource.Resource.__init__(self)

        cfg = nagios_objects.ConfigParser(nagios_cfg,
                ('object_cache_file', 'status_file'))

        self.putChild('', self)
        self.putChild('objects',
                static.File(cfg['object_cache_file'], 'text/plain'))
        self.putChild('status',
                static.File(cfg['status_file'], 'text/plain'))

Example 29

Project: nagcat
Source File: nagios_api.py
View license
    def __init__(self, nagios_cfg):
        resource.Resource.__init__(self)

        cfg = nagios_objects.ConfigParser(nagios_cfg,
                ('object_cache_file', 'status_file'))

        self.putChild('', self)
        self.putChild('objects',
                static.File(cfg['object_cache_file'], 'text/plain'))
        self.putChild('status',
                static.File(cfg['status_file'], 'text/plain'))

Example 30

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_path(self, path):
        """
        <path> is either a specific file or a directory to be set as the root
        of the web server. Use this if you have a directory full of HTML, cgi,
        epy, or rpy files or any other files that you want to be served up raw.
        """
        self['root'] = static.File(os.path.abspath(path))
        self['root'].processors = {
            '.cgi': twcgi.CGIScript,
            '.epy': script.PythonScript,
            '.rpy': script.ResourceScript,
            }

Example 31

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_processor(self, proc):
        """
        `ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass)

Example 32

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_mime_type(self, defaultType):
        """
        Specify the default mime-type for static files.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --mime_type after --path.")
        self['root'].defaultType = defaultType

Example 33

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_allow_ignore_ext(self):
        """
        Specify whether or not a request for 'foo' should return 'foo.ext'
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --allow_ignore_ext "
                                   "after --path.")
        self['root'].ignoreExt('*')

Example 34

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_ignore_ext(self, ext):
        """
        Specify an extension to ignore.  These will be processed in order.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --ignore_ext "
                                   "after --path.")
        self['root'].ignoreExt(ext)

Example 35

View license
    def test_getPublicHTMLChild(self):
        """
        L{UserDirectory.getChild} returns a L{static.File} instance when passed
        the name of a user with a home directory containing a I{public_html}
        directory.
        """
        home = filepath.FilePath(self.bob[-2])
        public_html = home.child('public_html')
        public_html.makedirs()
        request = DummyRequest(['bob'])
        result = self.directory.getChild('bob', request)
        self.assertIsInstance(result, static.File)
        self.assertEqual(result.path, public_html.path)

Example 36

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_path(self, path):
        """
        <path> is either a specific file or a directory to be set as the root
        of the web server. Use this if you have a directory full of HTML, cgi,
        epy, or rpy files or any other files that you want to be served up raw.
        """
        self['root'] = static.File(os.path.abspath(path))
        self['root'].processors = {
            '.cgi': twcgi.CGIScript,
            '.epy': script.PythonScript,
            '.rpy': script.ResourceScript,
            }

Example 37

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_processor(self, proc):
        """
        `ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass)

Example 38

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_mime_type(self, defaultType):
        """
        Specify the default mime-type for static files.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --mime_type after --path.")
        self['root'].defaultType = defaultType

Example 39

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_allow_ignore_ext(self):
        """
        Specify whether or not a request for 'foo' should return 'foo.ext'
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --allow_ignore_ext "
                                   "after --path.")
        self['root'].ignoreExt('*')

Example 40

Project: SubliminalCollaborator
Source File: tap.py
View license
    def opt_ignore_ext(self, ext):
        """
        Specify an extension to ignore.  These will be processed in order.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --ignore_ext "
                                   "after --path.")
        self['root'].ignoreExt(ext)

Example 41

View license
    def test_getPublicHTMLChild(self):
        """
        L{UserDirectory.getChild} returns a L{static.File} instance when passed
        the name of a user with a home directory containing a I{public_html}
        directory.
        """
        home = filepath.FilePath(self.bob[-2])
        public_html = home.child('public_html')
        public_html.makedirs()
        request = DummyRequest(['bob'])
        result = self.directory.getChild('bob', request)
        self.assertIsInstance(result, static.File)
        self.assertEqual(result.path, public_html.path)

Example 42

Project: droned
Source File: drone.py
View license
def start():
    global service
    if not running():
        kwargs = {'timeout': 60 * 60 * 12, 'logPath': None}
        try: kwargs.update({'timeout': config.DRONED_SERVER_TIMEOUT})
        except: pass
        dr = static.File(config.DRONED_WEBROOT)

        dr.putChild('_getprime', Prime())
        dr.putChild('_command', Control())
        dr.putChild('gremlin', Gremlin())

        site = DroneSite(dr, **kwargs)
        service = internet.TCPServer(config.DRONED_PORT, site) 
        service.setName(SERVICENAME)
        service.setServiceParent(parentService)

Example 43

Project: hatena-server
Source File: hatena.py
View license
	def __init__(self):
		resource.Resource.__init__(self)
		
		self.dsResource = ds()
		self.cssResource = static.File("hatenadir/css/")
		self.imagesResource = static.File("hatenadir/images/")

Example 44

View license
    def _startup_mode(self):
        self.putChild('startup-assets', File(self._startup_assets_folder))
        self._mode = MODE_STARTUP

Example 45

Project: mamba-framework
Source File: page.py
View license
    def add_script(self, script):
        """Adds a script to the page
        """

        self.putChild(script.prefix, static.File(script.path))

Example 46

Project: Cactus_Refactored
Source File: site.py
View license
    def serve(self, uri="localhost:8000"):
        """
        Start a http server and rebuild on changes.
        """
        host, _, port = uri.partition(":")
        port = int(port)

        self.clean()
        self.build(dist=False)

        logging.info('Running webserver at {0}'.format(uri))
        logging.info('Type control-c to exit')

        os.chdir(self.paths['build'])

        def rebuild(changes):
            logging.info("*** Rebuilding ({0} changed)".format(self.path))

            reload_needed = False
            rebuild_needed = False
            for p in changes.get('any', []):
                if os.path.realpath(os.path.dirname(p)) == os.path.realpath(self.path):
                    if os.path.basename(p) == "config.yml":
                        reload_needed = True
                        rebuild_needed = True
                else:
                    rebuild_needed = True

            if rebuild_needed:
                # We will pause the listener while building so scripts
                # that alter the output like coffeescript and less don't
                # trigger the listener again immediately.
                self.listener.pause()
                try:
                    if reload_needed:
                        self._load_config()
                        self.load_plugins()
                        self.load_context_processors()
                    self.build()
                except Exception, e:
                    logging.info("*** Error while building\n{0}".format(e))
                    traceback.print_exc(file=sys.stdout)

                cssonly = False
                if len(changes["added"]) == 0 and len(changes["deleted"]) == 0:
                    exts = set(map(lambda x: os.path.splitext(x)[1], changes["changed"]))
                    cssonly = True
                    for ext in exts:
                        if not re.match(r'\.(?:css|sass|scss|less)$', ext, re.I):
                            cssonly = False
                if cssonly:
                    browser.browserReloadCSS("http://localhost:{0}".format(port), self)
                else:
                    browser.browserReload("http://localhost:{0}".format(port), self)

                self.listener.resume()

        from .listener import Listener

        self.listener = Listener(
            self.path, rebuild, ignore=lambda x: '/.tmp/' in x
        )
        self.listener.run()

        from twisted.web.server import Site as Website
        from twisted.web.static import File
        from twisted.internet import reactor

        resource = File(self.paths['build'])
        factory = Website(resource)
        reactor.listenTCP(port, factory)

        browser.openurl("http://localhost:{0}".format(port), self)

        try:
            reactor.run()
        except (KeyboardInterrupt, SystemExit):
            reactor.stop()

        logging.info('See you!')

Example 47

Project: splash
Source File: resources.py
View license
    def __init__(self, pool, ui_enabled, lua_enabled, lua_sandbox_enabled,
                 lua_package_path,
                 lua_sandbox_allowed_modules,
                 max_timeout,
                 argument_cache_max_entries,
                 ):
        Resource.__init__(self)
        self.argument_cache = ArgumentCache(argument_cache_max_entries)
        self.ui_enabled = ui_enabled
        self.lua_enabled = lua_enabled

        _args = pool, max_timeout, self.argument_cache
        self.putChild(b"render.html", RenderHtmlResource(*_args))
        self.putChild(b"render.png", RenderPngResource(*_args))
        self.putChild(b"render.jpeg", RenderJpegResource(*_args))
        self.putChild(b"render.json", RenderJsonResource(*_args))
        self.putChild(b"render.har", RenderHarResource(*_args))

        self.putChild(b"_debug", DebugResource(pool, self.argument_cache))
        self.putChild(b"_gc", ClearCachesResource(self.argument_cache))
        self.putChild(b"_ping", PingResource())

        # backwards compatibility
        self.putChild(b"debug", DebugResource(pool, self.argument_cache, warn=True))

        if self.lua_enabled and ExecuteLuaScriptResource is not None:
            self.putChild(b"execute", ExecuteLuaScriptResource(
                pool=pool,
                sandboxed=lua_sandbox_enabled,
                lua_package_path=lua_package_path,
                lua_sandbox_allowed_modules=lua_sandbox_allowed_modules,
                max_timeout=max_timeout,
                argument_cache=self.argument_cache,
            ))

        if self.ui_enabled:
            root = os.path.dirname(__file__)
            ui = File(os.path.join(root, 'ui'))

            har_path = os.path.join(root, 'vendor', 'harviewer', 'webapp')
            ui.putChild(to_bytes(HARVIEWER_PATH), File(har_path))
            inspections_path = os.path.join(root, 'kernel', 'inspections')
            ui.putChild(b"inspections", File(inspections_path))
            examples_path = os.path.join(root, 'examples')
            ui.putChild(b"examples", File(examples_path))

            self.putChild(b"_ui", ui)
            self.putChild(DemoUI.PATH, DemoUI(
                pool=pool,
                lua_enabled=self.lua_enabled,
                max_timeout=max_timeout
            ))
        self.max_timeout = max_timeout

Example 48

Project: scrapy
Source File: test_downloader_handlers.py
View license
    def setUp(self):
        name = self.mktemp()
        os.mkdir(name)
        FilePath(name).child("file").setContent(b"0123456789")
        r = static.File(name)
        r.putChild(b"redirect", util.Redirect(b"/file"))
        r.putChild(b"wait", ForeverTakingResource())
        r.putChild(b"hang-after-headers", ForeverTakingResource(write=True))
        r.putChild(b"nolength", NoLengthResource())
        r.putChild(b"host", HostHeaderResource())
        r.putChild(b"payload", PayloadResource())
        r.putChild(b"broken", BrokenDownloadResource())
        r.putChild(b"contentlength", ContentLengthHeaderResource())
        r.putChild(b"nocontenttype", EmptyContentTypeHeaderResource())
        self.site = server.Site(r, timeout=None)
        self.wrapper = WrappingFactory(self.site)
        self.host = 'localhost'
        if self.scheme == 'https':
            self.port = reactor.listenSSL(
                0, self.wrapper, ssl_context_factory(self.keyfile, self.certfile),
                interface=self.host)
        else:
            self.port = reactor.listenTCP(0, self.wrapper, interface=self.host)
        self.portno = self.port.getHost().port
        self.download_handler = self.download_handler_cls(Settings())
        self.download_request = self.download_handler.download_request

Example 49

Project: scrapyd
Source File: website.py
View license
    def __init__(self, config, app):
        resource.Resource.__init__(self)
        self.debug = config.getboolean('debug', False)
        self.runner = config.get('runner')
        logsdir = config.get('logs_dir')
        itemsdir = config.get('items_dir')
        local_items = itemsdir and (urlparse(itemsdir).scheme.lower() in ['', 'file'])
        self.app = app
        self.nodename = config.get('node_name', socket.gethostname())
        self.putChild('', Home(self, local_items))
        if logsdir:
            self.putChild('logs', static.File(logsdir, 'text/plain'))
        if local_items:
            self.putChild('items', static.File(itemsdir, 'text/plain'))
        self.putChild('jobs', Jobs(self, local_items))
        services = config.items('services', ())
        for servName, servClsName in services:
          servCls = load_object(servClsName)
          self.putChild(servName, servCls(self))
        self.update_projects()

Example 50

Project: nodeset.core
Source File: scripts.py
View license
def run_web_node():
    
    config = WebNodeOptions()
    application = ts.Application('nodeset-web-node')
    #sc = ts.IServiceCollection(application)
      
    try:
        config.parseOptions()


        from twisted.web import static, script, resource

        from nodeset.core import web
        n = web.WebBridgeNode()
        n.setServiceParent(application)
     
        n.start()
        
        if config.subOptions.has_key('path'):
            root = static.File(config.subOptions['path'])
            root.ignoreExt(".rpy")
            root.processors = {'.rpy': script.ResourceScript}
        else:
            root = resource.Resource()
        
        site = web.NodeSetSite(root, n, logPath=config.subOptions['logfile'])

        root.putChild('subscribe', web.NodeSetSubscribe())
        root.putChild('publish', web.NodeSetPublish())
        
        webservice = internet.TCPServer(config.subOptions['port'], site)
        webservice.setServiceParent(application)
        
        #d = dispatcher.EventDispatcher(config['listen'])
        #d.setServiceParent(application)
    except usage.error, ue:
        #print config
        print ue
    else:
        runApp(config, application)