code
stringlengths
1
18.2k
def child(self, path): """ Override the base implementation to inject the share ID our constructor was passed. """ if self._shareID is not None: self = url.URL.child(self, self._shareID) self._shareID = None return url.URL.child(self, path)
def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment): """ Override the base implementation to pass along the share ID our constructor was passed. """ return self.__class__( self._shareID, scheme, netloc, pathsegs, querysegs, fragment)
def locateChild(self, ctx, segments): """ Retrieve a L{SharingIndex} for a particular user, or rend.NotFound. """ store = _storeFromUsername( self.loginSystem.store, segments[0].decode('utf-8')) if store is None: return rend.NotFound return (SharingIndex(store, self.webViewer), segments[1:])
def locateChild(self, ctx, segments): """ Look up a shared item for the role viewing this SharingIndex and return a L{PublicAthenaLivePage} containing that shared item's fragment to the user. These semantics are UNSTABLE. This method is adequate for simple uses, but it should be expanded in the future to be more consis...
to return the default share. if we find one, then # let's use that defaultShareID = getDefaultShareID(self.userStore) try: sharedItem = role.getShare(defaultShareID) except sharing.NoSuchShare: return rend.NotFound # otherwise the user is trying to access some other share else: # let's see if it's a real share try: sha...
def _set_autocommit(connection): """Make sure a connection is in autocommit mode.""" if hasattr(connection.connection, "autocommit"): if callable(connection.connection.autocommit): connection.connection.autocommit(True) else: connection.connection.autocommit = True elif hasattr(connection.connection, "set_isolation_lev...
def _patch_static_handler(handler): """Patch in support for static files serving if supported and enabled. """ if django.VERSION[:2] < (1, 3): return from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def _inject_selenium(self, test): """ Injects a selenium instance into the method. """ from django.conf import settings test_case = get_test_case_class(test) test_case.selenium_plugin_started = True # Provide some reasonable default values sel = selenium( getattr(settings, "SELENIUM_HOST", "localhost"), int(getattr(set...
def server_bind(self): """Bind server to socket. Overrided to store server name and set timeout. """ try: HTTPServer.server_bind(self) except Exception as e: raise WSGIServerException(e) self.setup_environ() self.socket.settimeout(1)
def result(self, wait=False): """ Gets the result of the method call. If the call was successful, return the result, otherwise, reraise the exception. :param wait: Block until the result is available, or just get the result. :raises: RuntimeError when called and the result is not yet available. """ if wait: self._async...
def post_build(self, container_builder, container): """ This method make sure the flask configuration is fine, and check the if ioc.extra.jinja2 service is available. If so, the flask instance will use this service, by keeping the flask template loader and the one registered at the jinja2 """ app = container.get('ioc.e...
def start(self): """ Start to listen for incoming requests. """ assert not self._started self._listening_stream.on_recv(self._recv_callback) self._started = True
def _create_listening_stream(self, pull_addr): """ Create a stream listening for Requests. The `self._recv_callback` method is asociated with incoming requests. """ sock = self._zmq_context.socket(zmq.PULL) sock.connect(pull_addr) stream = ZMQStream(sock, io_loop=self.io_loop) return stream
def _create_sending_stream(self, pub_addr): """ Create a `ZMQStream` for sending responses back to Mongrel2. """ sock = self._zmq_context.socket(zmq.PUB) sock.setsockopt(zmq.IDENTITY, self.sender_id) sock.connect(pub_addr) stream = ZMQStream(sock, io_loop=self.io_loop) return stream
def _recv_callback(self, msg): """ Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String. """ m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, no_keep_alive=self.no_keep_alive, xheaders=self.xheader...
def _begin_request(self): """ Actually start executing this request. """ headers = self.m2req.headers self._request = HTTPRequest(connection=self, method=headers.get("METHOD"), uri=self.m2req.path, version=headers.get("VERSION"), headers=headers, remote_ip=headers.get("x-forwarded-for")) if len(self.m2req.body) > 0: se...
def finish(self): """ Finish this connection. """ assert self._request, "Request closed" self._request_finished = True if self.m2req.should_close() or self.no_keep_alive: self._send("") self._request = None
def _send(self, msg): """ Raw send to the given connection ID at the given uuid, mostly used internally. """ uuid = self.m2req.sender conn_id = self.m2req.conn_id header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id)) zmq_message = header + ' ' + msg self.stream.send(zmq_message)
def _json_default_encoder(func): """ Monkey-Patch the core json encoder library. This isn't as bad as it sounds. We override the default method so that if an object falls through and can't be encoded normally, we see if it is a Future object and return the result to be encoded. I set a special attribute on the Struct o...
noqa except AttributeError: pass return func(self, o) return inner
def as_completed(*async_result_wrappers): """ Yields results as they become available from asynchronous method calls. Example usage :: async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)] for async_call in gemstone.as_completed(*async_calls): print("just finished with result ", async_call.resu...
def first_completed(*async_result_wrappers): """ Just like :py:func:`as_completed`, but returns only the first item and discards the rest. :param async_result_wrappers: :return: .. versionadded:: 0.5.0 """ for item in async_result_wrappers: if not isinstance(item, AsyncMethodCall): raise TypeError("Got non-AsyncMethodC...
def dynamic_load(module_or_member): """ Dynamically loads a class or member of a class. If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``. If ``module_or_member`` is something like ``"a"`` will perform ``import a`` :param module_or_member: the name of a module or member of a modu...
def encode(cls, value): """ convert a boolean value into something we can persist to redis. An empty string is the representation for False. :param value: bool :return: bytes """ if value not in [True, False]: raise InvalidValue('not a boolean') return b'1' if value else b''
def encode(cls, value): """ encode a floating point number to bytes in redis :param value: float :return: bytes """ try: if float(value) + 0 == value: return repr(value) except (TypeError, ValueError): pass raise InvalidValue('not a float')
def encode(cls, value): """ take an integer and turn it into a string representation to write into redis. :param value: int :return: str """ try: coerced = int(value) if coerced + 0 == value: return repr(coerced) except (TypeError, ValueError): pass raise InvalidValue('not an int')
def encode(cls, value): """ take a valid unicode string and turn it into utf-8 bytes :param value: unicode, str :return: bytes """ coerced = unicode(value) if coerced == value: return coerced.encode(cls._encoding) raise InvalidValue('not text')
def encode(cls, value): """ take a list of strings and turn it into utf-8 byte-string :param value: :return: """ coerced = unicode(value) if coerced == value and cls.PATTERN.match(coerced): return coerced.encode(cls._encoding) raise InvalidValue('not ascii')
def encode(cls, value): """ write binary data into redis without encoding it. :param value: bytes :return: bytes """ try: coerced = bytes(value) if coerced == value: return coerced except (TypeError, UnicodeError): pass raise InvalidValue('not binary')
def encode(cls, value): """ take a list and turn it into a utf-8 encoded byte-string for redis. :param value: list :return: bytes """ try: coerced = list(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) except TypeError: pass raise InvalidValue('not a list')
def decode(cls, value): """ take a utf-8 encoded byte-string from redis and turn it back into a list :param value: bytes :return: list """ try: return None if value is None else \ list(json.loads(value.decode(cls._encoding))) except (TypeError, AttributeError): return list(value)
def encode(cls, value): """ encode the dict as a json string to be written into redis. :param value: dict :return: bytes """ try: coerced = dict(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) except (TypeError, ValueError): pass raise InvalidValue('not a dict')
def decode(cls, value): """ decode the data from redis. :param value: bytes :return: list """ try: data = [v for v in value.decode(cls._encoding).split(',') if v != ''] return data if data else None except AttributeError: return value
def encode(cls, value): """ the list it so it can be stored in redis. :param value: list :return: bytes """ try: coerced = [str(v) for v in value] if coerced == value: return ",".join(coerced).encode(cls._encoding) if len( value) > 0 else None except TypeError: pass raise InvalidValue('not a list of strings')
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.cli.add_command(openaire) before_record_index.connect(indexer_receiver, sender=app) app.extensions['invenio-openaire'] = self
def swap_twitter_subject(subject, body): """If subject starts from 'Tweet from...' then we need to get first meaning line from the body.""" if subject.startswith('Tweet from'): lines = body.split('\n') for idx, line in enumerate(lines): if re.match(r'.*, ?\d{2}:\d{2}]]', line) is not None: try: subject = lines[idx + 1]...
def trial(log_dir=None, upload_dir=None, sync_period=None, trial_prefix="", param_map=None, init_logging=True): """ Generates a trial within a with context. """ global _trial # pylint: disable=global-statement if _trial: # TODO: would be nice to stack crawl at creation time to report # where that initial trial was crea...
def index(index, length): """Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to use them, the indexed object must convert them to the correct, p...
def range_to_numeric(ranges): """Converts a sequence of string ranges to a sequence of floats. E.g.:: >>> range_to_numeric(['1 uV', '2 mV', '1 V']) [1E-6, 0.002, 1.0] """ values, units = zip(*(r.split() for r in ranges)) # Detect common unit. unit = os.path.commonprefix([u[::-1] for u in units]) # Strip unit to get jus...
def wrap_exception(exc, new_exc): """Catches exceptions `exc` and raises `new_exc(exc)` instead. E.g.:: >>> class MyValueError(Exception): ... '''Custom ValueError.''' ... @wrap_exception(exc=ValueError, new_exc=MyValueError) ... def test(): ... raise ValueError() """ def make_wrapper(fn): @functools.wraps(fn) def wrap...
def range(self, value): """Estimates an appropriate sensitivity range.""" self._buffer.append(abs(value)) mean = sum(self._buffer) / len(self._buffer) estimate = next( (r for r in self.ranges if mean < self.scale * r), self.ranges[-1] ) if self._mapping: return self._mapping[estimate] else: return estimate
def add(self, schema, data): """ Stage ``data`` as a set of statements, based on the given ``schema`` definition. """ binding = self.get_binding(schema, data) uri, triples = triplify(binding) for triple in triples: self.graph.add(triple) return uri
def save(self): """ Transfer the statements in this context over to the main store. """ if self.parent.buffered: query = """ INSERT DATA { GRAPH %s { %s } } """ query = query % (self.identifier.n3(), self.graph.serialize(format='nt')) self.parent.graph.update(query) self.flush() else: self.meta.generate()
def delete(self): """ Delete all statements matching the current context identifier from the main store. """ if self.parent.buffered: query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3() self.parent.graph.update(query) self.flush() else: self.graph.remove((None, None, None))
def read_bytes(self, num_bytes): """Reads at most `num_bytes`.""" buffer_size = len(self._buffer) if buffer_size > num_bytes: # The buffer is larger than the requested amount of bytes. data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:] elif 0 < buffer_size <= num_bytes: # This might return less byt...
def read_until(self, delimiter): """Reads until the delimiter is found.""" if delimiter in self._buffer: data, delimiter, self._buffer = self._buffer.partition(delimiter) return data else: self._buffer += self.__read__(self._max_bytes) return self.read_until(delimiter)
def close(self): """Closes the gpib transport.""" if self._device is not None: ibsta = self._lib.ibonl(self._device, 0) self._check_status(ibsta) self._device = None
def trigger(self): """Triggers the device. The trigger method sens a GET(group execute trigger) command byte to the device. """ ibsta = self._lib.ibtrg(self._device) self._check_status(ibsta)
def _check_status(self, ibsta): """Checks ibsta value.""" if ibsta & 0x4000: raise LinuxGpib.Timeout() elif ibsta & 0x8000: raise LinuxGpib.Error(self.error_status)
def run(self): """ Just run wget quietly. """ output = shellout('wget -q "{url}" -O {output}', url=self.url) luigi.LocalTarget(output).move(self.output().path)
def output(self): """ Use the digest version, since URL can be ugly. """ return luigi.LocalTarget(path=self.path(digest=True, ext='html'))
def run(self): """ Construct the document id from the date and the url. """ document = {} document['_id'] = hashlib.sha1('%s:%s' % ( self.date, self.url)).hexdigest() with self.input().open() as handle: document['content'] = handle.read().decode('utf-8', 'ignore') document['url'] = self.url document['date'] = unicode(s...
def run(self): """ Index the document. Since ids are predictable, we won't index anything twice. """ with self.input().open() as handle: body = json.loads(handle.read()) es = elasticsearch.Elasticsearch() id = body.get('_id') es.index(index='frontpage', doc_type='html', id=id, body=body)
def complete(self): """ Check, if out hashed date:url id is already in the index. """ id = hashlib.sha1('%s:%s' % (self.date, self.url)).hexdigest() es = elasticsearch.Elasticsearch() try: es.get(index='frontpage', doc_type='html', id=id) except elasticsearch.NotFoundError: return False return True
def requires(self): """ Index all pages. """ for url in NEWSPAPERS: yield IndexPage(url=url, date=self.date)
def get_name(self, data): """ For non-specific queries, this will return the actual name in the result. """ if self.node.specific_attribute: return self.node.name name = data.get(self.predicate_var) if str(RDF.type) in [self.node.name, name]: return '$schema' if name.startswith(PRED): name = name[len(PRED):] return nam...
def project(self, q, parent=False): """ Figure out which attributes should be returned for the current level of the query. """ if self.parent: print (self.parent.var, self.predicate, self.var) q = q.project(self.var, append=True) if parent and self.parent: q = q.project(self.parent.var, append=True) if not self.node.sp...
def filter(self, q, parents=None): """ Apply any filters to the query. """ if self.node.leaf and self.node.filtered: # TODO: subject filters? q = q.where((self.parent.var, self.predicate, self.var)) # TODO: inverted nodes q = self.filter_value(q, self.var) elif self.parent is not None: q = q.where((self.parent.var, sel...
def query(self, parents=None): """ Compose the query and generate SPARQL. """ # TODO: benchmark single-query strategy q = Select([]) q = self.project(q, parent=True) q = self.filter(q, parents=parents) if self.parent is None: subq = Select([self.var]) subq = self.filter(subq, parents=parents) subq = subq.offset(self.no...
def base_object(self, data): """ Make sure to return all the existing filter fields for query results. """ obj = {'id': data.get(self.id)} if self.parent is not None: obj['$parent'] = data.get(self.parent.id) return obj
def execute(self, parents=None): """ Run the data query and construct entities from it's results. """ results = OrderedDict() for row in self.query(parents=parents).execute(self.context.graph): data = {k: v.toPython() for (k, v) in row.asdict().items()} id = data.get(self.id) if id not in results: results[id] = self.ba...
def collect(self, parents=None): """ Given re-constructed entities, conduct queries for child entities and merge them into the current level's object graph. """ results = self.execute(parents=parents) ids = results.keys() for child in self.nested(): name = child.node.name for child_data in child.collect(parents=ids).va...
def _download_and_decompress_if_necessary( full_path, download_url, timeout=None, use_wget_if_available=False): """ Downloads remote file at `download_url` to local file at `full_path` """ logger.info("Downloading %s to %s", download_url, full_path) filename = os.path.split(full_path)[1] base_name, ext = os.path.splite...
as dst: dst.write(contents) elif download_url.endswith(("html", "htm")) and full_path.endswith(".csv"): logger.info("Extracting HTML table into CSV %s...", filename) df = pd.read_html(tmp_path, header=0)[0] df.to_csv(full_path, sep=',', index=False, encoding='utf-8') else: move(tmp_path, full_path)
def file_exists( download_url, filename=None, decompress=False, subdir=None): """ Return True if a local file corresponding to these arguments exists. """ filename = build_local_filename(download_url, filename, decompress) full_path = build_path(filename, subdir) return os.path.exists(full_path)
def fetch_file( download_url, filename=None, decompress=False, subdir=None, force=False, timeout=None, use_wget_if_available=False): """ Download a remote file and store it locally in a cache directory. Don't download it again if it's already present (unless `force` is True.) Parameters ---------- download_url : str Re...
remote file is not downloaded if it's already present. However, with this argument set to True, it will be overwritten. timeout : float, optional Timeout for download in seconds, default is None which uses global timeout. use_wget_if_available: bool, optional If the `wget` command is available, use that for download in...
def fetch_and_transform( transformed_filename, transformer, loader, source_filename, source_url, subdir=None): """ Fetch a remote file from `source_url`, save it locally as `source_filename` and then use the `loader` and `transformer` function arguments to turn this saved data into an in-memory object. """ transformed_...
def fetch_csv_dataframe( download_url, filename=None, subdir=None, **pandas_kwargs): """ Download a remote file from `download_url` and save it locally as `filename`. Load that local file as a CSV into Pandas using extra keyword arguments such as sep='\t'. """ path = fetch_file( download_url=download_url, filename=file...
def getLoader(*a, **kw): """ Deprecated. Don't use this. """ warn("xmantissa.publicweb.getLoader is deprecated, use " "PrivateApplication.getDocFactory or SiteTemplateResolver." "getDocFactory.", category=DeprecationWarning, stacklevel=2) from xmantissa.webtheme import getLoader return getLoader(*a, **kw)
def renderShortUsername(ctx, username): """ Render a potentially shortened version of the user's login identifier, depending on how the user is viewing it. For example, if bob@example.com is viewing http://example.com/private/, then render 'bob'. If bob instead signed up with only his email address (bob@hotmail.com), a...
def _installV2Powerups(anonymousSite): """ Install the given L{AnonymousSite} for the powerup interfaces it was given in version 2. """ anonymousSite.store.powerUp(anonymousSite, IWebViewer) anonymousSite.store.powerUp(anonymousSite, IMantissaSite)
def createResource(self): """ When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex} for my application. """ pp = ixmantissa.IPublicPage(self.application, None) if pp is not None: warn( "Use the sharing system to provide public pages, not IPublicPage", category=DeprecationWarning, stacklevel=2) return p...
def _wrapNavFrag(self, frag, useAthena): """ Wrap the given L{INavigableFragment} in the appropriate type of L{_PublicPageMixin}. """ if useAthena: return PublicAthenaLivePage(self._siteStore, frag) else: return PublicPage(None, self._siteStore, frag, None, None)
def locateChild(self, ctx, segments): """ Return a Deferred which will fire with the customized version of the resource being located. """ D = defer.maybeDeferred( self.currentResource.locateChild, ctx, segments) def finishLocating((nextRes, nextPath)): custom = ixmantissa.ICustomizable(nextRes, None) if custom is not ...
def produceResource(self, request, segments, webViewer): """ Produce a resource that traverses site-wide content, passing down the given webViewer. This delegates to the site store's L{IMantissaSite} adapter, to avoid a conflict with the L{ISiteRootPlugin} interface. This method will typically be given an L{_Authentica...
to easily access the L{IWebViewer} from view code has not yet been developed; it is forthcoming. See ticket #2707 for progress on this. """ mantissaSite = self.publicSiteRoot if mantissaSite is not None: for resource, domain in userbase.getAccountNames(self.store): username = '%s@%s' % (resource, domain) break else: us...
def _getViewerPrivateApplication(self): """ Get the L{PrivateApplication} object for the logged-in user who is viewing this resource, as indicated by its C{username} attribute. This is highly problematic because it precludes the possibility of separating the stores of the viewer and the viewee into separate processes, ...
a direct reference to the requisite object. @rtype: L{PrivateApplication} """ ls = self.store.findUnique(userbase.LoginSystem) substore = ls.accountByAddress(*self.username.split('@')).avatars.open() from xmantissa.webapp import PrivateApplication return substore.findUnique(PrivateApplication)
def render_authenticateLinks(self, ctx, data): """ For unauthenticated users, add login and signup links to the given tag. For authenticated users, remove the given tag from the output. When necessary, the I{signup-link} pattern will be loaded from the tag. Each copy of it will have I{prompt} and I{url} slots filled. T...
to cause any real # problems... -glyph from xmantissa.signup import _getPublicSignupInfo IQ = inevow.IQ(ctx.tag) signupPattern = IQ.patternGenerator('signup-link') signups = [] for (prompt, url) in _getPublicSignupInfo(self.store): signups.append(signupPattern.fillSlots( 'prompt', prompt).fillSlots( 'url', url)) return...
def render_startmenu(self, ctx, data): """ For authenticated users, add the start-menu style navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.startMenu} """ if self.username is None: return '' translator = self._getViewerPrivateApplication() pageCompo...
def render_settingsLink(self, ctx, data): """ For authenticated users, add the URL of the settings page to the given tag. For unauthenticated users, remove the given tag from the output. """ if self.username is None: return '' translator = self._getViewerPrivateApplication() return settingsLink( translator, translator....
def render_applicationNavigation(self, ctx, data): """ For authenticated users, add primary application navigation to the given tag. For unauthenticated users, remove the given tag from the output. @see L{xmantissa.webnav.applicationNavigation} """ if self.username is None: return '' translator = self._getViewerPrivate...
def render_search(self, ctx, data): """ Render some UI for performing searches, if we know about a search aggregator. """ if self.username is None: return '' translator = self._getViewerPrivateApplication() searchAggregator = translator.getPageComponents().searchAggregator if searchAggregator is None or not searchAggre...
def render_rootURL(self, ctx, data): """ Add the WebSite's root URL as a child of the given tag. """ return ctx.tag[ ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))]
def render_header(self, ctx, data): """ Render any required static content in the header, from the C{staticContent} attribute of this page. """ if self.staticContent is None: return ctx.tag header = self.staticContent.getHeader() if header is not None: return ctx.tag[header] else: return ctx.tag
def render_footer(self, ctx, data): """ Render any required static content in the footer, from the C{staticContent} attribute of this page. """ if self.staticContent is None: return ctx.tag header = self.staticContent.getFooter() if header is not None: return ctx.tag[header] else: return ctx.tag
def render_urchin(self, ctx, data): """ Render the code for recording Google Analytics statistics, if so configured. """ key = website.APIKey.getKeyForAPI(self.store, website.APIKey.URCHIN) if key is None: return '' return ctx.tag.fillSlots('urchin-key', key.apiKey)
def getHeadContent(self, req): """ Retrieve a list of header content from all installed themes on the site store. """ site = ixmantissa.ISiteURLGenerator(self.store) for t in getInstalledThemes(self.store): yield t.head(req, site)
def render_head(self, ctx, data): """ This renderer calculates content for the <head> tag by concatenating the values from L{getHeadContent} and the overridden L{head} method. """ req = inevow.IRequest(ctx) more = getattr(self.fragment, 'head', None) if more is not None: fragmentHead = more() else: fragmentHead = None ...
def data_offerings(self, ctx, data): """ Generate a list of installed offerings. @return: a generator of dictionaries mapping 'name' to the name of an offering installed on the store. """ for io in self.original.store.query(offering.InstalledOffering): pp = ixmantissa.IPublicPage(io.application, None) if pp is not None...
def locateChild(self, ctx, segments): """ Look up children in the normal manner, but then customize them for the authenticated user if they support the L{ICustomizable} interface. If the user is attempting to access a private URL, redirect them. """ result = self._getAppStoreResource(ctx, segments[0]) if result is not ...
return u, () return rend.NotFound
def _getAppStoreResource(self, ctx, name): """ Customize child lookup such that all installed offerings on the site store that this page is viewing are given an opportunity to display their own page. """ offer = self.frontPageItem.store.findFirst( offering.InstalledOffering, offering.InstalledOffering.offeringName == u...
def child_(self, ctx): """ If the root resource is requested, return the primary application's front page, if a primary application has been chosen. Otherwise return 'self', since this page can render a simple index. """ if self.frontPageItem.defaultApplication is None: return self.webViewer.wrapModel( _OfferingsFragme...
def beforeRender(self, ctx): """ Before rendering this page, identify the correct URL for the login to post to, and the error message to display (if any), and fill the 'login action' and 'error' slots in the template accordingly. """ generator = ixmantissa.ISiteURLGenerator(self.store) url = generator.rootURL(IRequest(...
def locateChild(self, ctx, segments): """ Return a clone of this page that remembers its segments, so that URLs like /login/private/stuff will redirect the user to /private/stuff after login has completed. """ arguments = IRequest(ctx).args return self.__class__( self.store, segments, arguments), ()
def fromRequest(cls, store, request): """ Return a L{LoginPage} which will present the user with a login prompt. @type store: L{Store} @param store: A I{site} store. @type request: L{nevow.inevow.IRequest} @param request: The HTTP request which encountered a need for authentication. This will be effectively re-issued a...
def render_head(self, ctx, data): """ Put liveglue content into the header of this page to activate it, but otherwise delegate to my parent's renderer for <head>. """ ctx.tag[tags.invisible(render=tags.directive('liveglue'))] return _PublicPageMixin.render_head(self, ctx, data)