desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'@brief Set the line number on which this token was matched Using setter/getter methods is deprecated. Use o.line instead.'
def setLine(self, line):
raise NotImplementedError
'@brief Get the column of the tokens first character, Columns are numbered 0..n-1 Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def getCharPositionInLine(self):
raise NotImplementedError
'@brief Set the column of the tokens first character, Using setter/getter methods is deprecated. Use o.charPositionInLine instead.'
def setCharPositionInLine(self, pos):
raise NotImplementedError
'@brief Get the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.'
def getChannel(self):
raise NotImplementedError
'@brief Set the channel of the token Using setter/getter methods is deprecated. Use o.channel instead.'
def setChannel(self, channel):
raise NotImplementedError
'@brief Get the index in the input stream. An index from 0..n-1 of the token object in the input stream. This must be valid in order to use the ANTLRWorks debugger. Using setter/getter methods is deprecated. Use o.index instead.'
def getTokenIndex(self):
raise NotImplementedError
'@brief Set the index in the input stream. Using setter/getter methods is deprecated. Use o.index instead.'
def setTokenIndex(self, index):
raise NotImplementedError
'@brief From what character stream was this token created. You don\'t have to implement but it\'s nice to know where a Token comes from if you have include files etc... on the input.'
def getInputStream(self):
raise NotImplementedError
'@brief From what character stream was this token created. You don\'t have to implement but it\'s nice to know where a Token comes from if you have include files etc... on the input.'
def setInputStream(self, input):
raise NotImplementedError
'Override the text for this token. getText() will return this text rather than pulling from the buffer. Note that this does not mean that start/stop indexes are not valid. It means that that input was converted to a new string in the token object.'
def setText(self, text):
self._text = text
'reset the parser\'s state; subclasses must rewinds the input stream'
def reset(self):
if (self._state is None): return self._state.following = [] self._state.errorRecovery = False self._state.lastErrorIndex = (-1) self._state.syntaxErrors = 0 self._state.backtracking = 0 if (self._state.ruleMemo is not None): self._state.ruleMemo = {}
'Match current input symbol against ttype. Attempt single token insertion or deletion error recovery. If that fails, throw MismatchedTokenException. To turn off single token insertion or deletion error recovery, override mismatchRecover() and have it call plain mismatch(), which does not recover. Then any error in a...
def match(self, input, ttype, follow):
matchedSymbol = self.getCurrentInputSymbol(input) if (self.input.LA(1) == ttype): self.input.consume() self._state.errorRecovery = False return matchedSymbol if (self._state.backtracking > 0): raise BacktrackingFailed matchedSymbol = self.recoverFromMismatchedToken(input,...
'Match the wildcard: in a symbol'
def matchAny(self, input):
self._state.errorRecovery = False self.input.consume()
'Factor out what to do upon token mismatch so tree parsers can behave differently. Override and call mismatchRecover(input, ttype, follow) to get single token insertion and deletion. Use this to turn of single token insertion and deletion. Override mismatchRecover to call this instead.'
def mismatch(self, input, ttype, follow):
if self.mismatchIsUnwantedToken(input, ttype): raise UnwantedTokenException(ttype, input) elif self.mismatchIsMissingToken(input, follow): raise MissingTokenException(ttype, input, None) raise MismatchedTokenException(ttype, input)
'Report a recognition problem. This method sets errorRecovery to indicate the parser is recovering not parsing. Once in recovery mode, no errors are generated. To get out of recovery mode, the parser must successfully match a token (after a resync). So it will go: 1. error occurs 2. enter recovery mode, report error ...
def reportError(self, e):
if self._state.errorRecovery: return self._state.syntaxErrors += 1 self._state.errorRecovery = True self.displayRecognitionError(self.tokenNames, e)
'What error message should be generated for the various exception types? Not very object-oriented code, but I like having all error message generation within one method rather than spread among all of the exception classes. This also makes it much easier for the exception handling because the exception classes do not h...
def getErrorMessage(self, e, tokenNames):
if isinstance(e, UnwantedTokenException): tokenName = '<unknown>' if (e.expecting == EOF): tokenName = 'EOF' else: tokenName = self.tokenNames[e.expecting] msg = ('extraneous input %s expecting %s' % (self.getTokenErrorDisplay(e.getUnexpectedToken(...
'Get number of recognition errors (lexer, parser, tree parser). Each recognizer tracks its own number. So parser and lexer each have separate count. Does not count the spurious errors found between an error and next valid token match See also reportError()'
def getNumberOfSyntaxErrors(self):
return self._state.syntaxErrors
'What is the error header, normally line/character position information?'
def getErrorHeader(self, e):
return ('line %d:%d' % (e.line, e.charPositionInLine))
'How should a token be displayed in an error message? The default is to display just the text, but during development you might want to have a lot of information spit out. Override in that case to use t.toString() (which, for CommonToken, dumps everything about the token). This is better than forcing you to override a...
def getTokenErrorDisplay(self, t):
s = t.text if (s is None): if (t.type == EOF): s = '<EOF>' else: s = (('<' + t.type) + '>') return repr(s)
'Override this method to change where error messages go'
def emitErrorMessage(self, msg):
sys.stderr.write((msg + '\n'))
'Recover from an error found on the input stream. This is for NoViableAlt and mismatched symbol exceptions. If you enable single token insertion and deletion, this will usually not handle mismatched symbol exceptions but there could be a mismatched token that the match() routine could not recover from.'
def recover(self, input, re):
if (self._state.lastErrorIndex == input.index()): input.consume() self._state.lastErrorIndex = input.index() followSet = self.computeErrorRecoverySet() self.beginResync() self.consumeUntil(input, followSet) self.endResync()
'A hook to listen in on the token consumption during error recovery. The DebugParser subclasses this to fire events to the listenter.'
def beginResync(self):
pass
'A hook to listen in on the token consumption during error recovery. The DebugParser subclasses this to fire events to the listenter.'
def endResync(self):
pass
'Compute the error recovery set for the current rule. During rule invocation, the parser pushes the set of tokens that can follow that rule reference on the stack; this amounts to computing FIRST of what follows the rule reference in the enclosing rule. This local follow set only includes tokens from within the rule; ...
def computeErrorRecoverySet(self):
return self.combineFollows(False)
'Compute the context-sensitive FOLLOW set for current rule. This is set of token types that can follow a specific rule reference given a specific call chain. You get the set of viable tokens that can possibly come next (lookahead depth 1) given the current call chain. Contrast this with the definition of plain FOLLOW...
def computeContextSensitiveRuleFOLLOW(self):
return self.combineFollows(True)
'Attempt to recover from a single missing or extra token. EXTRA TOKEN LA(1) is not what we are looking for. If LA(2) has the right token, however, then assume LA(1) is some extra spurious token. Delete it and LA(2) as if we were doing a normal match(), which advances the input. MISSING TOKEN If current token is consi...
def recoverFromMismatchedToken(self, input, ttype, follow):
e = None if self.mismatchIsUnwantedToken(input, ttype): e = UnwantedTokenException(ttype, input) self.beginResync() input.consume() self.endResync() self.reportError(e) matchedSymbol = self.getCurrentInputSymbol(input) input.consume() return matche...
'Not currently used'
def recoverFromMismatchedSet(self, input, e, follow):
if self.mismatchIsMissingToken(input, follow): self.reportError(e) return self.getMissingSymbol(input, e, INVALID_TOKEN_TYPE, follow) raise e
'Match needs to return the current input symbol, which gets put into the label for the associated token ref; e.g., x=ID. Token and tree parsers need to return different objects. Rather than test for input stream type or change the IntStream interface, I use a simple method to ask the recognizer to tell me what the cur...
def getCurrentInputSymbol(self, input):
return None
'Conjure up a missing token during error recovery. The recognizer attempts to recover from single missing symbols. But, actions might refer to that missing symbol. For example, x=ID {f($x);}. The action clearly assumes that there has been an identifier matched previously and that $x points at that token. If that token ...
def getMissingSymbol(self, input, e, expectedTokenType, follow):
return None
'Consume tokens until one matches the given token or token set tokenTypes can be a single token type or a set of token types'
def consumeUntil(self, input, tokenTypes):
if (not isinstance(tokenTypes, (set, frozenset))): tokenTypes = frozenset([tokenTypes]) ttype = input.LA(1) while ((ttype != EOF) and (ttype not in tokenTypes)): input.consume() ttype = input.LA(1)
'Return List<String> of the rules in your parser instance leading up to a call to this method. You could override if you want more details such as the file/line info of where in the parser java code a rule is invoked. This is very useful for error messages and for context-sensitive error recovery. You must be careful,...
def getRuleInvocationStack(self):
return self._getRuleInvocationStack(self.__module__)
'A more general version of getRuleInvocationStack where you can pass in, for example, a RecognitionException to get it\'s rule stack trace. This routine is shared with all recognizers, hence, static. TODO: move to a utility class or something; weird having lexer call this'
def _getRuleInvocationStack(cls, module):
rules = [] for frame in reversed(inspect.stack()): code = frame[0].f_code codeMod = inspect.getmodule(code) if (codeMod is None): continue if (codeMod.__name__ != module): continue if (code.co_name in ('nextToken', '<module>')): continu...
'For debugging and other purposes, might want the grammar name. Have ANTLR generate an implementation for this method.'
def getGrammarFileName(self):
return self.grammarFileName
'A convenience method for use most often with template rewrites. Convert a List<Token> to List<String>'
def toStrings(self, tokens):
if (tokens is None): return None return [token.text for token in tokens]
'Given a rule number and a start token index number, return MEMO_RULE_UNKNOWN if the rule has not parsed input starting from start index. If this rule has parsed input starting from the start index before, then return where the rule stopped parsing. It returns the index of the last token matched by the rule.'
def getRuleMemoization(self, ruleIndex, ruleStartIndex):
if (ruleIndex not in self._state.ruleMemo): self._state.ruleMemo[ruleIndex] = {} return self._state.ruleMemo[ruleIndex].get(ruleStartIndex, self.MEMO_RULE_UNKNOWN)
'Has this rule already parsed input at the current index in the input stream? Return the stop token index or MEMO_RULE_UNKNOWN. If we attempted but failed to parse properly before, return MEMO_RULE_FAILED. This method has a side-effect: if we have seen this input for this rule and successfully parsed before, then seek...
def alreadyParsedRule(self, input, ruleIndex):
stopIndex = self.getRuleMemoization(ruleIndex, input.index()) if (stopIndex == self.MEMO_RULE_UNKNOWN): return False if (stopIndex == self.MEMO_RULE_FAILED): raise BacktrackingFailed else: input.seek((stopIndex + 1)) return True
'Record whether or not this rule parsed the input at this position successfully.'
def memoize(self, input, ruleIndex, ruleStartIndex, success):
if success: stopTokenIndex = (input.index() - 1) else: stopTokenIndex = self.MEMO_RULE_FAILED if (ruleIndex in self._state.ruleMemo): self._state.ruleMemo[ruleIndex][ruleStartIndex] = stopTokenIndex
'Return a Token object from your input stream (usually a CharStream). Do not fail/return upon lexing error; keep chewing on the characters until you get a good one; errors are not passed through to the parser.'
def nextToken(self):
raise NotImplementedError
'The TokenSource is an interator. The iteration will not include the final EOF token, see also the note for the next() method.'
def __iter__(self):
return self
'Return next token or raise StopIteration. Note that this will raise StopIteration when hitting the EOF token, so EOF will not be part of the iteration.'
def next(self):
token = self.nextToken() if ((token is None) or (token.type == EOF)): raise StopIteration return token
'Return a token from this source; i.e., match a token on the char stream.'
def nextToken(self):
while 1: self._state.token = None self._state.channel = DEFAULT_CHANNEL self._state.tokenStartCharIndex = self.input.index() self._state.tokenStartCharPositionInLine = self.input.charPositionInLine self._state.tokenStartLine = self.input.line self._state.text = None ...
'Instruct the lexer to skip creating a token for current lexer rule and look for another token. nextToken() knows to keep looking when a lexer rule finishes with token set to SKIP_TOKEN. Recall that if token==null at end of any token rule, it creates one for you and emits it.'
def skip(self):
self._state.token = SKIP_TOKEN
'This is the lexer entry point that sets instance var \'token\''
def mTokens(self):
raise NotImplementedError
'Set the char stream and reset the lexer'
def setCharStream(self, input):
self.input = None self.reset() self.input = input
'The standard method called to automatically emit a token at the outermost lexical rule. The token object should point into the char buffer start..stop. If there is a text override in \'text\', use that to set the token\'s text. Override this method to emit custom Token objects. If you are building trees, then you s...
def emit(self, token=None):
if (token is None): token = CommonToken(input=self.input, type=self._state.type, channel=self._state.channel, start=self._state.tokenStartCharIndex, stop=(self.getCharIndex() - 1)) token.line = self._state.tokenStartLine token.text = self._state.text token.charPositionInLine = self._...
'What is the index of the current character of lookahead?'
def getCharIndex(self):
return self.input.index()
'Return the text matched so far for the current token or any text override.'
def getText(self):
if (self._state.text is not None): return self._state.text return self.input.substring(self._state.tokenStartCharIndex, (self.getCharIndex() - 1))
'Set the complete text of this token; it wipes any previous changes to the text.'
def setText(self, text):
self._state.text = text
'Lexers can normally match any char in it\'s vocabulary after matching a token, so do the easy thing and just kill a character and hope it all works out. You can instead use the rule invocation stack to do sophisticated error recovery if you are in a fragment rule.'
def recover(self, re):
self.input.consume()
'Set the token stream and reset the parser'
def setTokenStream(self, input):
self.input = None self.reset() self.input = input
'Return the start token or tree.'
def getStart(self):
return None
'Return the stop token or tree.'
def getStop(self):
return None
'Has a value potentially if output=AST.'
def getTree(self):
return None
'Has a value potentially if output=template.'
def getTemplate(self):
return None
'From the input stream, predict what alternative will succeed using this DFA (representing the covering regular approximation to the underlying CFL). Return an alternative number 1..n. Throw an exception upon error.'
def predict(self, input):
mark = input.mark() s = 0 try: for _ in xrange(50000): specialState = self.special[s] if (specialState >= 0): s = self.specialStateTransition(specialState, input) if (s == (-1)): self.noViableAlt(s, input) ...
'A hook for debugging interface'
def error(self, nvae):
pass
'@brief Unpack the runlength encoded table data. Terence implemented packed table initializers, because Java has a size restriction on .class files and the lookup tables can grow pretty large. The generated JavaLexer.java of the Java.g example would be about 15MB with uncompressed array initializers. Python does not ha...
def unpack(cls, string):
ret = [] for i in range((len(string) / 2)): (n, v) = (ord(string[(i * 2)]), ord(string[((i * 2) + 1)])) if (v == 65535): v = (-1) ret += ([v] * n) return ret
'Read the request body into fp_out (or make_file() if None). Return fp_out.'
def read_into_file(self, fp_out=None):
if (fp_out is None): fp_out = self.make_file() self.read(fp_out=fp_out) return fp_out
'Return a file-like object into which the request body will be read. By default, this will return a TemporaryFile. Override as needed. See also :attr:`cherrypy._cpreqbody.Part.maxrambytes`.'
def make_file(self):
return tempfile.TemporaryFile()
'Return this entity as a string, whether stored in a file or not.'
def fullvalue(self):
if self.file: self.file.seek(0) value = self.file.read() self.file.seek(0) else: value = self.value return value
'Execute the best-match processor for the given media type.'
def process(self):
proc = None ct = self.content_type.value try: proc = self.processors[ct] except KeyError: toptype = ct.split('/', 1)[0] try: proc = self.processors[toptype] except KeyError: pass if (proc is None): self.default_proc() else: ...
'Called if a more-specific processor is not found for the ``Content-Type``.'
def default_proc(self):
pass
'Read bytes from self.fp and return or write them to a file. If the \'fp_out\' argument is None (the default), all bytes read are returned in a single byte string. If the \'fp_out\' argument is not None, it must be a file-like object that supports the \'write\' method; all bytes read will be written to the fp, and that...
def read_lines_to_boundary(self, fp_out=None):
endmarker = (self.boundary + ntob('--')) delim = ntob('') prev_lf = True lines = [] seen = 0 while True: line = self.fp.readline((1 << 16)) if (not line): raise EOFError('Illegal end of multipart body.') if (line.startswith(ntob('--')) and prev_lf)...
'Called if a more-specific processor is not found for the ``Content-Type``.'
def default_proc(self):
if self.filename: self.file = self.read_into_file() else: result = self.read_lines_to_boundary() if isinstance(result, basestring): self.value = result else: self.file = result
'Read the request body into fp_out (or make_file() if None). Return fp_out.'
def read_into_file(self, fp_out=None):
if (fp_out is None): fp_out = self.make_file() self.read_lines_to_boundary(fp_out=fp_out) return fp_out
'Read bytes from the request body and return or write them to a file. A number of bytes less than or equal to the \'size\' argument are read off the socket. The actual number of bytes read are tracked in self.bytes_read. The number may be smaller than \'size\' when 1) the client sends fewer bytes, 2) the \'Content-Leng...
def read(self, size=None, fp_out=None):
if (self.length is None): if (size is None): remaining = inf else: remaining = size else: remaining = (self.length - self.bytes_read) if (size and (size < remaining)): remaining = size if (remaining == 0): self.finish() if (...
'Read a line from the request body and return it.'
def readline(self, size=None):
chunks = [] while ((size is None) or (size > 0)): chunksize = self.bufsize if ((size is not None) and (size < self.bufsize)): chunksize = size data = self.read(chunksize) if (not data): break pos = (data.find(ntob('\n')) + 1) if pos: ...
'Read lines from the request body and return them.'
def readlines(self, sizehint=None):
if (self.length is not None): if (sizehint is None): sizehint = (self.length - self.bytes_read) else: sizehint = min(sizehint, (self.length - self.bytes_read)) lines = [] seen = 0 while True: line = self.readline() if (not line): break ...
'Process the request entity based on its Content-Type.'
def process(self):
h = cherrypy.serving.request.headers if (('Content-Length' not in h) and ('Transfer-Encoding' not in h)): raise cherrypy.HTTPError(411) self.fp = SizedReader(self.fp, self.length, self.maxbytes, bufsize=self.bufsize, has_trailers=('Trailer' in h)) super(RequestBody, self).process() request_p...
'Close and reopen all file handlers.'
def reopen_files(self):
for log in (self.error_log, self.access_log): for h in log.handlers: if isinstance(h, logging.FileHandler): h.acquire() h.stream.close() h.stream = open(h.baseFilename, h.mode) h.release()
'Write the given ``msg`` to the error log. This is not just for errors! Applications may call this at any time to log application-specific information. If ``traceback`` is True, the traceback of the current exception (if any) will be appended to ``msg``.'
def error(self, msg='', context='', severity=logging.INFO, traceback=False):
if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
'An alias for ``error``.'
def __call__(self, *args, **kwargs):
return self.error(*args, **kwargs)
'Write to the access log (in Apache/NCSA Combined Log format). See http://httpd.apache.org/docs/2.0/logs.html#combined for format details. CherryPy calls this automatically for you. Note there are no arguments; it collects the data itself from :class:`cherrypy.request<cherrypy._cprequest.Request>`. Like Apache started ...
def access(self):
request = cherrypy.serving.request remote = request.remote response = cherrypy.serving.response outheaders = response.headers inheaders = request.headers if (response.output_status is None): status = '-' else: status = response.output_status.split(ntob(' '), 1)[0] ...
'Return now() in Apache Common Log Format (no timezone).'
def time(self):
now = datetime.datetime.now() monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] month = monthnames[(now.month - 1)].capitalize() return ('[%02d/%s/%04d:%02d:%02d:%02d]' % (now.day, month, now.year, now.hour, now.minute, now.second))
'Flushes the stream.'
def flush(self):
try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, KeyError): pass else: stream.flush()
'Emit a record.'
def emit(self, record):
try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, KeyError): pass else: try: msg = self.format(record) fs = '%s\n' import types if (not hasattr(types, 'UnicodeType')): stream....
'Run all check_* methods.'
def __call__(self):
if self.on: oldformatwarning = warnings.formatwarning warnings.formatwarning = self.formatwarning try: for name in dir(self): if name.startswith('check_'): method = getattr(self, name) if (method and hasattr(method, '__call_...
'Function to format a warning.'
def formatwarning(self, message, category, filename, lineno, line=None):
return ('CherryPy Checker:\n%s\n\n' % message)
'Check for Application config with sections that repeat script_name.'
def check_app_config_entries_dont_start_with_script_name(self):
for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue if (not app.config): continue if (sn == ''): continue sn_atoms = sn.strip('/').split('/') for key in app.config.keys(): key_at...
'Check for mounted Applications that have site-scoped config.'
def check_site_config_entries_in_app_config(self):
for (sn, app) in iteritems(cherrypy.tree.apps): if (not isinstance(app, cherrypy.Application)): continue msg = [] for (section, entries) in iteritems(app.config): if section.startswith('/'): for (key, value) in iteritems(entries): f...
'Check for mounted Applications that have no config.'
def check_skipped_app_config(self):
for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue if (not app.config): msg = ('The Application mounted at %r has an empty config.' % sn) if self.global_config_contained_paths: ...
'Check for Application config with extraneous brackets in section names.'
def check_app_config_brackets(self):
for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue if (not app.config): continue for key in app.config.keys(): if (key.startswith('[') or key.endswith(']')): warnings.warn(('The applicat...
'Check Application config for incorrect static paths.'
def check_static_paths(self):
request = cherrypy.request for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue request.app = app for section in app.config: request.get_resource((section + '/dummy.html')) conf = request.config.get ...
'Process config and warn on each obsolete or deprecated entry.'
def _compat(self, config):
for (section, conf) in config.items(): if isinstance(conf, dict): for (k, v) in conf.items(): if (k in self.obsolete): warnings.warn(('%r is obsolete. Use %r instead.\nsection: [%s]' % (k, self.obsolete[k], section))) elif (k ...
'Process config and warn on each obsolete or deprecated entry.'
def check_compatibility(self):
self._compat(cherrypy.config) for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._compat(app.config)
'Process config and warn on each unknown config namespace.'
def check_config_namespaces(self):
for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._known_ns(app)
'Assert that config values are of the same type as default values.'
def check_config_types(self):
self._known_types(cherrypy.config) for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._known_types(app.config)
'Warn if any socket_host is \'localhost\'. See #711.'
def check_localhost(self):
for (k, v) in cherrypy.config.items(): if ((k == 'server.socket_host') and (v == 'localhost')): warnings.warn("The use of 'localhost' as a socket host can cause problems on newer systems, since 'localhost' can map to either an IPv4 ...
'Copy func parameter names to obj attributes.'
def _setargs(self):
try: for arg in _getargs(self.callable): setattr(self, arg, None) except (TypeError, AttributeError): if hasattr(self.callable, '__call__'): for arg in _getargs(self.callable.__call__): setattr(self, arg, None) except NotImplementedError: pass ...
'Return a dict of configuration entries for this Tool.'
def _merged_args(self, d=None):
if d: conf = d.copy() else: conf = {} tm = cherrypy.serving.request.toolmaps[self.namespace] if (self._name in tm): conf.update(tm[self._name]) if ('on' in conf): del conf['on'] return conf
'Compile-time decorator (turn on the tool in config). For example:: @tools.proxy() def whats_my_base(self): return cherrypy.request.base whats_my_base.exposed = True'
def __call__(self, *args, **kwargs):
if args: raise TypeError(('The %r Tool does not accept positional arguments; you must use keyword arguments.' % self._name)) def tool_decorator(f): if (not hasattr(f, '_cp_config')): f._cp_config = {} subspace = (((self.namespace + '.') + s...
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self.callable, priority=p, **conf)
'Use this tool as a CherryPy page handler. For example:: class Root: nav = tools.staticdir.handler(section="/nav", dir="nav", root=absDir)'
def handler(self, *args, **kwargs):
def handle_func(*a, **kw): handled = self.callable(*args, **self._merged_args(kwargs)) if (not handled): raise cherrypy.NotFound() return cherrypy.serving.response.body handle_func.exposed = True return handle_func
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self._wrapper, priority=p, **conf)
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
cherrypy.serving.request.error_response = self._wrapper
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
hooks = cherrypy.serving.request.hooks conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) hooks.attach(self._point, self.callable, priority=p, **conf) locking = conf.pop('locking', 'implicit') if (locking =...
'Drop the current session and make a new one (with a new id).'
def regenerate(self):
sess = cherrypy.serving.session sess.regenerate() conf = dict([(k, v) for (k, v) in self._merged_args().items() if (k in ('path', 'path_header', 'name', 'timeout', 'domain', 'secure'))]) _sessions.set_response_cookie(**conf)
'Hook caching into cherrypy.request.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, priority=p, **conf)
'Populate request.toolmaps from tools specified in config.'
def __enter__(self):
cherrypy.serving.request.toolmaps[self.namespace] = map = {} def populate(k, v): (toolname, arg) = k.split('.', 1) bucket = map.setdefault(toolname, {}) bucket[arg] = v return populate
'Run tool._setup() for each tool in our toolmap.'
def __exit__(self, exc_type, exc_val, exc_tb):
map = cherrypy.serving.request.toolmaps.get(self.namespace) if map: for (name, settings) in map.items(): if settings.get('on', False): tool = getattr(self, name) tool._setup()