def render():
    child = Elem()
    for _ in xrange(20):
        child = Elem([child])
    root = TagLoader([child] * 10).load()
    out = BytesIO()
    flatten(None, root, out.write)
def render():
    child = Elem()
    for _ in xrange(20):
        child = Elem([child])
    root = TagLoader([child] * 10).load()
    out = BytesIO()
    flatten(None, root, out.write)
Esempio n. 3
0
def renderPage(time, output):
    """
    Called to render the page from start to end and send results to the
    `output` write function.

    This should be the only public method.
    """
    start, end = monthRangeAround(time)
    actions = computeActions(start, end)
    scores = getscores(actions)

    page = HiscoresPage(start, scores)
    # Not requesting any asynchronous data, so we can just ignore the result of
    # this Deferred.
    flatten(None, page, output)
	def render_GET (self, request):
		saved_sketches = sketch.find(
			default_search = {
				'deleted': { 'value': 0 }
			}, order = [
				{ 'column': 'modified_date', 'dir': 'desc' }
			],
			fetch_columns = ['guid', 'title', 'user_id', 'modified_date'],
			return_counts = False,
		)

		past_experiments = experiment.find(
			default_search = {
				'deleted': { 'value': 0 },
				'finished_date': { 'value': 0, 'operator': 'gt' }
			}, order = [
				{ 'column': 'finished_date', 'dir': 'desc' }
			],
			fetch_columns = ['guid', 'title', 'user_id', 'finished_date', 'duration'],
			return_counts = False,
			limit = 10
		)

		tpl = template.Root(running_experiments(), past_experiments, saved_sketches)
		request.write("<!DOCTYPE html>\n")
		d = flatten(request, tpl, request.write)
		d.addCallbacks(lambda _: request.finish())
		d.addErrback(_error, request)

		return server.NOT_DONE_YET
Esempio n. 5
0
def create_pip_index(scratch_directory, packages):
    """
    Create an index file for pip.

    :param FilePath scratch_directory: Temporary directory to create index in.
    :param list packages: List of bytes, filenames of packages to be in the
        index.
    """
    index_file = scratch_directory.child('index.html')
    with index_file.open('w') as f:
        # Although this returns a Deferred, it works without the reactor
        # because there are no Deferreds in the template evaluation.
        # See this cheat described at
        # https://twistedmatrix.com/documents/15.0.0/web/howto/twisted-templates.html
        template.flatten(None, PackagesElement(packages), f.write)
    return index_file
Esempio n. 6
0
    def render_GET (self, request):
        saved_sketches = sketch.find(
            default_search = {
                'deleted': { 'value': 0 }
            }, order = [
                { 'column': 'modified_date', 'dir': 'desc' }
            ],
            fetch_columns = ['guid', 'title', 'user_id', 'modified_date'],
            return_counts = False,
        )

        past_experiments = experiment.find(
            default_search = {
                'deleted': { 'value': 0 },
                'finished_date': { 'value': 0, 'operator': 'gt' }
            }, order = [
                { 'column': 'finished_date', 'dir': 'desc' }
            ],
            fetch_columns = ['guid', 'title', 'user_id', 'finished_date', 'duration'],
            return_counts = False,
            limit = 10
        )

        tpl = template.Root(running_experiments(), past_experiments, saved_sketches)
        request.write("<!DOCTYPE html>\n".encode('utf-8'))
        d = flatten(request, tpl, request.write)
        d.addCallbacks(lambda _: request.finish())
        d.addErrback(_error, request)

        return server.NOT_DONE_YET
Esempio n. 7
0
def create_pip_index(scratch_directory, packages):
    """
    Create an index file for pip.

    :param FilePath scratch_directory: Temporary directory to create index in.
    :param list packages: List of bytes, filenames of packages to be in the
        index.
    """
    index_file = scratch_directory.child('index.html')
    with index_file.open('w') as f:
        # Although this returns a Deferred, it works without the reactor
        # because there are no Deferreds in the template evaluation.
        # See this cheat described at
        # https://twistedmatrix.com/documents/15.0.0/web/howto/twisted-templates.html
        template.flatten(None, PackagesElement(packages), f.write)
    return index_file
Esempio n. 8
0
 def render_POST(self, request):
     baseurl = request.args["baseurl"][0]
     revurl = reverseUrl(baseurl)
     row = getRow(revurl)
     deferred = flatten(request, WebPage(baseurl, revurl, row), request.write)
     deferred.addCallback(finish_request, request)
     deferred.addErrback(flattenerror, request)
     return NOT_DONE_YET
Esempio n. 9
0
    def render_GET(self, request):
        request.write("<!doctype html>\n")

        d = flatten(request, StatusElement(self.master), request.write)
        d.addCallback(lambda _: request.finish())
        d.addErrback(request.processingFailed)

        return NOT_DONE_YET
