INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version
def get_version(): """ Get version without importing from elasticapm. This avoids any side effects from importing while installing and/or building the module :return: a string, indicating the version """ version_file = open(os.path.join("elasticapm", "version.py"), encoding="utf-8") for line...
Returns only proper HTTP headers.
def get_headers(environ): """ Returns only proper HTTP headers. """ for key, value in compat.iteritems(environ): key = str(key) if key.startswith("HTTP_") and key not in ("HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"): yield key[5:].replace("_", "-").lower(), value elif ...
A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_...
def get_current_url(environ, root_only=False, strip_querystring=False, host_only=False): """A handy helper function that recreates the full URL for the current request or parts of it. Here an example: >>> from werkzeug import create_environ >>> env = create_environ("/?param=foo", "http://localhost/scr...
Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None
def _flush(self, buffer): """ Flush the queue. This method should only be called from the event processing queue :param sync: if true, flushes the queue synchronously in the current thread :return: None """ if not self.state.should_try(): logger.error("droppin...
Cleans up resources and closes connection :return:
def close(self): """ Cleans up resources and closes connection :return: """ if self._closed: return self._closed = True self.queue("close", None) if not self._flushed.wait(timeout=self._max_flush_time): raise ValueError("close timed...
Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed.
def flush(self): """ Trigger a flush of the queue. Note: this method will only return once the queue is empty. This means it can block indefinitely if more events are produced in other threads than can be consumed. """ self.queue(None, None, flush=True) if not sel...
Failure handler called by the transport on send failure
def handle_transport_fail(self, exception=None, **kwargs): """ Failure handler called by the transport on send failure """ message = str(exception) logger.error("Failed to submit message: %r", message, exc_info=getattr(exception, "print_trace", True)) self.state.set_fail(...
Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds and raises the Full exception if no free slot was available wit...
def put(self, item, block=True, timeout=None, chill=True): """Put an item into the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until a free slot is available. If 'timeout' is a non-negative number, it blocks at most 'timeout' seconds a...
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison.
def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() parse_result = compat.urlparse.urlparse(url) scheme, host, port = parse_result.scheme, parse_result.hostn...
Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client
def get_client(client=None): """ Get an ElasticAPM client. :param client: :return: :rtype: elasticapm.base.Client """ global _client tmp_client = client is not None if not tmp_client: config = getattr(django_settings, "ELASTIC_APM", {}) client = config.get("CLIENT",...
Generate a list of modules in settings.INSTALLED_APPS.
def _get_installed_apps_paths(): """ Generate a list of modules in settings.INSTALLED_APPS. """ out = set() for app in django_settings.INSTALLED_APPS: out.add(app) return out
If the stacktrace originates within the elasticapm module, it will skip frames until some other module comes up.
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """If the stacktrace originates within the elasticapm module, it will skip frames until som...
Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``.
def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. """ if self.config.server_url: ...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.
def deprecated(alternative=None): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.""" def real_decorator(func): @functools.wraps(func) def new_func(*args, **kwargs): msg = "Call to ...
Register a new metric set :param class_path: a string with the import path of the metricset class
def register(self, class_path): """ Register a new metric set :param class_path: a string with the import path of the metricset class """ if class_path in self._metricsets: return else: try: class_obj = import_string(class_path) ...
Collect metrics from all registered metric sets :return:
def collect(self): """ Collect metrics from all registered metric sets :return: """ logger.debug("Collecting metrics") for name, metricset in compat.iteritems(self._metricsets): data = metricset.collect() if data: self._queue_func(...
Returns an existing or creates and returns a new counter :param name: name of the counter :return: the counter object
def counter(self, name): """ Returns an existing or creates and returns a new counter :param name: name of the counter :return: the counter object """ with self._lock: if name not in self._counters: if self._registry._ignore_patterns and any( ...
Returns an existing or creates and returns a new gauge :param name: name of the gauge :return: the gauge object
def gauge(self, name): """ Returns an existing or creates and returns a new gauge :param name: name of the gauge :return: the gauge object """ with self._lock: if name not in self._gauges: if self._registry._ignore_patterns and any( ...
Collects all metrics attached to this metricset, and returns it as a list, together with a timestamp in microsecond precision. The format of the return value should be { "samples": {"metric.name": {"value": some_float}, ...}, "timestamp": unix epoch in micro...
def collect(self): """ Collects all metrics attached to this metricset, and returns it as a list, together with a timestamp in microsecond precision. The format of the return value should be { "samples": {"metric.name": {"value": some_float}, ...}, ...
Tags current transaction. Both key and value of the tag should be strings.
def tag(**tags): """ Tags current transaction. Both key and value of the tag should be strings. """ transaction = execution_context.get_transaction() if not transaction: error_logger.warning("Ignored tags %s. No transaction currently active.", ", ".join(tags.keys())) else: transa...
Begin a new span :param name: name of the span :param span_type: type of the span :param context: a context dict :param leaf: True if this is a leaf span :param tags: a flat string/string dict of tags :return: the Span object
def begin_span(self, name, span_type, context=None, leaf=False, tags=None): """ Begin a new span :param name: name of the span :param span_type: type of the span :param context: a context dict :param leaf: True if this is a leaf span :param tags: a flat string/str...
If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction.
def ensure_parent_id(self): """If current trace_parent has no span_id, generate one, then return it This is used to generate a span ID which the RUM agent will use to correlate the RUM transaction with the backend transaction. """ if self.trace_parent.span_id == self.id: ...
Tag this transaction with one or multiple key/value tags. Both the values should be strings transaction_obj.tag(key1="value1", key2="value2") Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_)
def tag(self, **tags): """ Tag this transaction with one or multiple key/value tags. Both the values should be strings transaction_obj.tag(key1="value1", key2="value2") Note that keys will be dedotted, replacing dot (.), star (*) and double quote (") with an underscore (_) ...
Start a new transactions and bind it in a thread-local variable :returns the Transaction object
def begin_transaction(self, transaction_type, trace_parent=None): """ Start a new transactions and bind it in a thread-local variable :returns the Transaction object """ if trace_parent: is_sampled = bool(trace_parent.trace_options.recorded) else: ...
Check your settings for common misconfigurations
def handle_check(self, command, **options): """Check your settings for common misconfigurations""" passed = True client = DjangoClient(metrics_interval="0ms") def is_set(x): return x and x != "None" # check if org/app is set: if is_set(client.config.service_...
wrapper around self.stdout/stderr to ensure Django 1.4 compatibility
def write(self, msg, style_func=None, ending=None, stream=None): """ wrapper around self.stdout/stderr to ensure Django 1.4 compatibility """ if stream is None: stream = self.stdout if OutputWrapper is None: ending = "\n" if ending is None else ending ...
Called when an exception has been raised in the code run by ZeroRPC
def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """Called when an exception has been raised in the code run by ZeroRPC""" # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ/STREAM server the frames to hide are: # - core.ServerBase._a...
Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method: :param wrapped: :param instance: :param args: :param kwargs: :param transactio...
def mutate_unsampled_call_args(self, module, method, wrapped, instance, args, kwargs, transaction): """ Method called for unsampled wrapped calls. This can e.g. be used to add traceparent headers to the underlying http call for HTTP instrumentations. :param module: :param method...
Auto-instruments code to get nice spans
def instrument(client): """ Auto-instruments code to get nice spans """ from elasticapm.instrumentation.control import instrument instrument() try: import celery # noqa F401 from elasticapm.contrib.celery import register_instrumentation register_instrumentation(client)...
Configures logging to pipe to Elastic APM. - ``exclude`` is a list of loggers that shouldn't go to ElasticAPM. For a typical Python install: >>> from elasticapm.handlers.logging import LoggingHandler >>> client = ElasticAPM(...) >>> setup_logging(LoggingHandler(client)) Within Django: >...
def setup_logging(handler, exclude=("gunicorn", "south", "elasticapm.errors")): """ Configures logging to pipe to Elastic APM. - ``exclude`` is a list of loggers that shouldn't go to ElasticAPM. For a typical Python install: >>> from elasticapm.handlers.logging import LoggingHandler >>> clien...
Given an ElasticAPM client and an RQ worker, registers exception handlers with the worker so exceptions are logged to the apm server. E.g.: from elasticapm.contrib.django.models import client from elasticapm.contrib.rq import register_elasticapm worker = Worker(map(Queue, listen)) register_el...
def register_elasticapm(client, worker): """Given an ElasticAPM client and an RQ worker, registers exception handlers with the worker so exceptions are logged to the apm server. E.g.: from elasticapm.contrib.django.models import client from elasticapm.contrib.rq import register_elasticapm wor...
Get the transaction registered for the current thread. :return: :rtype: Transaction
def get_transaction(self, clear=False): """ Get the transaction registered for the current thread. :return: :rtype: Transaction """ transaction = getattr(self.thread_local, "transaction", None) if clear: self.thread_local.transaction = None re...
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): """ Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ lineno = lineno - 1 lower_bound = max(0, lineno - context_lines) up...
Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable.
def iter_traceback_frames(tb): """ Given a traceback object, it will iterate over all frames that do not contain the ``__traceback_hide__`` local variable. """ while tb: # support for __traceback_hide__ which is used by a few libraries # to hide internal frames. frame = t...
Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple of module names. If the module of a frame matches one of the names (using `.startswith...
def iter_stack_frames(frames=None, start_frame=None, skip=0, skip_top_modules=()): """ Given an optional list of frames (defaults to current stack), iterates over all frames that do not contain the ``__traceback_hide__`` local variable. Frames can be skipped by either providing a number, or a tuple...
Given a list of frames, returns a list of stack information dictionary objects that are JSON-ready. We have to be careful here as certain implementations of the _Frame class do not contain the necessary data to lookup all of the information we want. :param frames: a list of (Frame, lineno) tuples ...
def get_stack_info( frames, with_locals=True, library_frame_context_lines=None, in_app_frame_context_lines=None, include_paths_re=None, exclude_paths_re=None, locals_processor_func=None, ): """ Given a list of frames, returns a list of stack information dictionary objects that ar...
Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit
def atexit_register(func): """ Uses either uwsgi's atexit mechanism, or atexit from the stdlib. When running under uwsgi, using their atexit handler is more reliable, especially when using gevent :param func: the function to call at exit """ try: import uwsgi orig = getattr...
Returns library paths depending on the used platform. :return: a list of glob paths
def get_default_library_patters(): """ Returns library paths depending on the used platform. :return: a list of glob paths """ python_version = platform.python_version_tuple() python_implementation = platform.python_implementation() system = platform.system() if python_implementation ==...
Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance
def multidict_to_dict(d): """ Turns a werkzeug.MultiDict or django.MultiValueDict into a dict with list values :param d: a MultiDict or MultiValueDict instance :return: a dict instance """ return dict((k, v[0] if len(v) == 1 else v) for k, v in iterlists(d))
Returns True if the given request *shouldn't* notify the site managers.
def _is_ignorable_404(uri): """ Returns True if the given request *shouldn't* notify the site managers. """ urls = getattr(django_settings, "IGNORABLE_404_URLS", ()) return any(pattern.search(uri) for pattern in urls)
Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141...
def get_cgroup_container_metadata(): """ Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "...
Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None
def parse_cgroups(filehandle): """ Reads lines from a file handle and tries to parse docker container IDs and kubernetes Pod IDs. See tests.utils.docker_tests.test_cgroup_parsing for a set of test cases :param filehandle: :return: nested dictionary or None """ for line in filehandle: ...
:param events: list of event types Only calls wrapped function if given event_type is in list of events
def for_events(*events): """ :param events: list of event types Only calls wrapped function if given event_type is in list of events """ events = set(events) def wrap(func): func.event_types = events return func return wrap
Removes local variables from any frames. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def remove_stacktrace_locals(client, event): """ Removes local variables from any frames. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ func = lambda frame: frame.pop("vars", None) return _process_stack_frames(event, func)
Sanitizes local variables in all frames :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_stacktrace_locals(client, event): """ Sanitizes local variables in all frames :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ def func(frame): if "vars" in frame: frame["vars"] = varmap(_sanitiz...
Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_request_cookies(client, event): """ Sanitizes http request cookies :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ # sanitize request.cookies dict try: cookies = event["context"]["request"]["cookie...
Sanitizes the set-cookie header of the response :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_response_cookies(client, event): """ Sanitizes the set-cookie header of the response :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: cookie_string = event["context"]["response"]["headers"]["set-cook...
Sanitizes http request/response headers :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_headers(client, event): """ Sanitizes http request/response headers :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ # request headers try: headers = event["context"]["request"]["headers"] ev...
Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_wsgi_env(client, event): """ Sanitizes WSGI environment variables :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: env = event["context"]["request"]["env"] event["context"]["request"]["env"]...
Sanitizes http request query string :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_request_querystring(client, event): """ Sanitizes http request query string :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event """ try: query_string = force_text(event["context"]["request"]["url"]["search"], e...
Sanitizes http request body. This only works if the request body is a query-encoded string. Other types (e.g. JSON) are not handled by this sanitizer. :param client: an ElasticAPM client :param event: a transaction or error event :return: The modified event
def sanitize_http_request_body(client, event): """ Sanitizes http request body. This only works if the request body is a query-encoded string. Other types (e.g. JSON) are not handled by this sanitizer. :param client: an ElasticAPM client :param event: a transaction or error event :return: T...
sanitizes a string that contains multiple key/value items :param unsanitized: the unsanitized string :param itemsep: string that separates items :param kvsep: string that separates key from value :return: a sanitized string
def _sanitize_string(unsanitized, itemsep, kvsep): """ sanitizes a string that contains multiple key/value items :param unsanitized: the unsanitized string :param itemsep: string that separates items :param kvsep: string that separates key from value :return: a sanitized string """ sanit...
Captures and processes an event and pipes it off to Client.send.
def capture(self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs): """ Captures and processes an event and pipes it off to Client.send. """ if event_type == "Exception": # never gather log stack for exceptions stack = False ...
Creates an event from ``message``. >>> client.capture_message('My event just happened!')
def capture_message(self, message=None, param_message=None, **kwargs): """ Creates an event from ``message``. >>> client.capture_message('My event just happened!') """ return self.capture("Message", message=message, param_message=param_message, **kwargs)
Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.capture_exception(exc_info) >>> finally: >>> del exc_info If exc_info is not provided, or is set to True, then this method will perform the ``exc_info = sys.exc_inf...
def capture_exception(self, exc_info=None, handled=True, **kwargs): """ Creates an event from an exception. >>> try: >>> exc_info = sys.exc_info() >>> client.capture_exception(exc_info) >>> finally: >>> del exc_info If exc_info is not provide...
Captures, processes and serializes an event into a dict object
def _build_msg_for_logging( self, event_type, date=None, context=None, custom=None, stack=None, handled=True, **kwargs ): """ Captures, processes and serializes an event into a dict object """ transaction = execution_context.get_transaction() if transaction: ...
Register the start of a transaction on the client
def begin_transaction(self, transaction_type, trace_parent=None): """Register the start of a transaction on the client """ return self.tracer.begin_transaction(transaction_type, trace_parent=trace_parent)
Overrideable in derived clients to add frames/info, e.g. templates
def _get_stack_info_for_trace( self, frames, library_frame_context_lines=None, in_app_frame_context_lines=None, with_locals=True, locals_processor_func=None, ): """Overrideable in derived clients to add frames/info, e.g. templates""" return stacks.get_...
This utility executes a single notebook on a container. Papermill takes a source notebook, applies parameters to the source notebook, executes the notebook with the specified kernel, and saves the output in the destination notebook.
def papermill( notebook_path, output_path, parameters, parameters_raw, parameters_file, parameters_yaml, parameters_base64, inject_input_path, inject_output_path, inject_paths, engine, prepare_only, kernel, cwd, progress_bar, log_output, log_level, ...
Wrapper to catch `nb` keyword arguments This helps catch `nb` keyword arguments and assign onto self when passed to the wrapped function. Used for callback methods when the caller may optionally have a new copy of the originally wrapped `nb` object.
def catch_nb_assignment(func): """ Wrapper to catch `nb` keyword arguments This helps catch `nb` keyword arguments and assign onto self when passed to the wrapped function. Used for callback methods when the caller may optionally have a new copy of the originally wrapped `nb` object. """ ...
Register entrypoints for an engine Load handlers provided by other packages
def register_entry_points(self): """Register entrypoints for an engine Load handlers provided by other packages """ for entrypoint in entrypoints.get_group_all("papermill.engine"): self.register(entrypoint.name, entrypoint.load())
Retrieves an engine by name.
def get_engine(self, name=None): """Retrieves an engine by name.""" engine = self._engines.get(name) if not engine: raise PapermillException("No engine named '{}' found".format(name)) return engine
Fetch a named engine and execute the nb object against it.
def execute_notebook_with_engine(self, engine_name, nb, kernel_name, **kwargs): """Fetch a named engine and execute the nb object against it.""" return self.get_engine(engine_name).execute_notebook(nb, kernel_name, **kwargs)
Saves the wrapped notebook state. If an output path is known, this triggers a save of the wrapped notebook state to the provided path. Can be used outside of cell state changes if execution is taking a long time to conclude but the notebook object should be synced. For example...
def save(self, **kwargs): """ Saves the wrapped notebook state. If an output path is known, this triggers a save of the wrapped notebook state to the provided path. Can be used outside of cell state changes if execution is taking a long time to conclude but the notebook...
Initialize a notebook, clearing its metadata, and save it. When starting a notebook, this initializes and clears the metadata for the notebook and its cells, and saves the notebook to the given output path. Called by Engine when execution begins.
def notebook_start(self, **kwargs): """ Initialize a notebook, clearing its metadata, and save it. When starting a notebook, this initializes and clears the metadata for the notebook and its cells, and saves the notebook to the given output path. Called by Engine when e...
Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path.
def cell_start(self, cell, cell_index=None, **kwargs): """ Set and save a cell's start state. Optionally called by engines during execution to initialize the metadata for a cell and save the notebook to the output path. """ if self.log_output: ceel_num = cell...
Set metadata when an exception is raised. Called by engines when an exception is raised within a notebook to set the metadata on the notebook indicating the location of the failure.
def cell_exception(self, cell, cell_index=None, **kwargs): """ Set metadata when an exception is raised. Called by engines when an exception is raised within a notebook to set the metadata on the notebook indicating the location of the failure. """ cell.metadata....
Finalize metadata for a cell and save notebook. Optionally called by engines during execution to finalize the metadata for a cell and save the notebook to the output path.
def cell_complete(self, cell, cell_index=None, **kwargs): """ Finalize metadata for a cell and save notebook. Optionally called by engines during execution to finalize the metadata for a cell and save the notebook to the output path. """ end_time = self.now() if...
Finalize the metadata for a notebook and save the notebook to the output path. Called by Engine when execution concludes, regardless of exceptions.
def notebook_complete(self, **kwargs): """ Finalize the metadata for a notebook and save the notebook to the output path. Called by Engine when execution concludes, regardless of exceptions. """ self.end_time = self.now() self.nb.metadata.papermill['end_time'] = ...
Refresh progress bar
def complete_pbar(self): """Refresh progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.n = len(self.nb.cells) self.pbar.refresh()
Clean up a progress bar
def cleanup_pbar(self): """Clean up a progress bar""" if hasattr(self, 'pbar') and self.pbar: self.pbar.close() self.pbar = None
A wrapper to handle notebook execution tasks. Wraps the notebook object in a `NotebookExecutionManager` in order to track execution state in a uniform manner. This is meant to help simplify engine implementations. This allows a developer to just focus on iterating and executing the cell...
def execute_notebook( cls, nb, kernel_name, output_path=None, progress_bar=True, log_output=False, **kwargs ): """ A wrapper to handle notebook execution tasks. Wraps the notebook object in a `NotebookExecutionManager` in order to track execution state in a uniform manner. T...
Performs the actual execution of the parameterized notebook locally. Args: nb (NotebookNode): Executable notebook object. kernel_name (str): Name of kernel to execute the notebook against. log_output (bool): Flag for whether or not to write notebook output to stderr. ...
def execute_managed_notebook( cls, nb_man, kernel_name, log_output=False, start_timeout=60, execution_timeout=None, **kwargs ): """ Performs the actual execution of the parameterized notebook locally. Args: nb (NotebookNode...
see: https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 # noqa: E501 abs://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sastoken
def _split_url(self, url): """ see: https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 # noqa: E501 abs://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sastoken """ match = re.match(r"abs://(.*)\.blob\.core\.windows\.ne...
Read storage at a given url
def read(self, url): """Read storage at a given url""" params = self._split_url(url) output_stream = io.BytesIO() block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block_blob_service.get_blob_to_str...
Returns a list of the files under the specified path
def listdir(self, url): """Returns a list of the files under the specified path""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) blobs = block_blob_service.list_blobs(param...
Write buffer to storage at a given url
def write(self, buf, url): """Write buffer to storage at a given url""" params = self._split_url(url) block_blob_service = self._block_blob_service( account_name=params["account"], sas_token=params["sas_token"] ) block_blob_service.create_blob_from_text( ...
Executes a single notebook locally. Parameters ---------- input_path : str Path to input notebook output_path : str Path to save executed notebook parameters : dict, optional Arbitrary keyword arguments to pass to the notebook parameters engine_name : str, optional ...
def execute_notebook( input_path, output_path, parameters=None, engine_name=None, prepare_only=False, kernel_name=None, progress_bar=True, log_output=False, start_timeout=60, report_mode=False, cwd=None, ): """Executes a single notebook locally. Parameters ------...
Prepare metadata associated with a notebook and its cells Parameters ---------- nb : NotebookNode Executable notebook object input_path : str Path to input notebook output_path : str Path to write executed notebook report_mode : bool, optional Flag to set report mod...
def prepare_notebook_metadata(nb, input_path, output_path, report_mode=False): """Prepare metadata associated with a notebook and its cells Parameters ---------- nb : NotebookNode Executable notebook object input_path : str Path to input notebook output_path : str Path to ...
Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook
def raise_for_execution_errors(nb, output_path): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object output_path : str Path to write executed notebook """ error = None for cell in nb.cel...
Limits a list of Bucket's objects based on prefix and delimiter.
def list(self, prefix='', delimiter=None): """Limits a list of Bucket's objects based on prefix and delimiter.""" return self.service._list( bucket=self.name, prefix=prefix, delimiter=delimiter, objects=True )
Copies source string into the destination location. Parameters ---------- source: string the string with the content to copy dest: string the s3 location
def cp_string(self, source, dest, **kwargs): """ Copies source string into the destination location. Parameters ---------- source: string the string with the content to copy dest: string the s3 location """ assert isinstance(sourc...
Returns a list of the files under the specified path name must be in the form of `s3://bucket/prefix` Parameters ---------- keys: optional if True then this will return the actual boto keys for files that are encountered objects: optional if True...
def list(self, name, iterator=False, **kwargs): """ Returns a list of the files under the specified path name must be in the form of `s3://bucket/prefix` Parameters ---------- keys: optional if True then this will return the actual boto keys for files ...
Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters ---------- keys: optional if True then t...
def listdir(self, name, **kwargs): """ Returns a list of the files under the specified path. This is different from list as it will only give you files under the current directory, much like ls. name must be in the form of `s3://bucket/prefix/` Parameters -----...
Iterates over a file in s3 split on newline. Yields a line in file.
def read(self, source, compressed=False, encoding='UTF-8'): """ Iterates over a file in s3 split on newline. Yields a line in file. """ buf = '' for block in self.cat(source, compressed=compressed, encoding=encoding): buf += block if '\n' in buf:...
Reusable by most interpreters
def translate_escaped_str(cls, str_val): """Reusable by most interpreters""" if isinstance(str_val, string_types): str_val = str_val.encode('unicode_escape') if sys.version_info >= (3, 0): str_val = str_val.decode('utf-8') str_val = str_val.replace('"'...
Translate each of the standard json/yaml types to appropiate objects.
def translate(cls, val): """Translate each of the standard json/yaml types to appropiate objects.""" if val is None: return cls.translate_none(val) elif isinstance(val, string_types): return cls.translate_str(val) # Needs to be before integer checks elif i...
Translate dicts to scala Maps
def translate_dict(cls, val): """Translate dicts to scala Maps""" escaped = ', '.join( ["{} -> {}".format(cls.translate_str(k), cls.translate(v)) for k, v in val.items()] ) return 'Map({})'.format(escaped)
Translate list to scala Seq
def translate_list(cls, val): """Translate list to scala Seq""" escaped = ', '.join([cls.translate(v) for v in val]) return 'Seq({})'.format(escaped)
Returns a notebook object with papermill metadata loaded from the specified path. Args: notebook_path (str): Path to the notebook file. Returns: nbformat.NotebookNode
def load_notebook_node(notebook_path): """Returns a notebook object with papermill metadata loaded from the specified path. Args: notebook_path (str): Path to the notebook file. Returns: nbformat.NotebookNode """ nb = nbformat.reads(papermill_io.read(notebook_path), as_version=4) ...
Sets the cwd during reads and writes
def cwd(self, new_path): '''Sets the cwd during reads and writes''' old_cwd = self._cwd self._cwd = new_path return old_cwd
Returns a list of the files under the specified path
def listdir(self, url): """Returns a list of the files under the specified path""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) return [ "adl://{store_name}.azuredatalakestore.net/{path_to_child}".format( store_name=stor...
Read storage at a given url
def read(self, url): """Read storage at a given url""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) lines = [] with adapter.open(path) as f: for line in f: lines.append(line.decode()) return lines
Write buffer to storage at a given url
def write(self, buf, url): """Write buffer to storage at a given url""" (store_name, path) = self._split_url(url) adapter = self._create_adapter(store_name) with adapter.open(path, 'wb') as f: f.write(buf.encode())
Wraps the parent class process call slightly
def preprocess(self, nb_man, resources, km=None): """ Wraps the parent class process call slightly """ with self.setup_preprocessor(nb_man.nb, resources, km=km): if self.log_output: self.log.info("Executing notebook with kernel: {}".format(self.kernel_name)) ...
This function acts as a replacement for the grandparent's `preprocess` method. We are doing this for the following reasons: 1. Notebooks will stop executing when they encounter a failure but not raise a `CellException`. This allows us to save the notebook with the traceba...
def papermill_process(self, nb_man, resources): """ This function acts as a replacement for the grandparent's `preprocess` method. We are doing this for the following reasons: 1. Notebooks will stop executing when they encounter a failure but not raise a `CellExcepti...
Add built-in parameters to a dictionary of parameters Parameters ---------- parameters : dict Dictionary of parameters provided by the user
def add_builtin_parameters(parameters): """Add built-in parameters to a dictionary of parameters Parameters ---------- parameters : dict Dictionary of parameters provided by the user """ with_builtin_parameters = { "pm": { "run_uuid": str(uuid4()), "curren...
Format a path with a provided dictionary of parameters Parameters ---------- path : string Path with optional parameters, as a python format string parameters : dict Arbitrary keyword arguments to fill in the path
def parameterize_path(path, parameters): """Format a path with a provided dictionary of parameters Parameters ---------- path : string Path with optional parameters, as a python format string parameters : dict Arbitrary keyword arguments to fill in the path """ if parameters i...
Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object parameters : dict Arbitrary keyword arguments to pass as notebook parameters report_mode : bool, optional Flag to set report mode
def parameterize_notebook(nb, parameters, report_mode=False): """Assigned parameters into the appropriate place in the input notebook Parameters ---------- nb : NotebookNode Executable notebook object parameters : dict Arbitrary keyword arguments to pass as notebook parameters rep...
Returns True if `key` is a scan code or name of a modifier key.
def is_modifier(key): """ Returns True if `key` is a scan code or name of a modifier key. """ if _is_str(key): return key in all_modifiers else: if not _modifier_scan_codes: scan_codes = (key_to_scan_codes(name, False) for name in all_modifiers) _modifier_sca...