code
stringlengths
1
18.2k
def add(self, *resources): """ Apply the tag to one or more resources :param resources: one or more `Resource` objects to which tags can be applied :return: `None` :raises DOAPIError: if the API endpoint replies with an error """ self.doapi_manager.request(self.url + '/resources', method='POST', data={"resources": _to_...
def act_on_droplets(self, **data): r""" Perform an arbitrary action on all of the droplets to which the tag is applied. ``data`` will be serialized as JSON and POSTed to the proper API endpoint. All currently-documented actions require the POST body to be a JSON object containing, at a minimum, a ``"type"`` field. :ret...
def add_badge_roles(app): """Add ``badge`` role to your sphinx documents. It can create a colorful badge inline. """ from docutils.nodes import inline, make_id from docutils.parsers.rst.roles import set_classes def create_badge_role(color=None): def badge_role(name, rawtext, text, lineno, inliner, options=None, content...
def add_github_roles(app, repo): """Add ``gh`` role to your sphinx documents. It can generate GitHub links easily:: :gh:`issue#57` will generate the issue link :gh:`PR#85` will generate the pull request link Use this function in ``conf.py`` to enable this feature:: def setup(app): sphinx_typlog_theme.add_github_roles(a...
node = reference(rawtext, text, refuri=url, **options) return [node], [] app.add_role('gh', github_role)
def promise(cls, fn, *args, **kwargs): """ Used to build a task based on a callable function and the arguments. Kick it off and start execution of the task. :param fn: callable :param args: tuple :param kwargs: dict :return: SynchronousTask or AsynchronousTask """ task = cls.task(target=fn, args=args, kwargs=kwargs) ta...
def _interfacesToNames(interfaces): """ Convert from a list of interfaces to a unicode string of names suitable for storage in the database. @param interfaces: an iterable of Interface objects. @return: a unicode string, a comma-separated list of names of interfaces. @raise ConflictingNames: if any of the names conflic...
def upgradeShare1to2(oldShare): "Upgrader from Share version 1 to version 2." sharedInterfaces = [] attrs = set(oldShare.sharedAttributeNames.split(u',')) for iface in implementedBy(oldShare.sharedItem.__class__): if set(iface) == attrs or attrs == set('*'): sharedInterfaces.append(iface) newShare = oldShare.upgradeVer...
def getAuthenticatedRole(store): """ Get the base 'Authenticated' role for this store, which is the role that is given to every user who is explicitly identified by a non-anonymous username. """ def tx(): def addToEveryone(newAuthenticatedRole): newAuthenticatedRole.becomeMemberOf(getEveryoneRole(store)) return newAuth...
def getPrimaryRole(store, primaryRoleName, createIfNotFound=False): """ Get Role object corresponding to an identifier name. If the role name passed is the empty string, it is assumed that the user is not authenticated, and the 'Everybody' role is primary. If the role name passed is non-empty, but has no corresponding ...
found. The default, False, will instead retrieve the 'nearest match' role, which can be Authenticated or Everybody depending on whether the user is logged in or not. @return: a L{Role}. """ if not primaryRoleName: return getEveryoneRole(store) ff = store.findUnique(Role, Role.externalID == primaryRoleName, default=None...
def getAccountRole(store, accountNames): """ Retrieve the first Role in the given store which corresponds an account name in C{accountNames}. Note: the implementation currently ignores all of the values in C{accountNames} except for the first. @param accountNames: A C{list} of two-tuples of account local parts and doma...
def shareItem(sharedItem, toRole=None, toName=None, shareID=None, interfaces=ALL_IMPLEMENTED): """ Share an item with a given role. This provides a way to expose items to users for later retrieval with L{Role.getShare}. This API is slated for deprecation. Prefer L{Role.shareItem} in new code. @param sharedItem: an item...
records the ability of the given role to access the given item. """ warnings.warn("Use Role.shareItem() instead of sharing.shareItem().", PendingDeprecationWarning, stacklevel=2) if toRole is None: if toName is not None: toRole = getPrimaryRole(sharedItem.store, toName, True) else: toRole = getEveryoneRole(sharedItem.s...
def _linearize(interface): """ Return a list of all the bases of a given interface in depth-first order. @param interface: an Interface object. @return: a L{list} of Interface objects, the input in all its bases, in subclass-to-base-class, depth-first order. """ L = [interface] for baseInterface in interface.__bases__:...
def _commonParent(zi1, zi2): """ Locate the common parent of two Interface objects. @param zi1: a zope Interface object. @param zi2: another Interface object. @return: the rightmost common parent of the two provided Interface objects, or None, if they have no common parent other than Interface itself. """ shorter, long...
def _checkConflictingNames(interfaces): """ Raise an exception if any of the names present in the given interfaces conflict with each other. @param interfaces: a list of Zope Interface objects. @return: None @raise ConflictingNames: if any of the attributes of the provided interfaces are the same, and they do not have ...
def getShare(store, role, shareID): """ Retrieve the accessible facet of an Item previously shared with L{shareItem}. This method is pending deprecation, and L{Role.getShare} should be preferred in new code. @param store: an axiom store (XXX must be the same as role.store) @param role: a L{Role}, the primary role for a...
def asAccessibleTo(role, query): """ Return an iterable which yields the shared proxies that are available to the given role, from the given query. This method is pending deprecation, and L{Role.asAccessibleTo} should be preferred in new code. @param role: The role to retrieve L{SharedProxy}s for. @param query: An Axio...
def unShare(sharedItem): """ Remove all instances of this item from public or shared view. """ sharedItem.store.query(Share, Share.sharedItem == sharedItem).deleteFromStore()
def randomEarlyShared(store, role): """ If there are no explicitly-published public index pages to display, find a shared item to present to the user as first. """ for r in role.allRoles(): share = store.findFirst(Share, Share.sharedTo == r, sort=Share.storeID.ascending) if share is not None: return share.sharedItem ra...
def fromSharedItem(cls, sharedItem): """ Return an instance of C{cls} derived from the given L{Item} that has been shared. Note that this API does not provide any guarantees of which result it will choose. If there are are multiple possible return values, it will select and return only one. Items may be shared under mu...
a user. """ localpart = None for (localpart, domain) in userbase.getAccountNames(sharedItem.store): break if localpart is None: raise NoSuchShare() for share in sharedItem.store.query(Share, Share.sharedItem == sharedItem): break else: raise NoSuchShare() return cls( shareID=share.shareID, localpart=localpart, domain=d...
def toString(self, obj): """ Convert the given L{Identifier} to a string. """ return Box(shareID=obj.shareID.encode('utf-8'), localpart=obj.localpart.encode('utf-8'), domain=obj.domain.encode('utf-8')).serialize()
def fromString(self, inString): """ Convert the given string to an L{Identifier}. """ box = parseString(inString)[0] return Identifier(shareID=box['shareID'].decode('utf-8'), localpart=box['localpart'].decode('utf-8'), domain=box['domain'].decode('utf-8'))
def becomeMemberOf(self, groupRole): """ Instruct this (user or group) Role to become a member of a group role. @param groupRole: The role that this group should become a member of. """ self.store.findOrCreate(RoleRelationship, group=groupRole, member=self)
def allRoles(self, memo=None): """ Identify all the roles that this role is authorized to act as. @param memo: used only for recursion. Do not pass this. @return: an iterator of all roles that this role is a member of, including itself. """ if memo is None: memo = set() elif self in memo: # this is bad, but we have suc...
def shareItem(self, sharedItem, shareID=None, interfaces=ALL_IMPLEMENTED): """ Share an item with this role. This provides a way to expose items to users for later retrieval with L{Role.getShare}. @param sharedItem: an item to be shared. @param shareID: a unicode string. If provided, specify the ID under which the shar...
def getShare(self, shareID): """ Retrieve a proxy object for a given shareID, previously shared with this role or one of its group roles via L{Role.shareItem}. @return: a L{SharedProxy}. This is a wrapper around the shared item which only exposes those interfaces explicitly allowed for the given role. @raise: L{NoSuchS...
def asAccessibleTo(self, query): """ @param query: An Axiom query describing the Items to retrieve, which this role can access. @type query: an L{iaxiom.IQuery} provider. @return: an iterable which yields the shared proxies that are available to the given role, from the given query. """ # XXX TODO #2371: this method re...
= list(query.store.query( Share, AND(Share.sharedItem == result, Share.sharedTo.oneOf(allRoles)))) interfaces = [] for share in allShares: interfaces += share.sharedInterfaces if allShares: count += 1 yield SharedProxy(result, interfaces, allShares[0].shareID) if count == query.limit: return
def sharedInterfaces(): """ This attribute is the public interface for code which wishes to discover the list of interfaces allowed by this Share. It is a list of Interface objects. """ def get(self): if not self.sharedInterfaceNames: return () if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB: I = implementedBy(self....
def every_minute(dt=datetime.datetime.utcnow(), fmt=None): """ Just pass on the given date. """ date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, 1, 0, dt.tzinfo) if fmt is not None: return date.strftime(fmt) return date
def hourly(dt=datetime.datetime.utcnow(), fmt=None): """ Get a new datetime object every hour. """ date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo) if fmt is not None: return date.strftime(fmt) return date
def weekly(date=datetime.date.today()): """ Weeks start are fixes at Monday for now. """ return date - datetime.timedelta(days=date.weekday())
def biweekly(date=datetime.date.today()): """ Every two weeks. """ return datetime.date(date.year, date.month, 1 if date.day < 15 else 15)
def monthly(date=datetime.date.today()): """ Take a date object and return the first day of the month. """ return datetime.date(date.year, date.month, 1)
def quarterly(date=datetime.date.today()): """ Fixed at: 1/1, 4/1, 7/1, 10/1. """ return datetime.date(date.year, ((date.month - 1)//3) * 3 + 1, 1)
def semiyearly(date=datetime.date.today()): """ Twice a year. """ return datetime.date(date.year, 1 if date.month < 7 else 7, 1)
def fragments(self, req, tag): """ Render our preference collection, any child preference collections we discover by looking at self.tab.children, and any fragments returned by its C{getSections} method. Subtabs and C{getSections} fragments are rendered as fieldsets inside the parent preference collection's tab. """ f ...
def tabbedPane(self, req, tag): """ Render a tabbed pane tab for each top-level L{xmantissa.ixmantissa.IPreferenceCollection} tab """ navigation = webnav.getTabs(self.aggregator.getPreferenceCollections()) pages = list() for tab in navigation: f = inevow.IRenderer( self.aggregator.store.getItemByID(tab.storeID)) f.tab ...
def resort(self, attributeID, isAscending=None): """Sort by one of my specified columns, identified by attributeID """ if isAscending is None: isAscending = self.defaultSortAscending newSortColumn = self.columns[attributeID] if newSortColumn.sortAttribute() is None: raise Unsortable('column %r has no sort attribute' % ...
def currentPage(self): """ Return a sequence of mappings of attribute IDs to column values, to display to the user. nextPage/prevPage will strive never to skip items whose column values have not been returned by this method. This is best explained by a demonstration. Let's say you have a table viewing an item with attr...
result of currentPage following that will be items beginning with item oid 2. This is because although there are no longer enough items to populate a full page from 0-1, the user has never seen item #2 on a page, so the 'next' page from the user's point of view contains #2. If instead, at that same point, the next thin...
def _sortAttributeValue(self, offset): """ return the value of the sort attribute for the item at 'offset' in the results of the last query, otherwise None. """ if self._currentResults: pageStart = (self._currentResults[offset][ self.currentSortColumn.attributeID], self._currentResults[offset][ '__item__'].storeID) els...
def open_display(self): """Establishes connection with X server and prepares objects necessary to retrieve and send data. """ self.close_display() # Properly finish previous open_display() XkbIgnoreExtension(False) display_name = None major = c_int(XkbMajorVersion) minor = c_int(XkbMinorVersion) reason = c_int() self._...
".") names_mask = XkbSymbolsNameMask | XkbGroupNamesMask status = XkbGetNames(self._display, names_mask, self._keyboard_description) if status != Success: self.close_display() raise X11Error(GET_NAMES_ERRORS[status] + ".")
def close_display(self): """Closes connection with X server and cleans up objects created on open_display(). """ if hasattr(self, "_keyboard_description") and self._keyboard_description: names_mask = XkbSymbolsNameMask | XkbGroupNamesMask XkbFreeNames(self._keyboard_description, names_mask, True) XkbFreeControls(self._...
def groups_data(self): """All data about all groups (get-only). :getter: Returns all data about all groups :type: list of GroupData """ return _ListProxy(GroupData(num, name, symbol, variant) for (num, name, symbol, variant) in zip(range(self.groups_count), self.groups_names, self.groups_symbols, self.groups_variants))
def groups_count(self): """Number of all groups (get-only). :getter: Returns number of all groups :type: int """ if self._keyboard_description.contents.ctrls is not None: return self._keyboard_description.contents.ctrls.contents.num_groups else: groups_source = self._groups_source groups_count = 0 while (groups_count <...
def groups_names(self): """Names of all groups (get-only). :getter: Returns names of all groups :type: list of str """ return _ListProxy(self._get_group_name_by_num(i) for i in range(self.groups_count))
def group_data(self): """All data about the current group (get-only). :getter: Returns all data about the current group :type: GroupData """ return GroupData(self.group_num, self.group_name, self.group_symbol, self.group_variant)
def group_num(self): """Current group number. :getter: Returns current group number :setter: Sets current group number :type: int """ xkb_state = XkbStateRec() XkbGetState(self._display, XkbUseCoreKbd, byref(xkb_state)) return xkb_state.group
def group_symbol(self): """Current group symbol. :getter: Returns current group symbol :setter: Sets current group symbol :type: str """ s_mapping = {symdata.index: symdata.symbol for symdata in self._symboldata_list} return s_mapping[self.group_num]
def group_variant(self): """Current group variant (get-only). :getter: Returns current group variant :type: str """ v_mapping = {symdata.index: symdata.variant for symdata in self._symboldata_list} return v_mapping[self.group_num] or ""
def format(self, format_str): """Returns a formatted version of format_str. The only named replacement fields supported by this method and their corresponding API calls are: * {num} group_num * {name} group_name * {symbol} group_symbol * {variant} group_variant * {current_data} group_data * {nums} groups_nums * {names}...
def _construct_register(reg, default_reg): """Constructs a register dict.""" if reg: x = dict((k, reg.get(k, d)) for k, d in default_reg.items()) else: x = dict(default_reg) return x
def pass_control_back(self, primary, secondary): """The address to which the controll is to be passed back. Tells a potential controller device the address to which the control is to be passed back. :param primary: An integer in the range 0 to 30 representing the primary address of the controller sending the command. :...
def free(host, port, timeout=float('Inf')): """ Wait for the specified port to become free (dropping or rejecting requests). Return when the port is free or raise a Timeout if timeout has elapsed. Timeout may be specified in seconds or as a timedelta. If timeout is None or ∞, the routine will run indefinitely. >>> free...
def find_available_local_port(): """ Find a free port on localhost. >>> 0 < find_available_local_port() < 65536 True """ infos = socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM) family, proto, _, _, addr = next(iter(infos)) sock = socket.socket(family, proto) sock.bind(addr) addr, port = sock.getsockna...
def assert_free(self, host, port=None): """ Assert that the given addr is free in that all attempts to connect fail within the timeout or raise a PortNotFree exception. >>> free_port = find_available_local_port() >>> Checker().assert_free('localhost', free_port) >>> Checker().assert_free('127.0.0.1', free_port) >>> Che...
def _createLocalRouter(siteStore): """ Create an L{IMessageRouter} provider for the default case, where no L{IMessageRouter} powerup is installed on the top-level store. It wraps a L{LocalMessageRouter} around the L{LoginSystem} installed on the given site store. If no L{LoginSystem} is present, this returns a null rou...
def redeliver(self): """ Re-deliver the answer to the consequence which previously handled it by raising an exception. This method is intended to be invoked after the code in question has been upgraded. Since there are no buggy answer receivers in production, nothing calls it yet. """ self.consequence.answerReceived(se...
def _routerForAccount(self, identifier): """ Locate an avatar by the username and domain portions of an L{Identifier}, so that we can deliver a message to the appropriate user. """ acct = self.loginSystem.accountByAddress(identifier.localpart, identifier.domain) return IMessageRouter(acct, None)
def routeMessage(self, sender, target, value, messageID): """ Implement L{IMessageRouter.routeMessage} by synchronously locating an account via L{axiom.userbase.LoginSystem.accountByAddress}, and delivering a message to it by calling a method on it. """ router = self._routerForAccount(target) if router is not None: rou...
def routeAnswer(self, originalSender, originalTarget, value, messageID): """ Implement L{IMessageRouter.routeMessage} by synchronously locating an account via L{axiom.userbase.LoginSystem.accountByAddress}, and delivering a response to it by calling a method on it and returning a deferred containing its answer. """ rou...
def _scheduleMePlease(self): """ This queue needs to have its run() method invoked at some point in the future. Tell the dependent scheduler to schedule it if it isn't already pending execution. """ sched = IScheduler(self.store) if len(list(sched.scheduledTimes(self))) == 0: sched.schedule(self, sched.now())
def routeMessage(self, sender, target, value, messageID): """ Implement L{IMessageRouter.routeMessage} by locating a shared item which provides L{IMessageReceiver}, identified by L{target} in this L{MessageQueue}'s L{Store}, as shared to the specified C{sender}, then invoke its L{messageReceived} method. Then, take the...
Value): raise TypeError("%r returned non-Value %r" % (receiver, output)) return output response = self.store.transact(txn) except RevertAndRespond, rar: response = rar.value except: log.err(Failure(), "An error occurred during inter-store " "message delivery.") response = Value(DELIVERY_ERROR, ERROR_REMOTE_EXCEPTION) a...
def _deliverAnswer(self, answer): """ Attempt to deliver an answer to a message sent to this store, via my store's parent's L{IMessageRouter} powerup. @param answer: an L{AlreadyAnswered} that contains an answer to a message sent to this store. """ router = self.siteRouter if answer.deliveryDeferred is None: d = answer...
def routeAnswer(self, originalSender, originalTarget, value, messageID): """ Route an incoming answer to a message originally sent by this queue. """ def txn(): qm = self._messageFromSender(originalSender, messageID) if qm is None: return c = qm.consequence if c is not None: c.answerReceived(value, qm.value, qm.sender,...
def _messageFromSender(self, sender, messageID): """ Locate a previously queued message by a given sender and messageID. """ return self.store.findUnique( _QueuedMessage, AND(_QueuedMessage.senderUsername == sender.localpart, _QueuedMessage.senderDomain == sender.domain, _QueuedMessage.messageID == messageID), default=...
def _verifySender(self, sender): """ Verify that this sender is valid. """ if self.store.findFirst( LoginMethod, AND(LoginMethod.localpart == sender.localpart, LoginMethod.domain == sender.domain, LoginMethod.internal == True)) is None: raise BadSender(sender.localpart + u'@' + sender.domain, [lm.localpart + u'@' + lm....
def queueMessage(self, sender, target, value, consequence=None): """ Queue a persistent outgoing message. @param sender: The a description of the shared item that is the sender of the message. @type sender: L{xmantissa.sharing.Identifier} @param target: The a description of the shared item that is the target of the mes...
def run(self): """ Attmept to deliver the first outgoing L{QueuedMessage}; return a time to reschedule if there are still more retries or outgoing messages to send. """ delay = None router = self.siteRouter for qmsg in self.store.query(_QueuedMessage, sort=_QueuedMessage.storeID.ascending): try: self._verifySender(qmsg...
def fromBox(self, name, strings, objects, proto): """ Retreive an attribute from the C{proto} parameter. """ objects[name] = getattr(proto, self.attr)
def messageRemote(self, cmdObj, consequence=None, **args): """ Send a message to the peer identified by the target, via the given L{Command} object and arguments. @param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized form will be the message. @param consequence: an L{IDeliveryConsequence} provider which w...
def expose(self, commandObject): """ Declare a method as being related to the given command object. @param commandObject: a L{Command} subclass. """ thunk = super(_AMPExposer, self).expose(commandObject.commandName) def thunkplus(function): result = thunk(function) result.command = commandObject return result return th...
def responderForName(self, instance, commandName): """ When resolving a command to a method from the wire, the information available is the command's name; look up a command. @param instance: an instance of a class who has methods exposed via this exposer's L{_AMPExposer.expose} method. @param commandName: the C{comman...
def expose(self, commandObject, exceptionType): """ Expose a function for processing a given AMP error. """ thunk = super(_AMPErrorExposer, self).expose( (commandObject.commandName, commandObject.errors.get(exceptionType))) def thunkplus(function): result = thunk(function) result.command = commandObject result.exceptio...
def errbackForName(self, instance, commandName, errorName): """ Retrieve an errback - a callable object that accepts a L{Failure} as an argument - that is exposed on the given instance, given an AMP commandName and a name in that command's error mapping. """ return super(_AMPErrorExposer, self).get(instance, (commandNa...
def _boxFromData(self, messageData): """ A box. @param messageData: a serialized AMP box representing either a message or an error. @type messageData: L{str} @raise MalformedMessage: if the C{messageData} parameter does not parse to exactly one AMP box. """ inputBoxes = parseString(messageData) if not len(inputBoxes) =...
def messageReceived(self, value, sender, target): """ An AMP-formatted message was received. Dispatch to the appropriate command responder, i.e. a method on this object exposed with L{commandMethod.expose}. @see IMessageReceiver.messageReceived """ if value.type != AMP_MESSAGE_TYPE: raise UnknownMessageType() inputBox ...
def answerReceived(self, value, originalValue, originalSender, originalTarget): """ An answer was received. Dispatch to the appropriate answer responder, i.e. a method on this object exposed with L{answerMethod.expose}. @see IDeliveryConsequence.answerReceived """ if value.type != AMP_ANSWER_TYPE: raise UnknownMessageT...
def _get(self, resource, payload=None): ''' Wrapper around requests.get that shorten caller url and takes care of errors ''' # Avoid dangerous default function argument `{}` payload = payload or {} # Build the request and return json response return requests.get( '{}/{}/{}'.format( self.master, pyconsul.__consul_api_ve...
def _put(self, resource, payload=None): ''' Wrapper around requests.put that shorten caller url and takes care of errors ''' # Avoid dangerous default function argument `{}` payload = payload or {} # Build the request and return json response return requests.put( '{}/{}/{}'.format( self.master, pyconsul.__consul_api_ve...
def table_names(self): """Returns names of all tables in the database""" query = "SELECT name FROM sqlite_master WHERE type='table'" cursor = self.connection.execute(query) results = cursor.fetchall() return [result_tuple[0] for result_tuple in results]
def drop_all_tables(self): """Drop all tables in the database""" for table_name in self.table_names(): self.execute_sql("DROP TABLE %s" % table_name) self.connection.commit()
def execute_sql(self, sql, commit=False): """Log and then execute a SQL query""" logger.info("Running sqlite query: \"%s\"", sql) self.connection.execute(sql) if commit: self.connection.commit()
def version(self): """What's the version of this database? Found in metadata attached by datacache when creating this database.""" query = "SELECT version FROM %s" % METADATA_TABLE_NAME cursor = self.connection.execute(query) version = cursor.fetchone() if not version: return 0 else: return int(version[0])
def _finalize_database(self, version): """ Create metadata table for database with version number. Parameters ---------- version : int Tag created database with user-specified version number """ require_integer(version, "version") create_metadata_sql = \ "CREATE TABLE %s (version INT)" % METADATA_TABLE_NAME self.execut...
def _create_table(self, table_name, column_types, primary=None, nullable=()): """Creates a sqlite3 table from the given metadata. Parameters ---------- column_types : list of (str, str) pairs First element of each tuple is the column name, second element is the sqlite3 type primary : str, optional Which column is the p...
def create(self, tables, version): """Do the actual work of creating the database, filling its tables with values, creating indices, and setting the datacache version metadata. Parameters ---------- tables : list List of datacache.DatabaseTable objects version : int """ for table in tables: self._create_table( table_na...
def _create_index(self, table_name, index_columns): """ Creates an index over multiple columns of a given table. Parameters ---------- table_name : str index_columns : iterable of str Which columns should be indexed """ logger.info( "Creating index on %s (%s)", table_name, ", ".join(index_columns)) index_name = "%s_ind...
def _create_indices(self, table_name, indices): """ Create multiple indices (each over multiple columns) on a given table. Parameters ---------- table_name : str indices : iterable of tuples Multiple groups of columns, each of which should be indexed. """ require_string(table_name, "table_name") require_iterable_of(ind...
def wrapModel(self, model): """ Converts application-provided model objects to L{IResource} providers. """ res = IResource(model, None) if res is None: frag = INavigableFragment(model) fragmentName = getattr(frag, 'fragmentName', None) if fragmentName is not None: fragDocFactory = self._getDocFactory(fragmentName) if f...
def locateChild(self, ctx, segments): """ Attempt to locate the child via the '.fragment' attribute, then fall back to normal locateChild behavior. """ if self.fragment is not None: # There are still a bunch of bogus subclasses of this class, which # are used in a variety of distasteful ways. 'fragment' *should* # alwa...
NotFound: return x return super(MantissaViewHelper, self).locateChild(ctx, segments)
def locateChild(self, context, segments): """ Return a statically defined child or a child defined by a site root plugin or an avatar from guard. """ request = IRequest(context) webViewer = IWebViewer(self.store, None) childAndSegments = self.siteProduceResource(request, segments, webViewer) if childAndSegments is not ...
def siteProduceResource(self, req, segments, webViewer): """ Retrieve a child resource and segments from rootChild_ methods on this object and SiteRootPlugins. @return: a 2-tuple of (resource, segments), suitable for return from locateChild. @param req: an L{IRequest} provider. @param segments: a tuple of L{str}s, the ...