index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
6,104
scrapy.item
__setitem__
null
def __setitem__(self, key, value): if key in self.fields: self._values[key] = value else: raise KeyError(f"{self.__class__.__name__} does not support field: {key}")
(self, key, value)
6,105
collections.abc
clear
D.clear() -> None. Remove all items from D.
null
(self)
6,106
scrapy.item
copy
null
def copy(self): return self.__class__(self)
(self)
6,107
scrapy.item
deepcopy
Return a :func:`~copy.deepcopy` of this item.
def deepcopy(self): """Return a :func:`~copy.deepcopy` of this item.""" return deepcopy(self)
(self)
6,110
scrapy.item
keys
null
def keys(self): return self._values.keys()
(self)
6,111
collections.abc
pop
D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
null
(self, key, default=<object object at 0x7fe9be7fc180>)
6,112
collections.abc
popitem
D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty.
null
(self)
6,113
collections.abc
setdefault
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
null
(self, key, default=None)
6,114
collections.abc
update
D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] =...
null
(self, other=(), /, **kwds)
6,116
scrapy.http.request
Request
Represents an HTTP request, which is usually generated in a Spider and executed by the Downloader, thus generating a :class:`Response`.
class Request(object_ref): """Represents an HTTP request, which is usually generated in a Spider and executed by the Downloader, thus generating a :class:`Response`. """ attributes: Tuple[str, ...] = ( "url", "callback", "method", "headers", "body", "cook...
(url: str, callback: Optional[Callable] = None, method: str = 'GET', headers: Optional[dict] = None, body: Union[bytes, str, NoneType] = None, cookies: Union[dict, List[dict], NoneType] = None, meta: Optional[dict] = None, encoding: str = 'utf-8', priority: int = 0, dont_filter: bool = False, errback: Optional[Callable...
6,117
scrapy.http.request
__init__
null
def __init__( self, url: str, callback: Optional[Callable] = None, method: str = "GET", headers: Optional[dict] = None, body: Optional[Union[bytes, str]] = None, cookies: Optional[Union[dict, List[dict]]] = None, meta: Optional[dict] = None, encoding: str = "utf-8", priority: int...
(self, url: str, callback: Optional[Callable] = None, method: str = 'GET', headers: Optional[dict] = None, body: Union[bytes, str, NoneType] = None, cookies: Union[dict, List[dict], NoneType] = None, meta: Optional[dict] = None, encoding: str = 'utf-8', priority: int = 0, dont_filter: bool = False, errback: Optional[Ca...
6,127
scrapy.selector.unified
Selector
An instance of :class:`Selector` is a wrapper over response to select certain parts of its content. ``response`` is an :class:`~scrapy.http.HtmlResponse` or an :class:`~scrapy.http.XmlResponse` object that will be used for selecting and extracting data. ``text`` is a unicode string or utf-8 e...
class Selector(_ParselSelector, object_ref): """ An instance of :class:`Selector` is a wrapper over response to select certain parts of its content. ``response`` is an :class:`~scrapy.http.HtmlResponse` or an :class:`~scrapy.http.XmlResponse` object that will be used for selecting and extractin...
(response: Optional[scrapy.http.response.text.TextResponse] = None, text: Optional[str] = None, type: Optional[str] = None, root: Optional[Any] = <object object at 0x7fe925b26a50>, **kwargs: Any)
6,128
parsel.selector
__bool__
Return ``True`` if there is any real content selected or ``False`` otherwise. In other words, the boolean value of a :class:`Selector` is given by the contents it selects.
def __bool__(self) -> bool: """ Return ``True`` if there is any real content selected or ``False`` otherwise. In other words, the boolean value of a :class:`Selector` is given by the contents it selects. """ return bool(self.get())
(self) -> bool
6,129
parsel.selector
__getstate__
null
def __getstate__(self) -> Any: raise TypeError("can't pickle Selector objects")
(self) -> Any
6,130
scrapy.selector.unified
__init__
null
def __init__( self, response: Optional[TextResponse] = None, text: Optional[str] = None, type: Optional[str] = None, root: Optional[Any] = _NOT_SET, **kwargs: Any, ): if response is not None and text is not None: raise ValueError( f"{self.__class__.__name__}.__init__() re...
(self, response: Optional[scrapy.http.response.text.TextResponse] = None, text: Optional[str] = None, type: Optional[str] = None, root: Optional[Any] = <object object at 0x7fe925b26a50>, **kwargs: Any)
6,133
parsel.selector
__repr__
null
def __repr__(self) -> str: data = repr(shorten(str(self.get()), width=40)) return f"<{type(self).__name__} query={self._expr!r} data={data}>"
(self) -> str
6,134
parsel.selector
__str__
null
def __str__(self) -> str: return str(self.get())
(self) -> str
6,135
parsel.selector
_css2xpath
null
def _css2xpath(self, query: str) -> str: type = _xml_or_html(self.type) return _ctgroup[type]["_csstranslator"].css_to_xpath(query)
(self, query: str) -> str
6,136
parsel.selector
_get_root
null
def _get_root( self, text: str = "", base_url: Optional[str] = None, huge_tree: bool = LXML_SUPPORTS_HUGE_TREE, type: Optional[str] = None, body: bytes = b"", encoding: str = "utf8", ) -> etree._Element: return create_root_node( text, body=body, encoding=encoding,...
(self, text: str = '', base_url: Optional[str] = None, huge_tree: bool = True, type: Optional[str] = None, body: bytes = b'', encoding: str = 'utf8') -> lxml.etree._Element
6,137
parsel.selector
css
Apply the given CSS selector and return a :class:`SelectorList` instance. ``query`` is a string containing the CSS selector to apply. In the background, CSS queries are translated into XPath queries using `cssselect`_ library and run ``.xpath()`` method. .. _cssselect: https:...
def css(self: _SelectorType, query: str) -> SelectorList[_SelectorType]: """ Apply the given CSS selector and return a :class:`SelectorList` instance. ``query`` is a string containing the CSS selector to apply. In the background, CSS queries are translated into XPath queries using `cssselect`_ libra...
(self: ~_SelectorType, query: str) -> parsel.selector.SelectorList[~_SelectorType]
6,138
parsel.selector
drop
Drop matched nodes from the parent element.
def drop(self) -> None: """ Drop matched nodes from the parent element. """ try: parent = self.root.getparent() except AttributeError: # 'str' object has no attribute 'getparent' raise CannotRemoveElementWithoutRoot( "The node you're trying to drop has no root, " ...
(self) -> NoneType
6,139
parsel.selector
get
Serialize and return the matched nodes. For HTML and XML, the result is always a string, and percent-encoded content is unquoted.
def get(self) -> Any: """ Serialize and return the matched nodes. For HTML and XML, the result is always a string, and percent-encoded content is unquoted. """ if self.type in ("text", "json"): return self.root try: return typing.cast( str, etree.tostr...
(self) -> Any
6,141
parsel.selector
getall
Serialize and return the matched node in a 1-element list of strings.
def getall(self) -> List[str]: """ Serialize and return the matched node in a 1-element list of strings. """ return [self.get()]
(self) -> List[str]
6,142
parsel.selector
jmespath
Find objects matching the JMESPath ``query`` and return the result as a :class:`SelectorList` instance with all elements flattened. List elements implement :class:`Selector` interface too. ``query`` is a string containing the `JMESPath <https://jmespath.org/>`_ query to apply. ...
def jmespath( self: _SelectorType, query: str, **kwargs: Any, ) -> SelectorList[_SelectorType]: """ Find objects matching the JMESPath ``query`` and return the result as a :class:`SelectorList` instance with all elements flattened. List elements implement :class:`Selector` interface too. ...
(self: ~_SelectorType, query: str, **kwargs: Any) -> parsel.selector.SelectorList[~_SelectorType]
6,143
parsel.selector
re
Apply the given regex and return a list of strings with the matches. ``regex`` can be either a compiled regular expression or a string which will be compiled to a regular expression using ``re.compile(regex)``. By default, character entity references are replaced by their ...
def re( self, regex: Union[str, Pattern[str]], replace_entities: bool = True ) -> List[str]: """ Apply the given regex and return a list of strings with the matches. ``regex`` can be either a compiled regular expression or a string which will be compiled to a regular expression using ``re.compil...
(self, regex: Union[str, Pattern[str]], replace_entities: bool = True) -> List[str]
6,144
parsel.selector
re_first
Apply the given regex and return the first string which matches. If there is no match, return the default value (``None`` if the argument is not provided). By default, character entity references are replaced by their corresponding character (except for ``&amp;`` and ``&lt;``)....
def re_first( self, regex: Union[str, Pattern[str]], default: Optional[str] = None, replace_entities: bool = True, ) -> Optional[str]: """ Apply the given regex and return the first string which matches. If there is no match, return the default value (``None`` if the argument is not prov...
(self, regex: Union[str, Pattern[str]], default: Optional[str] = None, replace_entities: bool = True) -> Optional[str]
6,145
parsel.selector
register_namespace
Register the given namespace to be used in this :class:`Selector`. Without registering namespaces you can't select or extract data from non-standard namespaces. See :ref:`selector-examples-xml`.
def register_namespace(self, prefix: str, uri: str) -> None: """ Register the given namespace to be used in this :class:`Selector`. Without registering namespaces you can't select or extract data from non-standard namespaces. See :ref:`selector-examples-xml`. """ self.namespaces[prefix] = uri
(self, prefix: str, uri: str) -> NoneType
6,146
parsel.selector
remove
Remove matched nodes from the parent element.
def remove(self) -> None: """ Remove matched nodes from the parent element. """ warn( "Method parsel.selector.Selector.remove is deprecated, please use parsel.selector.Selector.drop method instead", category=DeprecationWarning, stacklevel=2, ) try: parent = self.r...
(self) -> NoneType
6,147
parsel.selector
remove_namespaces
Remove all namespaces, allowing to traverse the document using namespace-less xpaths. See :ref:`removing-namespaces`.
def remove_namespaces(self) -> None: """ Remove all namespaces, allowing to traverse the document using namespace-less xpaths. See :ref:`removing-namespaces`. """ for el in self.root.iter("*"): if el.tag.startswith("{"): el.tag = el.tag.split("}", 1)[1] # loop on element ...
(self) -> NoneType
6,148
parsel.selector
xpath
Find nodes matching the xpath ``query`` and return the result as a :class:`SelectorList` instance with all elements flattened. List elements implement :class:`Selector` interface too. ``query`` is a string containing the XPATH query to apply. ``namespaces`` is an optional ``pr...
def xpath( self: _SelectorType, query: str, namespaces: Optional[Mapping[str, str]] = None, **kwargs: Any, ) -> SelectorList[_SelectorType]: """ Find nodes matching the xpath ``query`` and return the result as a :class:`SelectorList` instance with all elements flattened. List elements im...
(self: ~_SelectorType, query: str, namespaces: Optional[Mapping[str, str]] = None, **kwargs: Any) -> parsel.selector.SelectorList[~_SelectorType]
6,149
scrapy.spiders
Spider
Base class for scrapy spiders. All spiders must inherit from this class.
class Spider(object_ref): """Base class for scrapy spiders. All spiders must inherit from this class. """ name: str custom_settings: Optional[dict] = None def __init__(self, name: Optional[str] = None, **kwargs: Any): if name is not None: self.name = name elif not g...
(name: str = None, **kwargs: 'Any')
6,150
scrapy.spiders
__init__
null
def __init__(self, name: Optional[str] = None, **kwargs: Any): if name is not None: self.name = name elif not getattr(self, "name", None): raise ValueError(f"{type(self).__name__} must have a name") self.__dict__.update(kwargs) if not hasattr(self, "start_urls"): self.start_urls:...
(self, name: Optional[str] = None, **kwargs: Any)
6,152
scrapy.spiders
__repr__
null
def __repr__(self) -> str: return f"<{type(self).__name__} {self.name!r} at 0x{id(self):0x}>"
(self) -> str
6,153
scrapy.spiders
_parse
null
def _parse(self, response: Response, **kwargs: Any) -> Any: return self.parse(response, **kwargs)
(self, response: scrapy.http.response.Response, **kwargs: Any) -> Any
6,154
scrapy.spiders
_set_crawler
null
def _set_crawler(self, crawler: Crawler) -> None: self.crawler = crawler self.settings = crawler.settings crawler.signals.connect(self.close, signals.spider_closed)
(self, crawler: 'Crawler') -> 'None'
6,155
scrapy.spiders
close
null
@staticmethod def close(spider: Spider, reason: str) -> Union[Deferred, None]: closed = getattr(spider, "closed", None) if callable(closed): return cast(Union[Deferred, None], closed(reason)) return None
(spider: scrapy.spiders.Spider, reason: str) -> Optional[twisted.internet.defer.Deferred]
6,156
scrapy.spiders
log
Log the given message at the given log level This helper wraps a log call to the logger within the spider, but you can use it directly (e.g. Spider.logger.info('msg')) or use any other Python logger too.
def log(self, message: Any, level: int = logging.DEBUG, **kw: Any) -> None: """Log the given message at the given log level This helper wraps a log call to the logger within the spider, but you can use it directly (e.g. Spider.logger.info('msg')) or use any other Python logger too. """ self.logg...
(self, message: Any, level: int = 10, **kw: Any) -> NoneType
6,157
scrapy.spiders
parse
null
def parse(self, response: Response, **kwargs: Any) -> Any: raise NotImplementedError( f"{self.__class__.__name__}.parse callback is not defined" )
(self, response: scrapy.http.response.Response, **kwargs: Any) -> Any
6,158
scrapy.spiders
start_requests
null
def start_requests(self) -> Iterable[Request]: if not self.start_urls and hasattr(self, "start_url"): raise AttributeError( "Crawling could not start: 'start_urls' not found " "or empty (but found 'start_url' attribute instead, " "did you miss an 's'?)" ) for ...
(self) -> Iterable[scrapy.http.request.Request]
6,168
bottle
AppEngineServer
Adapter for Google App Engine.
class AppEngineServer(ServerAdapter): """ Adapter for Google App Engine. """ quiet = True def run(self, handler): from google.appengine.ext.webapp import util # A main() function in the handler script enables 'App Caching'. # Lets makes sure it is there. This _really_ improves perfor...
(host='127.0.0.1', port=8080, **options)
6,169
bottle
__init__
null
def __init__(self, host='127.0.0.1', port=8080, **options): self.options = options self.host = host self.port = int(port)
(self, host='127.0.0.1', port=8080, **options)
6,170
bottle
__repr__
null
def __repr__(self): args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()]) return "%s(%s)" % (self.__class__.__name__, args)
(self)
6,171
bottle
run
null
def run(self, handler): from google.appengine.ext.webapp import util # A main() function in the handler script enables 'App Caching'. # Lets makes sure it is there. This _really_ improves performance. module = sys.modules.get('__main__') if module and not hasattr(module, 'main'): module.main...
(self, handler)
6,172
bottle
AppStack
A stack-like list. Calling it returns the head of the stack.
class AppStack(list): """ A stack-like list. Calling it returns the head of the stack. """ def __call__(self): """ Return the current default application. """ return self[-1] def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstan...
(iterable=(), /)
6,173
bottle
__call__
Return the current default application.
def __call__(self): """ Return the current default application. """ return self[-1]
(self)
6,174
bottle
push
Add a new :class:`Bottle` instance to the stack
def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstance(value, Bottle): value = Bottle() self.append(value) return value
(self, value=None)
6,175
bottle
AutoServer
Untested.
class AutoServer(ServerAdapter): """ Untested. """ adapters = [WaitressServer, PasteServer, TwistedServer, CherryPyServer, CherootServer, WSGIRefServer] def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options)....
(host='127.0.0.1', port=8080, **options)
6,178
bottle
run
null
def run(self, handler): for sa in self.adapters: try: return sa(self.host, self.port, **self.options).run(handler) except ImportError: pass
(self, handler)
6,179
bottle
BaseRequest
A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only. Adding new attributes to a request actually adds them to the environ dictionary (as 'bottle.request.ext.<name>'). This is the recommended way to store an...
class BaseRequest(object): """ A wrapper for WSGI environment dictionaries that adds a lot of convenient access methods and properties. Most of them are read-only. Adding new attributes to a request actually adds them to the environ dictionary (as 'bottle.request.ext.<name>'). This is the r...
(environ=None)
6,180
bottle
__delitem__
null
def __delitem__(self, key): self[key] = ""; del(self.environ[key])
(self, key)
6,181
bottle
__getattr__
Search in self.environ for additional user defined attributes.
def __getattr__(self, name): ''' Search in self.environ for additional user defined attributes. ''' try: var = self.environ['bottle.request.ext.%s'%name] return var.__get__(self) if hasattr(var, '__get__') else var except KeyError: raise AttributeError('Attribute %r not defined.' % n...
(self, name)
6,182
bottle
__getitem__
null
def __getitem__(self, key): return self.environ[key]
(self, key)
6,183
bottle
__init__
Wrap a WSGI environ dictionary.
def __init__(self, environ=None): """ Wrap a WSGI environ dictionary. """ #: The wrapped WSGI environ dictionary. This is the only real attribute. #: All other attributes actually are read-only properties. self.environ = {} if environ is None else environ self.environ['bottle.request'] = self
(self, environ=None)
6,184
bottle
__iter__
null
def __iter__(self): return iter(self.environ)
(self)
6,185
bottle
__len__
null
def __len__(self): return len(self.environ)
(self)
6,186
bottle
__repr__
null
def __repr__(self): return '<%s: %s %s>' % (self.__class__.__name__, self.method, self.url)
(self)
6,187
bottle
__setattr__
null
def __setattr__(self, name, value): if name == 'environ': return object.__setattr__(self, name, value) self.environ['bottle.request.ext.%s'%name] = value
(self, name, value)
6,188
bottle
__setitem__
Change an environ value and clear all caches that depend on it.
def __setitem__(self, key, value): """ Change an environ value and clear all caches that depend on it. """ if self.environ.get('bottle.request.readonly'): raise KeyError('The environ dictionary is read-only.') self.environ[key] = value todelete = () if key == 'wsgi.input': todelete =...
(self, key, value)
6,189
bottle
_get_body_string
read body until content-length or MEMFILE_MAX into a string. Raise HTTPError(413) on requests that are to large.
def _get_body_string(self): ''' read body until content-length or MEMFILE_MAX into a string. Raise HTTPError(413) on requests that are to large. ''' clen = self.content_length if clen > self.MEMFILE_MAX: raise HTTPError(413, 'Request to large') if clen < 0: clen = self.MEMFILE_MAX + 1 ...
(self)
6,190
bottle
_iter_body
null
def _iter_body(self, read, bufsize): maxread = max(0, self.content_length) while maxread: part = read(min(maxread, bufsize)) if not part: break yield part maxread -= len(part)
(self, read, bufsize)
6,191
bottle
_iter_chunked
null
def _iter_chunked(self, read, bufsize): err = HTTPError(400, 'Error while parsing chunked transfer body.') rn, sem, bs = tob('\r\n'), tob(';'), tob('') while True: header = read(1) while header[-2:] != rn: c = read(1) header += c if not c: raise err ...
(self, read, bufsize)
6,192
bottle
copy
Return a new :class:`Request` with a shallow :attr:`environ` copy.
def copy(self): """ Return a new :class:`Request` with a shallow :attr:`environ` copy. """ return Request(self.environ.copy())
(self)
6,193
bottle
get
null
def get(self, value, default=None): return self.environ.get(value, default)
(self, value, default=None)
6,194
bottle
get_cookie
Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default value.
def get_cookie(self, key, default=None, secret=None): """ Return the content of a cookie. To read a `Signed Cookie`, the `secret` must match the one used to create the cookie (see :meth:`BaseResponse.set_cookie`). If anything goes wrong (missing cookie or wrong signature), return a default v...
(self, key, default=None, secret=None)
6,195
bottle
get_header
Return the value of a request header, or a given default value.
def get_header(self, name, default=None): ''' Return the value of a request header, or a given default value. ''' return self.headers.get(name, default)
(self, name, default=None)
6,196
bottle
keys
null
def keys(self): return self.environ.keys()
(self)
6,197
bottle
path_shift
Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1)
def path_shift(self, shift=1): ''' Shift path segments from :attr:`path` to :attr:`script_name` and vice versa. :param shift: The number of path segments to shift. May be negative to change the shift direction. (default: 1) ''' script = self.environ.get('SCRIPT_NAME','/')...
(self, shift=1)
6,198
bottle
BaseResponse
Storage class for a response body as well as headers and cookies. This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers. :param body: The response body as one o...
class BaseResponse(object): """ Storage class for a response body as well as headers and cookies. This class does support dict-like case-insensitive item-access to headers, but is NOT a dict. Most notably, iterating over a response yields parts of the body and not the headers. :par...
(body='', status=None, headers=None, **more_headers)
6,199
bottle
__contains__
null
def __contains__(self, name): return _hkey(name) in self._headers
(self, name)
6,200
bottle
__delitem__
null
def __delitem__(self, name): del self._headers[_hkey(name)]
(self, name)
6,201
bottle
__getitem__
null
def __getitem__(self, name): return self._headers[_hkey(name)][-1]
(self, name)
6,202
bottle
__init__
null
def __init__(self, body='', status=None, headers=None, **more_headers): self._cookies = None self._headers = {} self.body = body self.status = status or self.default_status if headers: if isinstance(headers, dict): headers = headers.items() for name, value in headers: ...
(self, body='', status=None, headers=None, **more_headers)
6,203
bottle
__iter__
null
def __iter__(self): return iter(self.body)
(self)
6,204
bottle
__repr__
null
def __repr__(self): out = '' for name, value in self.headerlist: out += '%s: %s\n' % (name.title(), value.strip()) return out
(self)
6,205
bottle
__setitem__
null
def __setitem__(self, name, value): self._headers[_hkey(name)] = [_hval(value)]
(self, name, value)
6,206
bottle
add_header
Add an additional response header, not removing duplicates.
def add_header(self, name, value): ''' Add an additional response header, not removing duplicates. ''' self._headers.setdefault(_hkey(name), []).append(_hval(value))
(self, name, value)
6,207
bottle
close
null
def close(self): if hasattr(self.body, 'close'): self.body.close()
(self)
6,208
bottle
copy
Returns a copy of self.
def copy(self, cls=None): ''' Returns a copy of self. ''' cls = cls or BaseResponse assert issubclass(cls, BaseResponse) copy = cls() copy.status = self.status copy._headers = dict((k, v[:]) for (k, v) in self._headers.items()) if self._cookies: copy._cookies = SimpleCookie() ...
(self, cls=None)
6,209
bottle
delete_cookie
Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie.
def delete_cookie(self, key, **kwargs): ''' Delete a cookie. Be sure to use the same `domain` and `path` settings as used to create the cookie. ''' kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs)
(self, key, **kwargs)
6,210
bottle
get_header
Return the value of a previously defined header. If there is no header with that name, return a default value.
def get_header(self, name, default=None): ''' Return the value of a previously defined header. If there is no header with that name, return a default value. ''' return self._headers.get(_hkey(name), [default])[-1]
(self, name, default=None)
6,211
bottle
iter_headers
Yield (header, value) tuples, skipping headers that are not allowed with the current response status code.
def iter_headers(self): ''' Yield (header, value) tuples, skipping headers that are not allowed with the current response status code. ''' return self.headerlist
(self)
6,212
bottle
set_cookie
Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signature key required for signed cookies. ...
def set_cookie(self, name, value, secret=None, **options): ''' Create a new cookie or replace an old one. If the `secret` parameter is set, create a `Signed Cookie` (described below). :param name: the name of the cookie. :param value: the value of the cookie. :param secret: a signatu...
(self, name, value, secret=None, **options)
6,213
bottle
set_header
Create a new response header, replacing any previously defined headers with the same name.
def set_header(self, name, value): ''' Create a new response header, replacing any previously defined headers with the same name. ''' self._headers[_hkey(name)] = [_hval(value)]
(self, name, value)
6,214
bottle
BaseTemplate
Base class and minimal API for template adapters
class BaseTemplate(object): """ Base class and minimal API for template adapters """ extensions = ['tpl','html','thtml','stpl'] settings = {} #used in prepare() defaults = {} #used in render() def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a n...
(source=None, name=None, lookup=[], encoding='utf8', **settings)
6,215
bottle
__init__
Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings. The lookup, encoding and settings parameters are stored as instance ...
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): """ Create a new template. If the source parameter (str or buffer) is missing, the name argument is used to guess a template filename. Subclasses can assume that self.source and/or self.filename are set. Both are strings...
(self, source=None, name=None, lookup=[], encoding='utf8', **settings)
6,216
bottle
prepare
Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings.
def prepare(self, **options): """ Run preparations (parsing, caching, ...). It should be possible to call this again to refresh a template or to update settings. """ raise NotImplementedError
(self, **options)
6,217
bottle
render
Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (args) or directly, as keywords (kwargs). ...
def render(self, *args, **kwargs): """ Render the template with the specified local variables and return a single byte or unicode string. If it is a byte string, the encoding must match self.encoding. This method must be thread-safe! Local variables may be provided in dictionaries (args) or directly...
(self, *args, **kwargs)
6,218
bottle
BjoernServer
Fast server written in C: https://github.com/jonashaag/bjoern
class BjoernServer(ServerAdapter): """ Fast server written in C: https://github.com/jonashaag/bjoern """ def run(self, handler): from bjoern import run run(handler, self.host, self.port)
(host='127.0.0.1', port=8080, **options)
6,221
bottle
run
null
def run(self, handler): from bjoern import run run(handler, self.host, self.port)
(self, handler)
6,222
bottle
Bottle
Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications. :param catchall: If true (default), handle all exceptions. Turn off to let debugging midd...
class Bottle(object): """ Each Bottle object represents a single, distinct web application and consists of routes, callbacks, plugins, resources and configuration. Instances are callable WSGI applications. :param catchall: If true (default), handle all exceptions. Turn off to ...
(catchall=True, autojson=True)
6,223
bottle
__call__
Each instance of :class:'Bottle' is a WSGI application.
def __call__(self, environ, start_response): ''' Each instance of :class:'Bottle' is a WSGI application. ''' return self.wsgi(environ, start_response)
(self, environ, start_response)
6,224
bottle
__init__
null
def __init__(self, catchall=True, autojson=True): #: A :class:`ConfigDict` for app specific configuration. self.config = ConfigDict() self.config._on_change = functools.partial(self.trigger_hook, 'config') self.config.meta_set('autojson', 'validate', bool) self.config.meta_set('catchall', 'validate'...
(self, catchall=True, autojson=True)
6,225
bottle
_cast
Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes
def _cast(self, out, peek=None): """ Try to convert the parameter into something WSGI compatible and set correct HTTP headers when possible. Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, iterable of strings and iterable of unicodes """ # Empty output is done here if...
(self, out, peek=None)
6,226
bottle
_handle
null
def _handle(self, environ): try: environ['bottle.app'] = self request.bind(environ) response.bind() path = environ['bottle.raw_path'] = environ['PATH_INFO'] if py3k: try: environ['PATH_INFO'] = path.encode('latin1').decode('utf8') excep...
(self, environ)
6,227
bottle
add_hook
Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each request regardless of ...
def add_hook(self, name, func): ''' Attach a callback to a hook. Three hooks are currently implemented: before_request Executed once before each request. The request context is available, but no routing has happened yet. after_request Executed once after each requ...
(self, name, func)
6,228
bottle
add_route
Add a route object, but do not change the :data:`Route.app` attribute.
def add_route(self, route): ''' Add a route object, but do not change the :data:`Route.app` attribute.''' self.routes.append(route) self.router.add(route.rule, route.method, route, name=route.name) if DEBUG: route.prepare()
(self, route)
6,229
bottle
close
Close the application and all installed plugins.
def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
(self)
6,230
bottle
default_error_handler
null
def default_error_handler(self, res): return tob(template(ERROR_PAGE_TEMPLATE, e=res))
(self, res)
6,231
bottle
delete
Equals :meth:`route` with a ``DELETE`` method parameter.
def delete(self, path=None, method='DELETE', **options): """ Equals :meth:`route` with a ``DELETE`` method parameter. """ return self.route(path, method, **options)
(self, path=None, method='DELETE', **options)
6,232
bottle
error
Decorator: Register an output handler for a HTTP error code
def error(self, code=500): """ Decorator: Register an output handler for a HTTP error code""" def wrapper(handler): self.error_handler[int(code)] = handler return handler return wrapper
(self, code=500)