code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def all_of(api_call, *args, **kwargs): kwargs = kwargs.copy() pos, outer_limit = 0, kwargs.get('limit', 0) or sys.maxsize while True: response = api_call(*args, **kwargs) for item in response.get('results', []): pos += 1 if pos > outer_limit: retu...
Generator that iterates over all results of an API call that requires limit/start pagination. If the `limit` keyword argument is set, it is used to stop the generator after the given number of result items. >>> for i, v in enumerate(all_of(api.get_content)): >>> v = bunchify(v) >>> print('...
def _start_http_session(self): api_logger.debug("Starting new HTTP session...") self.session = requests.Session() self.session.headers.update({"User-Agent": self.user_agent}) if self.username and self.password: api_logger.debug("Requests will use authorization.") ...
Start a new requests HTTP session, clearing cookies and session data. :return: None
def get_content_by_id(self, content_id, status=None, version=None, expand=None, callback=None): params = {} if status: params["status"] = status if version is not None: params["version"] = int(version) if expand: params["expand"] = expand ...
Returns a piece of Content. :param content_id (string): The id of the content. :param status (string): OPTIONAL: List of Content statuses to filter results on. Default value: [current] :param version (int): OPTIONAL: The content version to retrieve. Default: Latest. :param expand (string...
def get_content_macro_by_hash(self, content_id, version, macro_hash, callback=None): return self._service_get_request("rest/api/content/{id}/history/{version}/macro/hash/{hash}" "".format(id=content_id, version=version, hash=macro_hash), callback=callback)
Returns the body of a macro (in storage format) with the given hash. This resource is primarily used by connect applications that require the body of macro to perform their work. The hash is generated by connect during render time of the local macro holder and is usually only relevant during th...
def get_content_macro_by_macro_id(self, content_id, version, macro_id, callback=None): return self._service_get_request("rest/api/content/{id}/history/{version}/macro/id/{macro_id}" "".format(id=content_id, version=int(version), macro_id=macro_id), ...
Returns the body of a macro (in storage format) with the given id. This resource is primarily used by connect applications that require the body of macro to perform their work. When content is created, if no macroId is specified, then Confluence will generate a random id. The id is persisted as...
def search_content(self, cql_str=None, cql_context=None, expand=None, start=0, limit=None, callback=None): params = {} if cql_str: params["cql"] = cql_str if cql_context: params["cqlcontext"] = json.dumps(cql_context) if expand: params["expand...
Fetch a list of content using the Confluence Query Language (CQL). See: Advanced searching using CQL (https://developer.atlassian.com/display/CONFDEV/Advanced+Searching+using+CQL) :param cql_str (string): OPTIONAL: A cql query string to use to locate content. :param cql_context (string): OPTIONA...
def get_content_children(self, content_id, expand=None, parent_version=None, callback=None): params = {} if expand: params["expand"] = expand if parent_version: params["parentVersion"] = parent_version return self._service_get_request("rest/api/content/{i...
Returns a map of the direct children of a piece of Content. Content can have multiple types of children - for example a Page can have children that are also Pages, but it can also have Comments and Attachments. The {@link ContentType}(s) of the children returned is specified by the "expand" query param...
def get_content_descendants(self, content_id, expand=None, callback=None): params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}/descendant".format(id=content_id), params=params, call...
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants - for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments. The {@link ContentType}(s) of the descendants returned is specified by the "expand" query ...
def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None, callback=None): params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) ...
Returns the direct descendants of a piece of Content, limited to a single descendant type. The {@link ContentType}(s) of the descendants returned is specified by the "type" path parameter in the request. Currently the only supported descendants are comment descendants of non-comment Content. :...
def get_content_labels(self, content_id, prefix=None, start=None, limit=None, callback=None): params = {} if prefix: params["prefix"] = prefix if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit...
Returns the list of labels on a piece of Content. :param content_id (string): A string containing the id of the labels content container. :param prefix (string): OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}. Default: None. :param start (int...
def get_content_comments(self, content_id, expand=None, parent_version=None, start=None, limit=None, location=None, depth=None, callback=None): params = {} if expand: params["expand"] = expand if parent_version: params["parentVersion"...
Returns the comments associated with a piece of content. :param content_id (string): A string containing the id of the content to retrieve children for. :param expand (string): OPTIONAL: a comma separated list of properties to expand on the children. We can also specify s...
def get_content_attachments(self, content_id, expand=None, start=None, limit=None, filename=None, media_type=None, callback=None): params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) ...
Returns a paginated list of attachment Content entities within a single container. :param content_id (string): A string containing the id of the attachments content container. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the Attachments returned. ...
def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None): params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(l...
Returns a paginated list of content properties. Content properties are a key / value store of properties attached to a piece of Content. The key is a string, and the value is a JSON-serializable object. :param content_id (string): A string containing the id of the property content container. ...
def get_content_property_by_key(self, content_id, property_key, expand=None, callback=None): params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}/property/{key}".format(id=content_id, key=property_key), ...
Returns a content property. :param content_id (string): A string containing the id of the property content container. :param property_key (string): The key associated with the property requested. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the content prop...
def get_op_restrictions_by_content_operation(self, content_id, operation_key, expand=None, start=None, limit=None, callback=None): params = {} if expand: params["expand"] = expand if start is not None: params["star...
Returns info about all restrictions of given operation. :param content_id (string): The content ID to query on. :param operation_key (string): The operation key to query on. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the content properties. ...
def get_long_tasks(self, expand=None, start=None, limit=None, callback=None): params = {} if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not None: params["limit"] = int(limit) return...
Returns information about all tracked long-running tasks. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the tasks. :param start (int): OPTIONAL: The pagination start count. :param limit (int): OPTIONAL: The pagination return count limit. :param callb...
def get_long_task_info(self, long_task_id, expand=None, callback=None): params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/longtask/{id}".format(id=long_task_id), params=params, callback=callba...
Returns information about a long-running task. :param long_task_id (string): The key of the task to be returned. :param expand (string): A comma separated list of properties to expand on the task. Default: Empty :param callback: OPTIONAL: The callback to execute on the resulting data, before the...
def get_spaces(self, space_key=None, expand=None, start=None, limit=None, callback=None): params = {} if space_key: params["spaceKey"] = space_key if expand: params["expand"] = expand if start is not None: params["start"] = int(start) ...
Returns information about the spaces present in the Confluence instance. :param space_key (string): OPTIONAL: A list of space keys to filter on. Default: None. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the spaces. Default: Empty ...
def get_space_information(self, space_key, expand=None, callback=None): params = {} if expand: params["expand"] = expand return self._service_get_request("rest/api/space/{key}".format(key=space_key), params=params, callback=callback)
Returns information about a space. :param space_key (string): A string containing the key of the space. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the space. Default: Empty. :param callback: OPTIONAL: The callback to execute on the resulting data, before ...
def get_space_content(self, space_key, depth=None, expand=None, start=None, limit=None, callback=None): params = {} if depth: assert depth in {"all", "root"} params["depth"] = depth if expand: params["expand"] = expand if start is not None: ...
Returns the content in this given space. :param space_key (string): A string containing the key of the space. :param depth (string): OPTIONAL: A string indicating if all content, or just the root content of the space is returned. Default: "all". Valid values: "all", "root"...
def get_space_content_by_type(self, space_key, content_type, depth=None, expand=None, start=None, limit=None, callback=None): assert content_type in ["page", "blogpost"] params = {} if depth: assert depth in {"all", "root"} param...
Returns the content in this given space with the given type. :param space_key (string): A string containing the key of the space. :param content_type (string): The type of content to return with the space. Valid values: "page", "blogpost". :param depth (string): OPTIONAL: A string indicating if ...
def create_new_content(self, content_data, callback=None): assert isinstance(content_data, dict) and set(content_data.keys()) >= self.NEW_CONTENT_REQUIRED_KEYS return self._service_post_request("rest/api/content", data=json.dumps(content_data), headers=...
Creates a new piece of Content. :param content_data (dict): A dictionary representing the data for the new content. Must have keys: "type", "title", "space", "body". :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns. ...
def create_new_attachment_by_content_id(self, content_id, attachments, callback=None): if isinstance(attachments, list): assert all(isinstance(at, dict) and "file" in list(at.keys()) for at in attachments) elif isinstance(attachments, dict): assert "file" in list(attachm...
Add one or more attachments to a Confluence Content entity, with optional comments. Comments are optional, but if included there must be as many comments as there are files, and the comments must be in the same order as the files. :param content_id (string): A string containing the id of the at...
def create_new_label_by_content_id(self, content_id, label_names, callback=None): assert isinstance(label_names, list) assert all(isinstance(ln, dict) and set(ln.keys()) == {"prefix", "name"} for ln in label_names) return self._service_post_request("rest/api/content/{id}/label".format(i...
Adds a list of labels to the specified content. :param content_id (string): A string containing the id of the labels content container. :param label_names (list): A list of labels (strings) to apply to the content. :param callback: OPTIONAL: The callback to execute on the resulting data, before ...
def create_new_content_property(self, content_id, content_property, callback=None): assert isinstance(content_property, dict) assert {"key", "value"} <= set(content_property.keys()) return self._service_post_request("rest/api/content/{id}/property".format(id=content_id), ...
Creates a new content property. Potentially a duplicate at the REST API level of create_new_property. :param content_id (string): A string containing the id of the property content container. :param new_property_data (dict): A dictionary describing the new property for the content. Must have the...
def create_new_space(self, space_definition, callback=None): assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_post_request("rest/api/space", data=json.dumps(space_definition), ...
Creates a new Space. The incoming Space does not include an id, but must include a Key and Name, and should include a Description. :param space_definition (dict): The dictionary describing the new space. Must include keys "key", "name", and "description". ...
def update_content_by_id(self, content_data, content_id, callback=None): assert isinstance(content_data, dict) and set(content_data.keys()) >= self.UPDATE_CONTENT_REQUIRED_KEYS return self._service_put_request("rest/api/content/{id}".format(id=content_id), data=json.dumps(content_data), ...
Updates a piece of Content, or restores if it is trashed. The body contains the representation of the content. Must include the new version number. To restore a piece of content that has the status of trashed the content must have it's version incremented, and status set to current. No other f...
def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None): assert isinstance(new_metadata, dict) and set(new_metadata.keys()) >= self.ATTACHMENT_METADATA_KEYS return self._service_put_request("rest/api/content/{id}/child/attachment/{attachment_id}" ...
Update the non-binary data of an Attachment. This resource can be used to update an attachment's filename, media-type, comment, and parent container. :param content_id (string): A string containing the ID of the attachments content container. :param attachment_id (string): The ID of the attachm...
def update_attachment(self, content_id, attachment_id, attachment, callback=None): if isinstance(attachment, dict): assert "file" in list(attachment.keys()) else: assert False return self._service_post_request("rest/api/content/{content_id}/child/attachment/{atta...
Update the binary data of an Attachment, and optionally the comment and the minor edit field. This adds a new version of the attachment, containing the new binary data, filename, and content-type. When updating the binary data of an attachment, the comment related to it together with the field that ...
def update_property(self, content_id, property_key, new_property_data, callback=None): assert isinstance(new_property_data, dict) and {"key", "value", "version"} <= set(new_property_data.keys()) return self._service_put_request("rest/api/content/{id}/property/{key}".format(id=content_id, key=pr...
Updates a content property. The body contains the representation of the content property. Must include the property id, and the new version number. Attempts to create a new content property if the given version number is 1, just like {@link #create(com.atlassian.confluence.api.model.content.id....
def update_space(self, space_key, space_definition, callback=None): assert isinstance(space_definition, dict) and {"key", "name", "description"} <= set(space_definition.keys()) return self._service_put_request("rest/api/space/{key}".format(key=space_key), ...
Updates a Space. Currently only the Space name, description and homepage can be updated. :param space_key (string): The key of the space to update. :param space_definition (dict): The dictionary describing the updated space metadata. This should include "...
def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None): assert {old_representation, new_representation} < {"storage", "editor", "view", "export_view"} # TODO: Enforce conversion rules better here. request_data = {"value": str(conte...
Converts between content body representations. Not all representations can be converted to/from other formats. Supported conversions: Source Representation | Destination Representation Supported -------------------------------------------------------------- "storage" | ...
def delete_content_by_id(self, content_id, status=None, callback=None): params = {} if status: params["status"] = status return self._service_delete_request("rest/api/content/{id}".format(id=content_id), params=params, callback=cal...
Trashes or purges a piece of Content, based on its {@link ContentType} and {@link ContentStatus}. :param content_id (string): The ID for the content to remove. :param status (string): OPTIONAL: A status code to query for the location (?) of the content. The REST API sugge...
def delete_label_by_id(self, content_id, label_name, callback=None): params = {"name": label_name} return self._service_delete_request("rest/api/content/{id}/label".format(id=content_id), params=params, callback=callback)
Deletes a labels to the specified content. There is an alternative form of this delete method that is not implemented. A DELETE request to /rest/api/content/{id}/label/{label} will also delete a label, but is more limited in the label name that can be accepted (and has no real apparent upside)....
def delete_property(self, content_id, property_key, callback=None): return self._service_delete_request("rest/api/content/{id}/property/{key}" "".format(id=content_id, key=property_key), callback=callback)
Deletes a content property. :param content_id (string): The ID for the content that owns the property to be deleted. :param property_key (string): The name of the property to be deleted. :param callback: OPTIONAL: The callback to execute on the resulting data, before the method returns. ...
def delete_space(self, space_key, callback=None): return self._service_delete_request("rest/api/space/{key}".format(key=space_key), callback=callback)
Deletes a Space. The space is deleted in a long running task, so the space cannot be considered deleted when this method returns. Clients can follow the status link in the response and poll it until the task completes. :param space_key (string): The key of the space to delete. :param c...
def add(self, sensor): if isinstance(sensor, (list, tuple)): for sss in sensor: self.add(sss) return if not isinstance(sensor, Sensor): raise TypeError("pysma.Sensor expected") if sensor.name in self: old = self[sensor.na...
Add a sensor, warning if it exists.
def _fetch_json(self, url, payload): params = { 'data': json.dumps(payload), 'headers': {'content-type': 'application/json'}, 'params': {'sid': self.sma_sid} if self.sma_sid else None, } for _ in range(3): try: with async_t...
Fetch json data for requests.
def new_session(self): body = yield from self._fetch_json(URL_LOGIN, self._new_session_data) self.sma_sid = jmespath.search('result.sid', body) if self.sma_sid: return True msg = 'Could not start session, %s, got {}'.format(body) if body.get('err'): ...
Establish a new session.
def read(self, sensors): payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))} if self.sma_sid is None: yield from self.new_session() if self.sma_sid is None: return False body = yield from self._fetch_json(URL_VALUES, payload=pay...
Read a set of keys.
def run(self): loop = GLib.MainLoop() context = loop.get_context() while True: time.sleep(0.1) if context.pending(): context.iteration() self._manager[ATTR_POSITION] = self._position() try: method, args ...
Run the process. Iterate the GLib main loop and process the task queue.
def media(self, uri): try: local_path, _ = urllib.request.urlretrieve(uri) metadata = mutagen.File(local_path, easy=True) if metadata.tags: self._tags = metadata.tags title = self._tags.get(TAG_TITLE, []) self._manager[ATTR_TIT...
Play a media file.
def play(self): if self.state == STATE_PAUSED: self._player.set_state(Gst.State.PLAYING) self.state = STATE_PLAYING
Change state to playing.
def pause(self): if self.state == STATE_PLAYING: self._player.set_state(Gst.State.PAUSED) self.state = STATE_PAUSED
Change state to paused.
def stop(self): urllib.request.urlcleanup() self._player.set_state(Gst.State.NULL) self.state = STATE_IDLE self._tags = {}
Stop pipeline.
def set_position(self, position): if position > self._duration(): return position_ns = position * _NANOSEC_MULT self._manager[ATTR_POSITION] = position self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns)
Set media position.
def set_volume(self, volume): self._player.set_property(PROP_VOLUME, volume) self._manager[ATTR_VOLUME] = volume _LOGGER.info('volume set to %.2f', volume)
Set volume.
def state(self, state): self._state = state self._manager[ATTR_STATE] = state _LOGGER.info('state changed to %s', state)
Set state.
def _duration(self): duration = 0 if self.state != STATE_IDLE: resp = self._player.query_duration(_FORMAT_TIME) duration = resp[1] // _NANOSEC_MULT return duration
Get media duration.
def _position(self): position = 0 if self.state != STATE_IDLE: resp = self._player.query_position(_FORMAT_TIME) position = resp[1] // _NANOSEC_MULT return position
Get media position.
def _on_message(self, bus, message): # pylint: disable=unused-argument if message.type == Gst.MessageType.EOS: self.stop() elif message.type == Gst.MessageType.ERROR: self.stop() err, _ = message.parse_error() _LOGGER.error('%s', err)
When a message is received from Gstreamer.
def get_previous_node(node): if node.prev_sibling: return node.prev_sibling if node.parent: return get_previous_node(node.parent)
Return the node before this node.
def casperjs_command_kwargs(): kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'universal_newlines': True } phantom_js_cmd = app_settings['PHANTOMJS_CMD'] if phantom_js_cmd: path = '{0}:{1}'.format( os.getenv('PATH', ''), os.path.dirname(...
will construct kwargs for cmd
def casperjs_command(): method = app_settings['CAPTURE_METHOD'] cmd = app_settings['%s_CMD' % method.upper()] sys_path = os.getenv('PATH', '').split(':') if cmd is None: for binpath in sys_path: cmd = os.path.join(binpath, method) if os.path.exists(cmd): ...
Determine which capture engine is specified. Possible options: - casperjs - phantomjs Based on this value, locate the binary of the capture engine. If setting <engine>_CMD is not defined, then look up for ``<engine>`` in shell PATH and build the whole capture command.
def casperjs_capture(stream, url, method=None, width=None, height=None, selector=None, data=None, waitfor=None, size=None, crop=None, render='png', wait=None): if isinstance(stream, six.string_types): output = stream else: with NamedTemporaryFile('w...
Captures web pages using ``casperjs``
def process_casperjs_stdout(stdout): for line in stdout.splitlines(): bits = line.split(':', 1) if len(bits) < 2: bits = ('INFO', bits) level, msg = bits if level == 'FATAL': logger.fatal(msg) raise CaptureError(msg) elif level == 'ER...
Parse and digest capture script output.
def parse_url(request, url): try: validate = URLValidator() validate(url) except ValidationError: if url.startswith('/'): host = request.get_host() scheme = 'https' if request.is_secure() else 'http' url = '{scheme}://{host}{uri}'.format(scheme=sc...
Parse url URL parameter.
def parse_render(render): formats = { 'jpeg': guess_all_extensions('image/jpeg'), 'png': guess_all_extensions('image/png'), 'gif': guess_all_extensions('image/gif'), 'bmp': guess_all_extensions('image/x-ms-bmp'), 'tiff': guess_all_extensions('image/tiff'), 'xbm':...
Parse render URL parameter. >>> parse_render(None) 'png' >>> parse_render('html') 'png' >>> parse_render('png') 'png' >>> parse_render('jpg') 'jpeg' >>> parse_render('gif') 'gif'
def parse_size(size_raw): try: width_str, height_str = size_raw.lower().split('x') except AttributeError: size = None except ValueError: size = None else: try: width = int(width_str) assert width > 0 except (ValueError, AssertionError)...
Parse size URL parameter. >>> parse_size((100,None)) None >>> parse_size('300x100') (300, 100) >>> parse_size('300x') None >>> parse_size('x100') None >>> parse_size('x') None
def image_postprocess(imagefile, output, size, crop, render): try: from PIL import Image except ImportError: import Image img = Image.open(imagefile) size_crop = None img_resized = img if size and crop and crop.lower() == 'true': width_raw, height_raw = img.size ...
Resize and crop captured image, and saves to output. (can be stream or filename)
def build_absolute_uri(request, url): if app_settings.get('CAPTURE_ROOT_URL'): return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url) return request.build_absolute_uri(url)
Allow to override printing url, not necessarily on the same server instance.
def render_template(template_name, context, format='png', output=None, using=None, **options): # output stream, as required by casperjs_capture stream = BytesIO() out_f = None # the suffix=.html is a hack for phantomjs which *will* # complain about not being able to open sou...
Render a template from django project, and return the file object of the result.
def go(fn, *args, **kwargs): if not callable(fn): raise TypeError('go() requires a function, not %r' % (fn,)) result = [None] error = [] def target(): try: result[0] = fn(*args, **kwargs) except Exception: # Are we in interpreter shutdown? ...
Launch an operation on a thread and get a handle to its future result. >>> from time import sleep >>> def print_sleep_print(duration): ... sleep(duration) ... print('hello from background thread') ... sleep(duration) ... print('goodbye from background thread') ... return...
def going(fn, *args, **kwargs): future = go(fn, *args, **kwargs) try: yield future except: # We are raising an exception, just try to clean up the future. exc_info = sys.exc_info() try: # Shorter than normal timeout. future(timeout=1) exce...
Launch a thread and wait for its result before exiting the code block. >>> with going(lambda: 'return value') as future: ... pass >>> future() # Won't block, the future is ready by now. 'return value' Or discard the result: >>> with going(lambda: "don't care"): ... pass If an...
def wait_until(predicate, success_description, timeout=10): start = time.time() while True: retval = predicate() if retval: return retval if time.time() - start > timeout: raise AssertionError("Didn't ever %s" % success_description) time.sleep(0.1)
Wait up to 10 seconds (by default) for predicate to be true. E.g.: wait_until(lambda: client.primary == ('a', 1), 'connect to the primary') If the lambda-expression isn't true after 10 seconds, we raise AssertionError("Didn't ever connect to the primary"). Returns the pred...
def _get_c_string(data, position): end = data.index(b"\x00", position) return _utf_8_decode(data[position:end], None, True)[0], end + 1
Decode a BSON 'C' string to python unicode string.
def _synchronized(meth): @functools.wraps(meth) def wrapper(self, *args, **kwargs): with self._lock: return meth(self, *args, **kwargs) return wrapper
Call method while holding a lock.
def bind_tcp_socket(address): host, port = address for res in set(socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)): family, socktype, proto, _, sock_addr = res sock = socket...
Takes (host, port) and returns (socket_object, (host, port)). If the passed-in port is None, bind an unused port and return it.
def bind_domain_socket(address): path, _ = address try: os.unlink(path) except OSError: pass sock = socket.socket(socket.AF_UNIX) sock.bind(path) sock.listen(128) return sock, (path, 0)
Takes (socket path, 0) and returns (socket_object, (path, 0)).
def mock_server_receive_request(client, server): header = mock_server_receive(client, 16) length = _UNPACK_INT(header[:4])[0] request_id = _UNPACK_INT(header[4:8])[0] opcode = _UNPACK_INT(header[12:])[0] msg_bytes = mock_server_receive(client, length - 16) if opcode not in OPCODES: ...
Take a client socket and return a Request.
def mock_server_receive(sock, length): msg = b'' while length: chunk = sock.recv(length) if chunk == b'': raise socket.error(errno.ECONNRESET, 'closed') length -= len(chunk) msg += chunk return msg
Receive `length` bytes from a socket object.
def make_docs(*args, **kwargs): err_msg = "Can't interpret args: " if not args and not kwargs: return [] if not args: # OpReply(ok=1, ismaster=True). return [kwargs] if isinstance(args[0], (int, float, bool)): # server.receives().ok(0, err='uh oh'). if args...
Make the documents for a `Request` or `Reply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Request.replies`, and so on. See examples in tutorial.
def make_matcher(*args, **kwargs): if args and isinstance(args[0], Matcher): if args[1:] or kwargs: raise_args_err("can't interpret args") return args[0] return Matcher(*args, **kwargs)
Make a Matcher from a :ref:`message spec <message spec>`: >>> make_matcher() Matcher(Request()) >>> make_matcher({'ismaster': 1}, namespace='admin') Matcher(Request({"ismaster": 1}, namespace="admin")) >>> make_matcher({}, {'_id': 1}) Matcher(Request({}, {"_id": 1})) See more examples in t...
def make_prototype_request(*args, **kwargs): if args and inspect.isclass(args[0]) and issubclass(args[0], Request): request_cls, arg_list = args[0], args[1:] return request_cls(*arg_list, **kwargs) if args and isinstance(args[0], Request): if args[1:] or kwargs: raise_ar...
Make a prototype Request for a Matcher.
def docs_repr(*args): sio = StringIO() for doc_idx, doc in enumerate(args): if doc_idx > 0: sio.write(u', ') sio.write(text_type(json_util.dumps(doc))) return sio.getvalue()
Stringify ordered dicts like a regular ones. Preserve order, remove 'u'-prefix on unicodes in Python 2: >>> print(docs_repr(OrderedDict([(u'_id', 2)]))) {"_id": 2} >>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]), ... OrderedDict([(u'a', 1)]))) {"_id": 2, "a": "b"},...
def seq_match(seq0, seq1): len_seq1 = len(seq1) if len_seq1 < len(seq0): return False seq1_idx = 0 for i, elem in enumerate(seq0): while seq1_idx < len_seq1: if seq1[seq1_idx] == elem: break seq1_idx += 1 if seq1_idx >= len_seq1 or seq...
True if seq0 is a subset of seq1 and their elements are in same order. >>> seq_match([], []) True >>> seq_match([1], [1]) True >>> seq_match([1, 1], [1]) False >>> seq_match([1], [1, 2]) True >>> seq_match([1, 1], [1, 1]) True >>> seq_match([3], [1, 2, 3]) True >>> s...
def raise_args_err(message='bad arguments', error_class=TypeError): frame = inspect.currentframe().f_back raise error_class(message + ': ' + format_call(frame))
Throw an error with standard message, displaying function call. >>> def f(a, *args, **kwargs): ... raise_args_err() ... >>> f(1, 2, x='y') Traceback (most recent call last): ... TypeError: bad arguments: f(1, 2, x='y')
def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB', ssl=False, uds_path=None): if uds_path is not None: port = None server = MockupDB(port=port, verbose=verbose, request_timeout=int(1e6), ...
A `MockupDB` that the mongo shell can connect to. Call `~.MockupDB.run` on the returned server, and clean it up with `~.MockupDB.stop`. If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific responder.
def client_port(self): address = self._client.getpeername() if isinstance(address, tuple): return address[1] # Maybe a Unix domain socket connection. return 0
Client connection's TCP port.
def assert_matches(self, *args, **kwargs): matcher = make_matcher(*args, **kwargs) if not matcher.matches(self): raise AssertionError('%r does not match %r' % (self, matcher)) return self
Assert this matches a :ref:`message spec <message spec>`. Returns self.
def fail(self, err='MockupDB query failure', *args, **kwargs): kwargs.setdefault('flags', 0) kwargs['flags'] |= REPLY_FLAGS['QueryFailure'] kwargs['$err'] = err self.replies(*args, **kwargs) return True
Reply to a query with the QueryFailure flag and an '$err' key. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
def command_err(self, code=1, errmsg='MockupDB command failure', *args, **kwargs): kwargs.setdefault('ok', 0) kwargs['code'] = code kwargs['errmsg'] = errmsg self.replies(*args, **kwargs) return True
Error reply to a command. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
def hangup(self): if self._server: self._server._log('\t%d\thangup' % self.client_port) self._client.shutdown(socket.SHUT_RDWR) return True
Close the connection. Returns True so it is suitable as an `~MockupDB.autoresponds` handler.
def _matches_docs(self, docs, other_docs): for doc, other_doc in zip(docs, other_docs): if not self._match_map(doc, other_doc): return False return True
Overridable method.
def _replies(self, *args, **kwargs): reply_msg = make_reply(*args, **kwargs) if self._server: self._server._log('\t%d\t<-- %r' % (self.client_port, reply_msg)) reply_bytes = reply_msg.reply_bytes(self) self._client.sendall(reply_bytes)
Overridable method.
def unpack(cls, msg, client, server, request_id): payload_document = OrderedDict() flags, = _UNPACK_UINT(msg[:4]) pos = 4 if flags != 0 and flags != 2: raise ValueError('OP_MSG flag must be 0 or 2 not %r' % (flags,)) while pos < len(msg): payload...
Parse message and return an `OpMsg`. Takes the client message as bytes, the client and server socket objects, and the client request id.
def unpack(cls, msg, client, server, request_id): flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) is_command = namespace.endswith('.$cmd') num_to_skip, = _UNPACK_INT(msg[pos:pos + 4]) pos += 4 num_to_return, = _UNPACK_INT(msg[pos:pos + 4]) ...
Parse message and return an `OpQuery` or `Command`. Takes the client message as bytes, the client and server socket objects, and the client request id.
def unpack(cls, msg, client, server, request_id): flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) num_to_return, = _UNPACK_INT(msg[pos:pos + 4]) pos += 4 cursor_id, = _UNPACK_LONG(msg[pos:pos + 8]) return OpGetMore(namespace=namespace, flags=...
Parse message and return an `OpGetMore`. Takes the client message as bytes, the client and server socket objects, and the client request id.
def unpack(cls, msg, client, server, _): # Leading 4 bytes are reserved. num_of_cursor_ids, = _UNPACK_INT(msg[4:8]) cursor_ids = [] pos = 8 for _ in range(num_of_cursor_ids): cursor_ids.append(_UNPACK_INT(msg[pos:pos + 4])[0]) pos += 4 ret...
Parse message and return an `OpKillCursors`. Takes the client message as bytes, the client and server socket objects, and the client request id.
def unpack(cls, msg, client, server, request_id): flags, = _UNPACK_INT(msg[:4]) namespace, pos = _get_c_string(msg, 4) docs = bson.decode_all(msg[pos:], CODEC_OPTIONS) return cls(*docs, namespace=namespace, flags=flags, _client=client, request_id=request_id, _...
Parse message and return an `OpInsert`. Takes the client message as bytes, the client and server socket objects, and the client request id.
def reply_bytes(self, request): flags = struct.pack("<i", self._flags) cursor_id = struct.pack("<q", self._cursor_id) starting_from = struct.pack("<i", self._starting_from) number_returned = struct.pack("<i", len(self._docs)) reply_id = random.randint(0, 1000000) ...
Take a `Request` and return an OP_REPLY message as bytes.
def reply_bytes(self, request): flags = struct.pack("<I", self._flags) payload_type = struct.pack("<b", 0) payload_data = bson.BSON.encode(self.doc) data = b''.join([flags, payload_type, payload_data]) reply_id = random.randint(0, 1000000) response_to = request....
Take a `Request` and return an OP_MSG message as bytes.
def matches(self, *args, **kwargs): request = make_prototype_request(*args, **kwargs) if self._prototype.opcode not in (None, request.opcode): return False if self._prototype.is_command not in (None, request.is_command): return False for name in dir(self....
Test if a request matches a :ref:`message spec <message spec>`. Returns ``True`` or ``False``.
def run(self): self._listening_sock, self._address = ( bind_domain_socket(self._address) if self._uds_path else bind_tcp_socket(self._address)) if self._ssl: certfile = os.path.join(os.path.dirname(__file__), 'server.pem') self._liste...
Begin serving. Returns the bound port, or 0 for domain socket.
def stop(self): self._stopped = True threads = [self._accept_thread] threads.extend(self._server_threads) self._listening_sock.close() for sock in list(self._server_socks): try: sock.shutdown(socket.SHUT_RDWR) except socket.error: ...
Stop serving. Always call this to clean up after yourself.
def receives(self, *args, **kwargs): timeout = kwargs.pop('timeout', self._request_timeout) end = time.time() + timeout matcher = Matcher(*args, **kwargs) while not self._stopped: try: # Short timeout so we notice if the server is stopped. ...
Pop the next `Request` and assert it matches. Returns None if the server is stopped. Pass a `Request` or request pattern to specify what client request to expect. See the tutorial for examples. Pass ``timeout`` as a keyword argument to override this server's ``request_timeout``.
def got(self, *args, **kwargs): timeout = kwargs.pop('timeout', self._request_timeout) end = time.time() + timeout matcher = make_matcher(*args, **kwargs) while not self._stopped: try: # Short timeout so we notice if the server is stopped. ...
Does `.request` match the given :ref:`message spec <message spec>`? >>> s = MockupDB(auto_ismaster=True) >>> port = s.run() >>> s.got(timeout=0) # No request enqueued. False >>> from pymongo import MongoClient >>> client = MongoClient(s.uri) >>> future = go(clie...
def append_responder(self, matcher, *args, **kwargs): return self._insert_responder("bottom", matcher, *args, **kwargs)
Add a responder of last resort. Like `.autoresponds`, but instead of adding a responder to the top of the stack, add it to the bottom. This responder will be called if no others match.
def uri(self): if self._uds_path: uri = 'mongodb://%s' % (quote_plus(self._uds_path),) else: uri = 'mongodb://%s' % (format_addr(self._address),) return uri + '/?ssl=true' if self._ssl else uri
Connection string to pass to `~pymongo.mongo_client.MongoClient`.
def _accept_loop(self): self._listening_sock.setblocking(0) while not self._stopped and not _shutting_down: try: # Wait a short time to accept. if select.select([self._listening_sock.fileno()], [], [], 1): client, client_addr = sel...
Accept client connections and spawn a thread for each.