text
stringlengths
81
112k
Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str] def _extract_programming_immediate_instructions_text(self, element_id): """ ...
Extract notebook text (instructions). @param element_id: Element id to extract notebook links. @type element_id: str @return: Notebook URL. @rtype: [str] def _extract_notebook_text(self, element_id): """ Extract notebook text (instructions). @param element_id:...
Extract assignment text (instructions). @param element_id: Element id to extract assignment instructions from. @type element_id: str @return: List of assignment text (instructions). @rtype: [str] def _extract_assignment_text(self, element_id): """ Extract assignment te...
Extract peer assignment text (instructions). @param element_id: Element id to extract peer assignment instructions from. @type element_id: str @return: List of peer assignment text (instructions). @rtype: [str] def _extract_peer_assignment_text(self, element_id): """ E...
Extract supplement links from the html text. Links may be provided in two ways: 1. <a> tags with href attribute 2. <asset> tags with id attribute (requires additional request to get the direct URL to the asset file) @param text: HTML text. @type text: str ...
Scan the text and extract asset tags and links to corresponding files. @param text: Page text. @type text: str @return: @see CourseraOnDemand._extract_links_from_text def _extract_links_from_asset_tags_in_text(self, text): """ Scan the text and extract asset tags and l...
Extract supplement links from the html text that contains <a> tags with href attribute. @param text: HTML text. @type text: str @return: Dictionary with supplement links grouped by extension. @rtype: { '<extension1>': [ ('<link1>', '<title1>'), ...
Create M3U playlist with contents of `section_dir`/*.mp4. The playlist will be created in that directory. @param section_dir: Path where to scan for *.mp4 files. @type section_dir: str def create_m3u_playlist(section_dir): """ Create M3U playlist with contents of `section_dir`/*.mp4. The playlist ...
List enrolled courses. @return: List of enrolled courses. @rtype: [str] def list_courses(self): """ List enrolled courses. @return: List of enrolled courses. @rtype: [str] """ course = CourseraOnDemand(session=self._session, ...
Get the on-demand course listing webpage. def _get_on_demand_syllabus(self, class_name): """ Get the on-demand course listing webpage. """ url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format( class_name=class_name) page = get_page(self._session, url) loggin...
Parse a Coursera on-demand course listing/syllabus page. @return: Tuple of (bool, list), where bool indicates whether there was at least on error while parsing syllabus, the list is a list of parsed modules. @rtype: (bool, list) def _parse_on_demand_syllabus(self, course_name, ...
This huge function generates a hierarchy with hopefully more clear structure of modules/sections/lectures. def _iter_modules(modules, class_name, path, ignored_formats, args): """ This huge function generates a hierarchy with hopefully more clear structure of modules/sections/lectures. """ file...
Helper generator that traverses modules in returns a flattened iterator. def _walk_modules(modules, class_name, path, ignored_formats, args): """ Helper generator that traverses modules in returns a flattened iterator. """ for module in _iter_modules(modules=modules, ...
Handle resource. This function builds up resource file name and downloads it if necessary. @param url: URL of the resource. @type url: str @param fmt: Format of the resource (pdf, csv, etc) @type fmt: str @param lecture_filename: File name of the lecture. @type...
Prepare a destination lecture filename. @param combined_section_lectures_nums: Flag that indicates whether section lectures should have combined numbering. @type combined_section_lectures_nums: bool @param section_dir: Path to current section directory. @type section_dir: str @param secnu...
Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl def format_bytes(bytes): """ Get human readable version of given bytes. Ripped from https://github.com/rg3/youtube-dl """ if bytes is None: return 'N/A' if type(bytes) is str: bytes = fl...
Decides which downloader to use. def get_downloader(session, class_name, args): """ Decides which downloader to use. """ external = { 'wget': WgetDownloader, 'curl': CurlDownloader, 'aria2': Aria2Downloader, 'axel': AxelDownloader, } for bin, class_ in iteritem...
Download the given url to the given file. When the download is aborted by the user, the partially downloaded file is also removed. def download(self, url, filename, resume=False): """ Download the given url to the given file. When the download is aborted by the user, the partially downl...
Extract cookies from the requests session and add them to the command def _prepare_cookies(self, command, url): """ Extract cookies from the requests session and add them to the command """ req = requests.models.Request() req.method = 'GET' req.url = url cookie...
Report download progress. def report_progress(self): """Report download progress.""" percent = self.calc_percent() total = format_bytes(self._total) speed = self.calc_speed() total_speed_report = '{0} at {1}'.format(total, speed) report = '\r{0: <56} {1: >30}'.format(p...
Actual download call. Calls the underlying file downloader, catches all exceptions and returns the result. def _download_wrapper(self, url, *args, **kwargs): """ Actual download call. Calls the underlying file downloader, catches all exceptions and returns the result. """ ...
Return a list of config files paths to try in order, given config file name and possibly a user-specified path. For Windows platforms, there are several paths that can be tried to retrieve the netrc file. There is, however, no "standard way" of doing things. A brief recap of the situation (all fil...
Return the tuple user / password given a path for the .netrc file. Raises CredentialsError if no valid netrc file is found. def authenticate_through_netrc(path=None): """ Return the tuple user / password given a path for the .netrc file. Raises CredentialsError if no valid netrc file is found. ""...
Return valid username, password tuple. Raises CredentialsError if username or password is missing. def get_credentials(username=None, password=None, netrc=None, use_keyring=False): """ Return valid username, password tuple. Raises CredentialsError if username or password is missing. """ if ne...
The mimetype (content type without charset etc.) def mimetype(self): """The mimetype (content type without charset etc.)""" ct = self.headers.get("content-type") if ct: return ct.split(";")[0].strip()
The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``. .. versionadded:: 0.5 def mimetype_params(self): """The mimetype parameters as dict. For example if the content type is ``text/html; ch...
Index of all pages. def page_index(request): """Index of all pages.""" letters = {} for page in Page.query.order_by(Page.name): letters.setdefault(page.name.capitalize()[0], []).append(page) return Response( generate_template("page_index.html", letters=sorted(letters.items())) )
Display the recent changes. def recent_changes(request): """Display the recent changes.""" page = max(1, request.args.get("page", type=int)) query = RevisionedPage.query.order_by(RevisionedPage.revision_id.desc()) return Response( generate_template( "recent_changes.html", ...
Helper function that creates a plnt app. def make_app(): """Helper function that creates a plnt app.""" from plnt import Plnt database_uri = os.environ.get("PLNT_DATABASE_URI") app = Plnt(database_uri or "sqlite:////tmp/plnt.db") app.bind_to_context() return app
Initialize the database def initdb(): """Initialize the database""" from plnt.database import Blog, session make_app().init_database() # and now fill in some python blogs everybody should read (shamelessly # added my own blog too) blogs = [ Blog( "Armin Ronacher", ...
Start a new development server. def runserver(hostname, port, no_reloader, debugger, no_evalex, threaded, processes): """Start a new development server.""" app = make_app() reloader = not no_reloader evalex = not no_evalex run_simple( hostname, port, app, use_reloade...
Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. def iter_multi_items(mapping): """Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. """ if isinstance(mapping, MultiDict): ...
Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In this case the function will return the default as if the value was not found: >>...
Used internally by the accessor properties. def _get_cache_value(self, key, empty, type): """Used internally by the accessor properties.""" if type is bool: return key in self if key in self: value = self[key] if value is None: return empty ...
Used internally by the accessor properties. def _set_cache_value(self, key, value, type): """Used internally by the accessor properties.""" if type is bool: if value: self[key] = None else: self.pop(key, None) else: if value is...
Remove a header from the set. This raises an :exc:`KeyError` if the header is not in the set. .. versionchanged:: 0.5 In older versions a :exc:`IndexError` was raised instead of a :exc:`KeyError` if the object was missing. :param header: the header to be removed. def ...
Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. def update(self, iterable): """Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. """ inserted...
Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up. def find(self, header): """Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up. """ header = header.lower(...
Return the index of the header in the set or raise an :exc:`IndexError`. :param header: the header to be looked up. def index(self, header): """Return the index of the header in the set or raise an :exc:`IndexError`. :param header: the header to be looked up. """ ...
Clear the set. def clear(self): """Clear the set.""" self._set.clear() del self._headers[:] if self.on_update is not None: self.on_update(self)
Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. :param preserve_casing: if set to `True` the items in the set returned will have the original case like in the :...
Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set. def as_set(self, include_weak=False): """Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set.""" rv = set(self._strong) if i...
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only. def contains_raw(self, etag): """When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is...
Convert the etags set into a HTTP header string. def to_header(self): """Convert the etags set into a HTTP header string.""" if self.star_tag: return "*" return ", ".join( ['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak] )
Converts the object back into an HTTP header. def to_header(self): """Converts the object back into an HTTP header.""" if self.date is not None: return http_date(self.date) if self.etag is not None: return quote_etag(self.etag) return ""
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a ``(start, stop)`` tuple, otherwise `None`. def range_for_length(self, length): """If the range is for bytes, the length is not None and there is exactly one range and it i...
Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. def make_content_range(self, length): """Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. """ rng = se...
Converts the object back into an HTTP header. def to_header(self): """Converts the object back into an HTTP header.""" ranges = [] for begin, end in self.ranges: if end is None: ranges.append("%s-" % begin if begin >= 0 else str(begin)) else: ...
Converts the object into `Content-Range` HTTP header, based on given length def to_content_range_header(self, length): """Converts the object into `Content-Range` HTTP header, based on given length """ range_for_length = self.range_for_length(length) if range_for_length ...
Clear the auth info and enable digest auth. def set_digest( self, realm, nonce, qop=("auth",), opaque=None, algorithm=None, stale=False ): """Clear the auth info and enable digest auth.""" d = { "__auth_type__": "digest", "realm": realm, "nonce": nonce, ...
Convert the stored values into a WWW-Authenticate header. def to_header(self): """Convert the stored values into a WWW-Authenticate header.""" d = dict(self) auth_type = d.pop("__auth_type__", None) or "basic" return "%s %s" % ( auth_type.title(), ", ".join( ...
A static helper function for subclasses to add extra authentication system properties onto a class:: class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') For more information have a look at the sourcecode to see how the regular prop...
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at :func:`...
Enforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`BaseResponse` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a regular :class:`BaseResponse` object, even if you...
Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the `write()` callable returned by the `start_response` function. This tries to resolve such edge cases automati...
Returns the content length if available or `None` otherwise. def calculate_content_length(self): """Returns the content length if available or `None` otherwise.""" try: self._ensure_sequence() except RuntimeError: return None return sum(len(x) for x in self.iter_...
Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. .. versionadded:: 0.6 def ...
Sets a cookie. The parameters are the same as in the cookie `Morsel` object in the Python standard library but it accepts unicode data, too. A warning is raised if the size of the cookie header exceeds :attr:`max_cookie_size`, but the header will still be set. :param key: the key (name...
Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. .. versionadded:: 0.9 Can now be used in a with statement. def close(self): """Close the wrapped response if possible. You can also use the object in ...
This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the roo...
Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment i...
Returns a binary digest for the PBKDF2 hash algorithm of `data` with the given `salt`. It iterates `iterations` times and produces a key of `keylen` bytes. By default, SHA-256 is used as hash function; a different hashlib `hashfunc` can be provided. .. versionadded:: 0.9 :param data: the data to d...
Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted passwords are used hmac is used. def _hash_internal(method, salt, password): """Internal password hash helper. Supports plaintext without salt, unsalted and salted passwords. In case salted...
Safely join `directory` and one or more untrusted `pathnames`. If this cannot be done, this function returns ``None``. :param directory: the base directory. :param pathnames: the untrusted pathnames relative to that directory. def safe_join(directory, *pathnames): """Safely join `directory` and one o...
Generates an adhoc SSL context for the development server. def generate_adhoc_ssl_context(): """Generates an adhoc SSL context for the development server.""" crypto = _get_openssl_crypto_module() import tempfile import atexit cert, pkey = generate_adhoc_ssl_pair() cert_handle, cert_file = temp...
Loads SSL context from cert/private key files and optional protocol. Many parameters are directly taken from the API of :py:class:`ssl.SSLContext`. :param cert_file: Path of the certificate to use. :param pkey_file: Path of the private key to use. If not given, the key will be obt...
Checks if the given error (or the current one) is an SSL error. def is_ssl_error(error=None): """Checks if the given error (or the current one) is an SSL error.""" exc_types = (ssl.SSLError,) try: from OpenSSL.SSL import Error exc_types += (Error,) except ImportError: pass ...
Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port. def select_address_family(host, port): """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.""" # disabled due to problems with current ipv6 implementations # and various operating syste...
Return a fully qualified socket address that can be passed to :func:`socket.bind`. def get_sockaddr(host, port, family): """Return a fully qualified socket address that can be passed to :func:`socket.bind`.""" if family == af_unix: return host.split("://", 1)[1] try: res = socket.ge...
Start a WSGI application. Optional features include a reloader, multithreading and fork support. This function has a command-line interface too:: python -m werkzeug.serving --help .. versionadded:: 0.5 `static_files` was added to simplify serving of static files as well as `passthro...
A simple command-line interface for :py:func:`run_simple`. def main(): """A simple command-line interface for :py:func:`run_simple`.""" # in contrast to argparse, this works at least under Python < 2.7 import optparse from .utils import import_string parser = optparse.OptionParser(usage="Usage: %...
Handles a request ignoring dropped connections. def handle(self): """Handles a request ignoring dropped connections.""" rv = None try: rv = BaseHTTPRequestHandler.handle(self) except (_ConnectionError, socket.timeout) as e: self.connection_dropped(e) exce...
A horrible, horrible way to kill the server for Python 2.6 and later. It's the best we can do. def initiate_shutdown(self): """A horrible, horrible way to kill the server for Python 2.6 and later. It's the best we can do. """ # Windows does not provide SIGKILL, go with SIGTERM...
Handle a single HTTP request. def handle_one_request(self): """Handle a single HTTP request.""" self.raw_requestline = self.rfile.readline() if not self.raw_requestline: self.close_connection = 1 elif self.parse_request(): return self.run_wsgi()
Send the response header and log the response code. def send_response(self, code, message=None): """Send the response header and log the response code.""" self.log_request(code) if message is None: message = code in self.responses and self.responses[code][0] or "" if self.re...
Get an iterable list of key/value pairs representing headers. This function provides Python 2/3 compatibility as related to the parsing of request headers. Python 2.7 is not compliant with RFC 3875 Section 4.1.18 which requires multiple values for headers to be provided. This function w...
Check if there is a handler in the logging chain that will handle the given logger's effective level. def _has_level_handler(logger): """Check if there is a handler in the logging chain that will handle the given logger's effective level. """ level = logger.getEffectiveLevel() current = logger ...
Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added. def _log(type, message, *args, **kwargs): """L...
Return a signature object for the function. def _parse_signature(func): """Return a signature object for the function.""" if hasattr(func, "im_func"): func = func.im_func # if we have a cached validator for this function, return it parse = _signature_cache.get(func) if parse is not None: ...
Converts a timetuple, integer or datetime object into the seconds from epoch in utc. def _date_to_unix(arg): """Converts a timetuple, integer or datetime object into the seconds from epoch in utc. """ if isinstance(arg, datetime): arg = arg.utctimetuple() elif isinstance(arg, integer_ty...
Lowlevel cookie parsing facility that operates on bytes. def _cookie_parse_impl(b): """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) while i < n: match = _cookie_re.search(b + b";", i) if not match: break key = match.group("key").stri...
Like the name says. But who knows how it works? def _easteregg(app=None): """Like the name says. But who knows how it works?""" def bzzzzzzz(gyver): import base64 import zlib return zlib.decompress(base64.b64decode(gyver)).decode("ascii") gyver = u"\n".join( [ ...
Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for ...
The name of the pin cookie. def pin_cookie_name(self): """The name of the pin cookie.""" if not hasattr(self, "_pin_cookie"): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin_cookie
Execute a command in a console. def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype="text/html")
Display a standalone shell. def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault("app", self.a...
Return a static resource from the shared folder. def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join("shared", basename(filename)) try: data = pkgutil.get_data(__package__, filename) except OSError: da...
Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken. def check_pin_trust(self, environ): ...
Authenticates with the pin. def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value ...
Log the pin if needed. def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log( "info", " * To enable the debugger you need to enter the security pin:" ) _log("info", " * Debugger pin code: %s" % self...
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). This does not use the real unquoting but what browsers are actually using for quoting. .. versionadded:: 0.5 :param value: the header value to unquote. def unquote_header_value(value, is_filename=False): r"""Unquotes a header...
The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of options to append. def dump_options_header(header, options): """The reverse function to :func:`parse_options_header`. :param header: the header to dump :param options: a dict of optio...
Dump an HTTP header again. This is the reversal of :func:`parse_list_header`, :func:`parse_set_header` and :func:`parse_dict_header`. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> du...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True ...
Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightly different format. For these headers u...
Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality with some additional accessor methods). The s...
Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements. .. versionadded:: 0.5 The `cls` was added. If not specified an immutable :class:`~werkzeug.datastructures.Reques...
Parse a set-like header and return a :class:`~werkzeug.datastructures.HeaderSet` object: >>> hs = parse_set_header('token, "quoted value"') The return value is an object that treats the items case-insensitively and keeps the order of the items: >>> 'TOKEN' in hs True >>> hs.index('quoted ...
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an :class:`~werkzeug.datastructures.Authorization` object. :param value: the authorization header to parse. :return: a :class:`~werkze...
Parse an HTTP WWW-Authenticate header into a :class:`~werkzeug.datastructures.WWWAuthenticate` object. :param value: a WWW-Authenticate header to parse. :param on_update: an optional callable that is called every time a value on the :class:`~werkzeug.datastructures.WWWAuthenticate` ...