Esempio n. 10
0
    def render_GET(self, request):
        d = flatten(request, self.index, request.write)

        def done_index(ignored):
            request.finish()

        d.addBoth(done_index)
        return server.NOT_DONE_YET
Esempio n. 11
0
    def render_GET(self, request):
        request.write("<!doctype html>\n")

        d = flatten(request, StatusElement(self.master), request.write)
        d.addCallback(lambda _: request.finish())
        d.addErrback(request.processingFailed)

        return NOT_DONE_YET
		def _done (exists):
			if not exists:
				request.write("Sketch %s not found." % self._id)
				request.finish()
				return

			tpl = template.SketchEdit(self._id)
			request.write("<!DOCTYPE html>\n")
			d = flatten(request, tpl, request.write)
			d.addCallbacks(lambda _: request.finish())
Esempio n. 13
0
    def render_GET(self, request):
        d = flatten(request, CancerElement(), request.write)
        @d.addCallback
        def flattened(none):
            request.finish()

        # Jumpstart page rendering.
        request.write(" " * 4096)
        request.write("<!DOCTYPE html>")
        return NOT_DONE_YET
Esempio n. 14
0
        def _done(exists):
            if not exists:
                request.write(f"Sketch {self._id} not found.".encode('utf-8'))
                request.finish()
                return

            tpl = template.SketchEdit(self._id)
            request.write("<!DOCTYPE html>\n".encode('utf-8'))
            d = flatten(request, tpl, request.write)
            d.addCallbacks(lambda _: request.finish())
Esempio n. 15
0
def renderElement(request, element):
	# per http://stackoverflow.com/questions/8160061/twisted-web-resource-resource-with-twisted-web-template-element-example
	# should be replaced with twisted.web.template.renderElement once we have Twisted >= 12.1.0 available in MacPorts.
	d = template.flatten(request, element, request.write)
	
	def done(ignored):
		request.finish()
		return ignored
	
	d.addBoth(done)
	return server.NOT_DONE_YET
Esempio n. 16
0
def flattenToFile(fobj: IO[bytes], page: Element) -> None:
    """
    This method writes a page to a HTML file.
    @raises Exception: If the L{flatten} call fails.
    """
    fobj.write(DOCTYPE)
    err: List[Failure] = []
    d = flatten(None, page, fobj.write).addErrback(err.append)
    assert d.called
    if err:
        raise err[0]
Esempio n. 17
0
def renderElement(request, element):
    # per http://stackoverflow.com/questions/8160061/twisted-web-resource-resource-with-twisted-web-template-element-example
    # should be replaced with twisted.web.template.renderElement once we have Twisted >= 12.1.0 available in MacPorts.
    d = template.flatten(request, element, request.write)

    def done(ignored):
        request.finish()
        return ignored

    d.addBoth(done)
    return server.NOT_DONE_YET
Esempio n. 18
0
    def render(self, request):
        setRequestCatalog(request)
        form = self.form(request)
        request.write('<!DOCTYPE html>\n')
        if request.method == "POST" and form.validate():
            content = tags.span("Form Valid!")
        else:
            content = FormElement(form)

        done = flatten(request, Layout(content), request.write)
        done.addCallback(lambda r: request.finish())
        return server.NOT_DONE_YET
Esempio n. 19
0
    def render_GET(self, request):
        """Render SimpleStats main page."""
        request.write("<!DOCTYPE html>\n")
        data_element = ChartDataElement(self.datastore)
        d = flatten(request, data_element, request.write)

        def done(_):
            request.finish()
            return _

        d.addBoth(done)
        return server.NOT_DONE_YET
Esempio n. 20
0
File: web.py Progetto: JDShu/bravo
    def render_GET(self, request):
        def write(s):
            if not request._disconnected:
                request.write(s)

        d = flatten(request, self.element, write)
        @d.addCallback
        def complete_request(html):
            if not request._disconnected:
                request.finish()

        return NOT_DONE_YET
Esempio n. 21
0
    def render_GET(self, request):
        """Render SimpleStats main page."""
        request.write("<!DOCTYPE html>\n")
        data_element = ChartDataElement(self.datastore)
        d = flatten(request, data_element, request.write)

        def done(_):
            request.finish()
            return _

        d.addBoth(done)
        return server.NOT_DONE_YET
Esempio n. 22
0
File: web.py Progetto: tazjel/bravo
    def render_GET(self, request):
        def write(s):
            if not request._disconnected:
                request.write(s)

        d = flatten(request, self.element, write)

        @d.addCallback
        def complete_request(html):
            if not request._disconnected:
                request.finish()

        return NOT_DONE_YET
Esempio n. 23
0
    def render_GET(self, request):
        d = flatten(request, self.element, request.write)
        template_name = "template.xml"
#        element = self.loader.load(template_name)

        def cb(content):
            request.write(content)
            request.setResponseCode(200)
            request.finish()

        d = element.render(template_name)
        d.addCallback(cb)
        return server.NOT_DONE_YET
Esempio n. 24
0
def renderElement(request, element):
    # per http://stackoverflow.com/questions/8160061/twisted-web-resource-resource-with-twisted-web-template-element-example
    # should be replaced with twisted.web.template.renderElement once we have Twisted >= 12.1.0 available in MacPorts.

    # TODO: Instead of this kludge (here because it would be a syntax error in the XHTML template}, serve XHTML and fix the client-side issues that pop up due to element-name capitalization.
    request.write(b'<!doctype html>')

    d = template.flatten(request, element, request.write)

    def done(ignored):
        request.finish()
        return ignored

    d.addBoth(done)
    return NOT_DONE_YET
Esempio n. 25
0
def renderElement(request, element):
    # per http://stackoverflow.com/questions/8160061/twisted-web-resource-resource-with-twisted-web-template-element-example
    # should be replaced with twisted.web.template.renderElement once we have Twisted >= 12.1.0 available in MacPorts.
    
    # TODO: Instead of this kludge (here because it would be a syntax error in the XHTML template}, serve XHTML and fix the client-side issues that pop up due to element-name capitalization.
    request.write('<!doctype html>')
    
    d = template.flatten(request, element, request.write)
    
    def done(ignored):
        request.finish()
        return ignored
    
    d.addBoth(done)
    return server.NOT_DONE_YET
Esempio n. 26
0
    def _render_GET(self, request):
        request.write("<!DOCTYPE html>\n".encode('utf-8'))

        try:
            expt = yield self._getExperiment(self._id)
        except Exception as e:
            request.write(f"There was an error: {str(e)}".encode('utf-8'))
            request.finish()
            return

        tpl = template.ExperimentDownload(
            experiment.CompletedExperiment(self._id))

        yield flatten(request, tpl, request.write)

        request.finish()
	def _render_GET (self, request):
		request.write("<!DOCTYPE html>\n")

		try:
			expt = yield self._getExperiment(self._id)
		except Exception as e:
			request.write("There was an error: " + str(e))
			request.finish()
			return

		tpl = template.ExperimentDownload(
			experiment.CompletedExperiment(self._id)
		)

		yield flatten(request, tpl, request.write)

		request.finish()
Esempio n. 28
0
        def _done (exists):
            if not exists:
                request.write(f"Experiment {self._id} not found.".encode('utf-8'))
                request.finish()
                return

            expt = next((expt for expt in running_experiments() if expt.id == self._id), None)

            request.write("<!DOCTYPE html>\n".encode('utf-8'))
            if expt is not None:
                tpl = template.ExperimentRunning(expt)
            else:
                tpl = template.ExperimentResult(
                    experiment.CompletedExperiment(self._id)
                )

            d = flatten(request, tpl, request.write)
            d.addCallbacks(lambda _: request.finish())
		def _done (exists):
			if not exists:
				request.write("Experiment %s not found." % self._id)
				request.finish()
				return

			expt = next((expt for expt in running_experiments() if expt.id == self._id), None)

			request.write("<!DOCTYPE html>\n")
			if expt is not None:
				tpl = template.ExperimentRunning(expt)
			else:
				tpl = template.ExperimentResult(
					experiment.CompletedExperiment(self._id)
				)

			d = flatten(request, tpl, request.write)
			d.addCallbacks(lambda _: request.finish())
Esempio n. 30
0
 def render_GET(self, request):
     deferred = flatten(request, WebPage(), request.write)
     deferred.addCallback(finish_request, request)
     # in case of error we don't want the browser to stay stuck
     deferred.addErrback(flattenerror, request)
     return NOT_DONE_YET
Esempio n. 31
0
 def _render_page(self, request, element):
     d = flatten(request, element, request.write)
     def done(x):
         request.finish()
         return x
     d.addBoth(done)
Esempio n. 32
0
    def getChild(self, path, request):
        request.postpath = []

        if self.master.config["web_function"] != "ddl":
            self.brief = "DDL Disabled"
            self.detail = "The owner of this txoffer instance has chosen to disable DDL. Use XDCC or pester them to turn it back on."
            return self

        try:
            number = int(path)
        except:
            self.brief = "Invalid Pack Number"
            self.detail = "Given pack number \"{}\" is not a valid integer".format(path)
            return self

        if number not in self.master.packs:
            self.brief = "No Such Pack"
            self.detail = "Could not find a pack with number \"{:d}\".".format(number)
            return self

        if not os.path.isfile(self.master.packs[number]):
            self.brief = "Pack #{:d} Deleted".format(number)
            self.detail = "{} no longer exists.".format(os.path.basename(self.master.packs[number]))
            return self

        if self.master.config["proxy_header"] is not None:
            host = request.getHeader(self.master.config["proxy_header"])
        else:
            host = request.getClientIP()

        if host in self.factory.authorized and number in self.factory.authorized[host]:
            if self.master.config["log_requests"]:
                log.msg("Serving: {} - {}".format(host, os.path.basename(self.master.packs[number])), system="WEB")
            self.factory.authorized[host].remove(number)
            request.notifyFinish().addBoth(self.factory.done, host, number)
            r = EncodingResourceWrapper(File(self.master.packs[number]), [GzipEncoderFactory()])
            return ThrottledResource(r, self.master.downloads[host][number], limit=self.master.config["throttle"])

        elif host in self.master.downloads and number in self.master.downloads[host]:
            request.redirect("/")
            self.type = self.types.REDIRECT
            return self

        else:
            try:
                position = list(self.master.queue).index((self.factory, host, number)) + 1
                element = QueueElement(self.master, os.path.basename(self.master.packs[number]), position)
                request.write("<!doctype html>\n")

                d = flatten(request, element, request.write)
                d.addCallback(lambda _: request.finish())
                d.addErrback(request.processingFailed)

                self.type = self.types.QUEUE
                return self

            except ValueError:
                self.master.queue.append((self.factory, host, number))
                self.master.checkQueue()
                request.redirect("/pack/{:d}/{}".format(number, os.path.basename(self.master.packs[number])))
                self.type = self.types.REDIRECT
                return self
Esempio n. 33
0
from twisted.internet.defer import Deferred

sample = XMLString(
    """
    <div xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1">
    Before waiting ...
    <span t:render="wait"></span>
    ... after waiting.
    </div>
    """)

class WaitForIt(Element):
    def __init__(self):
        Element.__init__(self, loader=sample)
        self.deferred = Deferred()

    @renderer
    def wait(self, request, tag):
        return self.deferred.addCallback(
            lambda aValue: tag("A value: " + repr(aValue)))

def done(ignore):
    print("[[[Deferred fired.]]]")

print('[[[Rendering the template.]]]')
it = WaitForIt()
flatten(None, it, sys.stdout.write).addCallback(done)
print('[[[In progress... now firing the Deferred.]]]')
it.deferred.callback("<value>")
print('[[[All done.]]]')
Esempio n. 34
0
    def getChild(self, path, request):
        request.postpath = []

        if self.master.config["web_function"] != "ddl":
            self.brief = "DDL Disabled"
            self.detail = "The owner of this txoffer instance has chosen to disable DDL. Use XDCC or pester them to turn it back on."
            return self

        try:
            number = int(path)
        except:
            self.brief = "Invalid Pack Number"
            self.detail = "Given pack number \"{}\" is not a valid integer".format(path)
            return self

        if number not in self.master.packs:
            self.brief = "No Such Pack"
            self.detail = "Could not find a pack with number \"{:d}\".".format(number)
            return self

        if not os.path.isfile(self.master.packs[number]):
            self.brief = "Pack #{:d} Deleted".format(number)
            self.detail = "{} no longer exists.".format(os.path.basename(self.master.packs[number]))
            return self

        if self.master.config["proxy_header"] is not None:
            host = request.getHeader(self.master.config["proxy_header"])
        else:
            host = request.getClientIP()

        if host in self.factory.authorized and number in self.factory.authorized[host]:
            if self.master.config["log_requests"]:
                log.msg("Serving: {} - {}".format(host, os.path.basename(self.master.packs[number])), system="WEB")
            self.factory.authorized[host].remove(number)
            request.notifyFinish().addBoth(self.factory.done, host, number)
            r = EncodingResourceWrapper(File(self.master.packs[number]), [GzipEncoderFactory()])
            return ThrottledResource(r, self.master.downloads[host][number], limit=self.master.config["throttle"])

        elif host in self.master.downloads and number in self.master.downloads[host]:
            request.redirect("/")
            self.type = self.types.REDIRECT
            return self

        else:
            try:
                position = list(self.master.queue).index((self.factory, host, number)) + 1
                element = QueueElement(self.master, os.path.basename(self.master.packs[number]), position)
                request.write("<!doctype html>\n")

                d = flatten(request, element, request.write)
                d.addCallback(lambda _: request.finish())
                d.addErrback(request.processingFailed)

                self.type = self.types.QUEUE
                return self

            except ValueError:
                self.master.queue.append((self.factory, host, number))
                self.master.checkQueue()
                request.redirect("/pack/{:d}/{}".format(number, os.path.basename(self.master.packs[number])))
                self.type = self.types.REDIRECT
                return self
Esempio n. 35
0
 def render_GET(self, request):
     element = IndexElement(self.store)
     d = flatten(request, element, request.write)
     d.addCallback(lambda none: request.finish())
     return NOT_DONE_YET