INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
List user group members.
def members(group_id): """List user group members.""" page = request.args.get('page', 1, type=int) per_page = request.args.get('per_page', 5, type=int) q = request.args.get('q', '') s = request.args.get('s', '') group = Group.query.get_or_404(group_id) if group.can_see_members(current_user)...
Leave group.
def leave(group_id): """Leave group.""" group = Group.query.get_or_404(group_id) if group.can_leave(current_user): try: group.remove_member(current_user) except Exception as e: flash(str(e), "error") return redirect(url_for('.index')) flash( ...
Approve a user.
def approve(group_id, user_id): """Approve a user.""" membership = Membership.query.get_or_404((user_id, group_id)) group = membership.group if group.can_edit(current_user): try: membership.accept() except Exception as e: flash(str(e), 'error') return...
Remove user from a group.
def remove(group_id, user_id): """Remove user from a group.""" group = Group.query.get_or_404(group_id) user = User.query.get_or_404(user_id) if group.can_edit(current_user): try: group.remove_member(user) except Exception as e: flash(str(e), "error") ...
Accpet pending invitation.
def accept(group_id): """Accpet pending invitation.""" membership = Membership.query.get_or_404((current_user.get_id(), group_id)) # no permission check, because they are checked during Memberships creating try: membership.accept() except Exception as e: flash(str(e), 'error') ...
Add ( invite ) new member.
def new_member(group_id): """Add (invite) new member.""" group = Group.query.get_or_404(group_id) if group.can_invite_others(current_user): form = NewMemberForm() if form.validate_on_submit(): emails = filter(None, form.data['emails'].splitlines()) group.invite_by_e...
Get an initial featuring of sphere positions in an image.
def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3), trim_edge=True, **kwargs): """ Get an initial featuring of sphere positions in an image. Parameters ----------- image : :class:`peri.util.Image` object Image object which defines the image file as we...
Completely optimizes a state from an image of roughly monodisperse particles.
def get_initial_featuring(statemaker, feature_rad, actual_rad=None, im_name=None, tile=None, invert=True, desc='', use_full_path=False, featuring_params={}, statemaker_kwargs={}, **kwargs): """ Completely optimizes a state from an image of roughly monodisperse particles. The user can in...
Gets a completely - optimized state from an image and an initial guess of particle positions and radii.
def feature_from_pos_rad(statemaker, pos, rad, im_name=None, tile=None, desc='', use_full_path=False, statemaker_kwargs={}, **kwargs): """ Gets a completely-optimized state from an image and an initial guess of particle positions and radii. The state is periodically saved during optimization, w...
Optimizes a state from an initial set of positions and radii without any known microscope parameters.
def optimize_from_initial(s, max_mem=1e9, invert='guess', desc='', rz_order=3, min_rad=None, max_rad=None): """ Optimizes a state from an initial set of positions and radii, without any known microscope parameters. Parameters ---------- s : :class:`peri.states.ImageState` ...
Translates one optimized state into another image where the particles have moved by a small amount ( ~1 particle radius ).
def translate_featuring(state_name=None, im_name=None, use_full_path=False, **kwargs): """ Translates one optimized state into another image where the particles have moved by a small amount (~1 particle radius). Returns a completely-optimized state. The user can interactively selects the in...
Combines centroid featuring with the globals from a previous state.
def get_particles_featuring(feature_rad, state_name=None, im_name=None, use_full_path=False, actual_rad=None, invert=True, featuring_params={}, **kwargs): """ Combines centroid featuring with the globals from a previous state. Runs trackpy.locate on an image, sets the globals from a previou...
If state_name or im_name is None picks them interactively through Tk and then sets with or without the full path.
def _pick_state_im_name(state_name, im_name, use_full_path=False): """ If state_name or im_name is None, picks them interactively through Tk, and then sets with or without the full path. Parameters ---------- state_name : {string, None} The name of the state. If None, selected t...
Workhorse for translating particles. See get_particles_featuring for docs.
def _translate_particles(s, max_mem=1e9, desc='', min_rad='calc', max_rad='calc', invert='guess', rz_order=0, do_polish=True): """ Workhorse for translating particles. See get_particles_featuring for docs. """ if desc is not None: desc_trans = desc + 'translate-particles' desc_bu...
Links the state st psf zscale with the global zscale
def link_zscale(st): """Links the state ``st`` psf zscale with the global zscale""" # FIXME should be made more generic to other parameters and categories psf = st.get('psf') psf.param_dict['zscale'] = psf.param_dict['psf-zscale'] psf.params[psf.params.index('psf-zscale')] = 'zscale' psf.global_...
Final optimization for the best - possible state.
def finish_state(st, desc='finish-state', invert='guess'): """ Final optimization for the best-possible state. Runs a local add-subtract to capture any difficult-to-feature particles, then does another set of optimization designed to get to the best possible fit. Parameters ---------- ...
Methods available are gn: Gauss - Newton with JTJ ( recommended ) nr: Newton - Rhaphson with hessian
def optimize_particle(state, index, method='gn', doradius=True): """ Methods available are gn : Gauss-Newton with JTJ (recommended) nr : Newton-Rhaphson with hessian if doradius, also optimize the radius. """ blocks = state.param_particle(index) if not doradius: blocks ...
Workhorse for creating & optimizing states with an initial centroid guess.
def makestate(im, pos, rad, slab=None, mem_level='hi'): """ Workhorse for creating & optimizing states with an initial centroid guess. This is an example function that works for a particular microscope. For your own microscope, you'll need to change particulars such as the psf type and the orde...
Calculates an ilm order based on the shape of an image. This is based on something that works for our particular images. Your mileage will vary.
def _calc_ilm_order(imshape): """ Calculates an ilm order based on the shape of an image. This is based on something that works for our particular images. Your mileage will vary. Parameters ---------- imshape : 3-element list-like The shape of the image. Returns -------...
Used to check if there is a dict in a dict
def _check_for_inception(self, root_dict): ''' Used to check if there is a dict in a dict ''' for key in root_dict: if isinstance(root_dict[key], dict): root_dict[key] = ResponseObject(root_dict[key]) return root_dict
Create random parameters for this ILM that mimic experiments as closely as possible without real assumptions.
def randomize_parameters(self, ptp=0.2, fourier=False, vmin=None, vmax=None): """ Create random parameters for this ILM that mimic experiments as closely as possible without real assumptions. """ if vmin is not None and vmax is not None: ptp = vmax - vmin elif...
Creates a barnes interpolant & calculates its values
def _barnes(self, pos): """Creates a barnes interpolant & calculates its values""" b_in = self.b_in dist = lambda x: np.sqrt(np.dot(x,x)) #we take a filter size as the max distance between the grids along #x or y: sz = self.npts[1] coeffs = self.get_values(self.ba...
Returns details of the posting schedules associated with a social media profile.
def schedules(self): ''' Returns details of the posting schedules associated with a social media profile. ''' url = PATHS['GET_SCHEDULES'] % self.id self.__schedules = self.api.get(url=url) return self.__schedules
Set the posting schedules for the specified social media profile.
def schedules(self, schedules): ''' Set the posting schedules for the specified social media profile. ''' url = PATHS['UPDATE_SCHEDULES'] % self.id data_format = "schedules[0][%s][]=%s&" post_data = "" for format_type, values in schedules.iteritems(): for value in values: ...
Calculates the moments of the probability distribution p with vector v
def moment(p, v, order=1): """ Calculates the moments of the probability distribution p with vector v """ if order == 1: return (v*p).sum() elif order == 2: return np.sqrt( ((v**2)*p).sum() - (v*p).sum()**2 )
Calculates the 3D psf at a particular z pixel height
def psf_slice(self, zint, size=11, zoffset=0., getextent=False): """ Calculates the 3D psf at a particular z pixel height Parameters ---------- zint : float z pixel height in image coordinates , converted to 1/k by the function using the slab position as ...
Convert from pixel to 1/ k_incoming ( laser_wavelength/ ( 2 \ pi )) units
def _p2k(self, v): """ Convert from pixel to 1/k_incoming (laser_wavelength/(2\pi)) units """ return 2*np.pi*self.pxsize*v/self.param_dict['psf-laser-wavelength']
Transform z to real - space coordinates from tile coordinates
def _tz(self, z): """ Transform z to real-space coordinates from tile coordinates """ return (z-self.param_dict['psf-zslab'])*self.param_dict[self.zscale]
Returns the size of the psf in each direction a particular z ( px )
def measure_size_drift(self, z, size=31, zoffset=0.): """ Returns the 'size' of the psf in each direction a particular z (px) """ drift = 0.0 for i in range(self.measurement_iterations): psf, vec = self.psf_slice(z, size=size, zoffset=zoffset+drift) psf = psf / psf.sum() ...
Get support size and drift polynomial for current set of params
def characterize_psf(self): """ Get support size and drift polynomial for current set of params """ # there may be an issue with the support and characterization-- # it might be best to do the characterization with the same support # as the calculated psf. l,u = max(self.zrange[0...
fftshift and pad the field with zeros until it has size finalshape. if zpad is off then no padding is put on the z direction. returns the fourier transform of the field
def _kpad(self, field, finalshape, zpad=False, norm=True): """ fftshift and pad the field with zeros until it has size finalshape. if zpad is off, then no padding is put on the z direction. returns the fourier transform of the field """ currshape = np.array(field.shape) ...
Pack the parameters into the form necessary for the integration routines above. For example packs for calculate_linescan_psf
def pack_args(self): """ Pack the parameters into the form necessary for the integration routines above. For example, packs for calculate_linescan_psf """ mapper = { 'psf-kfki': 'kfki', 'psf-alpha': 'alpha', 'psf-n2n1': 'n2n1', 'ps...
Calculates a linescan psf
def psffunc(self, *args, **kwargs): """Calculates a linescan psf""" if self.polychromatic: func = psfcalc.calculate_polychrome_linescan_psf else: func = psfcalc.calculate_linescan_psf return func(*args, **kwargs)
Calculates a pinhole psf
def psffunc(self, x, y, z, **kwargs): """Calculates a pinhole psf""" #do_pinhole?? FIXME if self.polychromatic: func = psfcalc.calculate_polychrome_pinhole_psf else: func = psfcalc.calculate_pinhole_psf x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]] ...
Get support size and drift polynomial for current set of params
def characterize_psf(self): """ Get support size and drift polynomial for current set of params """ l,u = max(self.zrange[0], self.param_dict['psf-zslab']), self.zrange[1] size_l, drift_l = self.measure_size_drift(l, size=self.support) size_u, drift_u = self.measure_size_drift(u, size=s...
Make request and convert JSON response to python objects
def _req(self, url, method='GET', **kw): '''Make request and convert JSON response to python objects''' send = requests.post if method == 'POST' else requests.get try: r = send( url, headers=self._token_header(), timeout=self.settings['...
Returns all active bets
def get_active_bets(self, project_id=None): '''Returns all active bets''' url = urljoin( self.settings['bets_url'], 'bets?state=fresh,active,accept_end&page=1&page_size=100') if project_id is not None: url += '&kava_project_id={}'.format(project_id) ...
Return bets with given filters and ordering.
def get_bets(self, type=None, order_by=None, state=None, project_id=None, page=None, page_size=None): """Return bets with given filters and ordering. :param type: return bets only with this type. Use None to include all (default). :param order_by: '-last_st...
Return slug of a project that given bet is associated with or None if bet is not associated with any project.
def get_project_slug(self, bet): '''Return slug of a project that given bet is associated with or None if bet is not associated with any project. ''' if bet.get('form_params'): params = json.loads(bet['form_params']) return params.get('project') return Non...
Subscribe to event for given bet ids.
def subscribe(self, event, bet_ids): '''Subscribe to event for given bet ids.''' if not self._subscriptions.get(event): self._subscriptions[event] = set() self._subscriptions[event] = self._subscriptions[event].union(bet_ids)
Opens local preview of your blog website
def preview(context): """Opens local preview of your blog website""" config = context.obj pelican(config, '--verbose', '--ignore-cache') server_proc = None os.chdir(config['OUTPUT_DIR']) try: try: command = 'python -m http.server ' + str(PORT) server_proc = run...
Get the relative path to the API resource collection
def get_collection_endpoint(cls): """ Get the relative path to the API resource collection If self.collection_endpoint is not set, it will default to the lowercase name of the resource class plus an "s" and the terminating "/" :param cls: Resource class :return: Relative path to...
Make the actual request to the API: param url: URL: param http_method: The method used to make the request to the API: param client_args: Arguments to be sent to the auth client: return: requests response object
def send(self, url, http_method, **client_args): """ Make the actual request to the API :param url: URL :param http_method: The method used to make the request to the API :param client_args: Arguments to be sent to the auth client :return: requests' response object ...
Get one single resource from the API: param resource_id: Id of the resource to be retrieved: return: Retrieved resource
def get(self, resource_id): """ Get one single resource from the API :param resource_id: Id of the resource to be retrieved :return: Retrieved resource """ response = self.send(self.get_resource_endpoint(resource_id), "get") try: resource = self.resou...
Get a filtered list of resources: param search_args: To be translated into ?arg1 = value1&arg2 = value2...: return: A list of resources
def filter(self, **search_args): """ Get a filtered list of resources :param search_args: To be translated into ?arg1=value1&arg2=value2... :return: A list of resources """ search_args = search_args or {} raw_resources = [] for url, paginator_params in se...
Create a resource on the server: params kwargs: Attributes ( field names and values ) of the new resource
def create(self, **kwargs): """ Create a resource on the server :params kwargs: Attributes (field names and values) of the new resource """ resource = self.resource_class(self.client) resource.update_from_dict(kwargs) resource.save(force_create=True) retu...
Subclasses must implement this method that will be used to send API requests with proper auth: param relative_path: URL path relative to self. base_url: param http_method: HTTP method: param requests_args: kargs to be sent to requests: return:
def send(self, relative_path, http_method, **requests_args): """ Subclasses must implement this method, that will be used to send API requests with proper auth :param relative_path: URL path relative to self.base_url :param http_method: HTTP method :param requests_args: kargs to ...
Get response data or throw an appropiate exception: param response: requests response object: param parse_json: if True response will be parsed as JSON: return: response data either as json or as a regular response. content object
def get_response_data(self, response, parse_json=True): """ Get response data or throw an appropiate exception :param response: requests response object :param parse_json: if True, response will be parsed as JSON :return: response data, either as json or as a regular response.con...
Make a unauthorized request: param relative_path: URL path relative to self. base_url: param http_method: HTTP method: param requests_args: kargs to be sent to requests: return: requests response object
def send(self, relative_path, http_method, **requests_args): """ Make a unauthorized request :param relative_path: URL path relative to self.base_url :param http_method: HTTP method :param requests_args: kargs to be sent to requests :return: requests' response object ...
Starts a new article
def write(context): """Starts a new article""" config = context.obj title = click.prompt('Title') author = click.prompt('Author', default=config.get('DEFAULT_AUTHOR')) slug = slugify(title) creation_date = datetime.now() basename = '{:%Y-%m-%d}_{}.md'.format(creation_date, slug) meta ...
Looks for errors in source code of your blog
def lint(context): """Looks for errors in source code of your blog""" config = context.obj try: run('flake8 {dir} --exclude={exclude}'.format( dir=config['CWD'], exclude=','.join(EXCLUDE), )) except SubprocessError: context.exit(1)
value_class is initially a string with the import path to the resource class but we need to get the actual class before doing any work
def set_real_value_class(self): """ value_class is initially a string with the import path to the resource class, but we need to get the actual class before doing any work We do not expect the actual clas to be in value_class since the beginning to avoid nasty import egg-before-chicken errors ...
Saves changes and sends them to GitHub
def publish(context): """Saves changes and sends them to GitHub""" header('Recording changes...') run('git add -A') header('Displaying changes...') run('git -c color.status=always status') if not click.confirm('\nContinue publishing'): run('git reset HEAD --') abort(context) ...
Uploads new version of the blog website
def deploy(context): """Uploads new version of the blog website""" config = context.obj header('Generating HTML...') pelican(config, '--verbose', production=True) header('Removing unnecessary output...') unnecessary_paths = [ 'author', 'category', 'tag', 'feeds', 'tags.html', ...
Return the given number as a string with a sign in front of it ie. + if the number is positive - otherwise.
def signed_number(number, precision=2): """ Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise. """ prefix = '' if number <= 0 else '+' number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision) return number_str
Show Zebra balance.
def balance(ctx): """ Show Zebra balance. Like the hours balance, vacation left, etc. """ backend = plugins_registry.get_backends_by_class(ZebraBackend)[0] timesheet_collection = get_timesheet_collection_for_context(ctx, None) hours_to_be_pushed = timesheet_collection.get_hours(pushed=Fals...
Transforms the given params dict to values that are understood by Zebra ( eg. False is represented as false )
def to_zebra_params(params): """ Transforms the given `params` dict to values that are understood by Zebra (eg. False is represented as 'false') """ def to_zebra_value(value): transform_funcs = { bool: lambda v: 'true' if v else 'false', } return transform_funcs.get(...
Show all messages in the messages key of the given dict.
def show_response_messages(response_json): """ Show all messages in the `messages` key of the given dict. """ message_type_kwargs = { 'warning': {'fg': 'yellow'}, 'error': {'fg': 'red'}, } for message in response_json.get('messages', []): click.secho(message['text'], **me...
Override alias mapping in the user configuration file with the given new_mapping which should be a tuple with 2 or 3 elements ( in the form ( project_id activity_id role_id ) ).
def update_alias_mapping(settings, alias, new_mapping): """ Override `alias` mapping in the user configuration file with the given `new_mapping`, which should be a tuple with 2 or 3 elements (in the form `(project_id, activity_id, role_id)`). """ mapping = aliases_database[alias] new_mapping = M...
Adds images to the last article
def photos(context, path): """Adds images to the last article""" config = context.obj header('Looking for the latest article...') article_filename = find_last_article(config['CONTENT_DIR']) if not article_filename: return click.secho('No articles.', fg='red') click.echo(os.path.basenam...
Generates the circle.
def _generate_circle(self): """Generates the circle. """ total_weight = 0 for node in self.nodes: total_weight += self.weights.get(node, 1) for node in self.nodes: weight = 1 if node in self.weights: weight = self.weights.get(...
Given a string key a corresponding node in the hash ring is returned.
def get_node(self, string_key): """Given a string key a corresponding node in the hash ring is returned. If the hash ring is empty, `None` is returned. """ pos = self.get_node_pos(string_key) if pos is None: return None return self.ring[self._sorted_keys[pos]...
Given a string key a corresponding node in the hash ring is returned along with it s position in the ring.
def get_node_pos(self, string_key): """Given a string key a corresponding node in the hash ring is returned along with it's position in the ring. If the hash ring is empty, (`None`, `None`) is returned. """ if not self.ring: return None key = self.gen_key(st...
Given a string key it returns the nodes as a generator that can hold the key.
def iterate_nodes(self, string_key, distinct=True): """Given a string key it returns the nodes as a generator that can hold the key. The generator iterates one time through the ring starting at the correct position. if `distinct` is set, then the nodes returned will be unique, ...
Given a string key it returns a long value this long value represents a place on the hash ring.
def gen_key(self, key): """Given a string key it returns a long value, this long value represents a place on the hash ring. md5 is currently used because it mixes well. """ b_key = self._hash_digest(key) return self._hash_val(b_key, lambda x: x)
Get the number of ports for the given app JSON. This roughly follows the logic in marathon - lb for finding app IPs/ ports although we are only interested in the quantity of ports an app should have and don t consider the specific IPs/ ports of individual tasks: https:// github. com/ mesosphere/ marathon - lb/ blob/ v1...
def get_number_of_app_ports(app): """ Get the number of ports for the given app JSON. This roughly follows the logic in marathon-lb for finding app IPs/ports, although we are only interested in the quantity of ports an app should have and don't consider the specific IPs/ports of individual tasks: ...
Get the Marathon networking mode for the app.
def _get_networking_mode(app): """ Get the Marathon networking mode for the app. """ # Marathon 1.5+: there is a `networks` field networks = app.get('networks') if networks: # Modes cannot be mixed, so assigning the last mode is fine return networks[-1].get('mode', 'container') ...
Get the portMappings field for the app container.
def _get_container_port_mappings(app): """ Get the ``portMappings`` field for the app container. """ container = app['container'] # Marathon 1.5+: container.portMappings field port_mappings = container.get('portMappings') # Older Marathon: container.docker.portMappings field if port_ma...
Given a list of pem objects sort the objects into the private key leaf certificate and list of CA certificates in the trust chain. This function assumes that the list of pem objects will contain exactly one private key and exactly one leaf certificate and that only key and certificate type objects are provided.
def sort_pem_objects(pem_objects): """ Given a list of pem objects, sort the objects into the private key, leaf certificate, and list of CA certificates in the trust chain. This function assumes that the list of pem objects will contain exactly one private key and exactly one leaf certificate and th...
Given a non - None response from the Vault key/ value store convert the key/ values into a list of PEM objects.
def _cert_data_to_pem_objects(cert_data): """ Given a non-None response from the Vault key/value store, convert the key/values into a list of PEM objects. """ pem_objects = [] for key in ['privkey', 'cert', 'chain']: pem_objects.extend(pem.parse(cert_data[key].encode('utf-8'))) retu...
Raises a requests. exceptions. HTTPError if the response has a non - 200 status code.
def raise_for_not_ok_status(response): """ Raises a `requests.exceptions.HTTPError` if the response has a non-200 status code. """ if response.code != OK: raise HTTPError('Non-200 response code (%s) for url: %s' % ( response.code, uridecode(response.request.absoluteURI))) re...
Sometimes we need the protocol object so that we can manipulate the underlying transport in tests.
def _sse_content_with_protocol(response, handler, **sse_kwargs): """ Sometimes we need the protocol object so that we can manipulate the underlying transport in tests. """ protocol = SseProtocol(handler, **sse_kwargs) finished = protocol.when_finished() response.deliverBody(protocol) r...
Callback to collect the Server - Sent Events content of a response. Callbacks passed will receive event data.
def sse_content(response, handler, **sse_kwargs): """ Callback to collect the Server-Sent Events content of a response. Callbacks passed will receive event data. :param response: The response from the SSE request. :param handler: The handler for the SSE protocol. """ # An SS...
Recursively make requests to each endpoint in endpoints.
def _request(self, failure, endpoints, *args, **kwargs): """ Recursively make requests to each endpoint in ``endpoints``. """ # We've run out of endpoints, fail if not endpoints: return failure endpoint = endpoints.pop(0) d = super(MarathonClient, sel...
Perform a GET request and get the contents of the JSON response.
def get_json_field(self, field, **kwargs): """ Perform a GET request and get the contents of the JSON response. Marathon's JSON responses tend to contain an object with a single key which points to the actual data of the response. For example /v2/apps returns something like {"ap...
Get a JSON field from the response JSON.
def _get_json_field(self, response_json, field_name): """ Get a JSON field from the response JSON. :param: response_json: The parsed JSON content of the response. :param: field_name: The name of the field in the JSON to get. """ if field_name not ...
Attach to Marathon s event stream using Server - Sent Events ( SSE ).
def get_events(self, callbacks): """ Attach to Marathon's event stream using Server-Sent Events (SSE). :param callbacks: A dict mapping event types to functions that handle the event data """ d = self.request( 'GET', path='/v2/events', unbuffered=True, ...
Parse value from string.
def parse( self, value: str, type_: typing.Type[typing.Any] = str, subtype: typing.Type[typing.Any] = str, ) -> typing.Any: """ Parse value from string. Convert :code:`value` to .. code-block:: python >>> parser = Config() >>> ...
Parse a value from an environment variable.
def get( self, key: str, default: typing.Any = UNSET, type_: typing.Type[typing.Any] = str, subtype: typing.Type[typing.Any] = str, mapper: typing.Optional[typing.Callable[[object], object]] = None, ) -> typing.Any: """ Parse a value from an environmen...
Perform a request to a specific endpoint. Raise an error if the status code indicates a client or server error.
def _request(self, endpoint, *args, **kwargs): """ Perform a request to a specific endpoint. Raise an error if the status code indicates a client or server error. """ kwargs['url'] = endpoint return (super(MarathonLbClient, self).request(*args, **kwargs) ....
Check the result of each request that we made. If a failure occurred but some requests succeeded log and count the failures. If all requests failed raise an error.
def _check_request_results(self, results): """ Check the result of each request that we made. If a failure occurred, but some requests succeeded, log and count the failures. If all requests failed, raise an error. :return: The list of responses, with a None value for...
Set up a client key if one does not exist already.
def maybe_key(pem_path): """ Set up a client key if one does not exist already. https://gist.github.com/glyph/27867a478bb71d8b6046fbfb176e1a33#file-local-certs-py-L32-L50 :type pem_path: twisted.python.filepath.FilePath :param pem_path: The path to the certificate directory to use. :rt...
Set up a client key in Vault if one does not exist already.
def maybe_key_vault(client, mount_path): """ Set up a client key in Vault if one does not exist already. :param client: The Vault API client to use. :param mount_path: The Vault key/value mount path to use. :rtype: twisted.internet.defer.Deferred """ d = client.read_kv2('cli...
Create a creator for txacme clients to provide to the txacme service. See txacme. client. Client. from_url (). We create the underlying JWSClient with a non - persistent pool to avoid https:// github. com/ mithrandi/ txacme/ issues/ 86.
def create_txacme_client_creator(key, reactor, url, alg=RS256): """ Create a creator for txacme clients to provide to the txacme service. See ``txacme.client.Client.from_url()``. We create the underlying JWSClient with a non-persistent pool to avoid https://github.com/mithrandi/txacme/issues/86. ...
Generate a wildcard ( subject name * ) self - signed certificate valid for 10 years.
def generate_wildcard_pem_bytes(): """ Generate a wildcard (subject name '*') self-signed certificate valid for 10 years. https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate :return: Bytes representation of the PEM certificate data """ key = generate_private...
Create a Vault client with configuration from the environment. Supports a limited number of the available config options: https:// www. vaultproject. io/ docs/ commands/ index. html#environment - variables https:// github. com/ hashicorp/ vault/ blob/ v0. 11. 3/ api/ client. go#L28 - L40
def from_env(cls, reactor=None, env=os.environ): """ Create a Vault client with configuration from the environment. Supports a limited number of the available config options: https://www.vaultproject.io/docs/commands/index.html#environment-variables https://github.com/hashicorp/v...
Read data from Vault. Returns the JSON - decoded response.
def read(self, path, **params): """ Read data from Vault. Returns the JSON-decoded response. """ d = self.request('GET', '/v1/' + path, params=params) return d.addCallback(self._handle_response)
Write data to Vault. Returns the JSON - decoded response.
def write(self, path, **data): """ Write data to Vault. Returns the JSON-decoded response. """ d = self.request('PUT', '/v1/' + path, json=data) return d.addCallback(self._handle_response, check_cas=True)
Read some data from a key/ value version 2 secret engine.
def read_kv2(self, path, version=None, mount_path='secret'): """ Read some data from a key/value version 2 secret engine. """ params = {} if version is not None: params['version'] = version read_path = '{}/data/{}'.format(mount_path, path) return self...
Create or update some data in a key/ value version 2 secret engine.
def create_or_update_kv2(self, path, data, cas=None, mount_path='secret'): """ Create or update some data in a key/value version 2 secret engine. :raises CasError: Raises an error if the ``cas`` value, when provided, doesn't match Vault's version for the key. """...
Get a single value for the given key out of the given set of headers.
def get_single_header(headers, key): """ Get a single value for the given key out of the given set of headers. :param twisted.web.http_headers.Headers headers: The set of headers in which to look for the header value :param str key: The header key """ raw_headers = headers.getRa...
Raises a requests. exceptions. HTTPError if the response did not succeed. Adapted from the Requests library: https:// github. com/ kennethreitz/ requests/ blob/ v2. 8. 1/ requests/ models. py#L825 - L837
def raise_for_status(response): """ Raises a `requests.exceptions.HTTPError` if the response did not succeed. Adapted from the Requests library: https://github.com/kennethreitz/requests/blob/v2.8.1/requests/models.py#L825-L837 """ http_error_msg = '' if 400 <= response.code < 500: h...
Compose a URL starting with the given URL ( or self. url if that URL is None ) and using the values in kwargs.
def _compose_url(self, url, kwargs): """ Compose a URL starting with the given URL (or self.url if that URL is None) and using the values in kwargs. :param str url: The base URL to use. If None, ``self.url`` will be used instead. :param dict kwargs: A dic...
Perform a request.
def request(self, method, url=None, **kwargs): """ Perform a request. :param: method: The HTTP method to use (example is `GET`). :param: url: The URL to use. The default value is the URL this client was created with (`self.url`) (example is `http://lo...
Run the server i. e. start listening for requests on the given host and port.
def listen(self, reactor, endpoint_description): """ Run the server, i.e. start listening for requests on the given host and port. :param reactor: The ``IReactorTCP`` to use. :param endpoint_description: The Twisted description for the endpoint to listen on. ...
Listens to incoming health checks from Marathon on/ health.
def health(self, request): """ Listens to incoming health checks from Marathon on ``/health``. """ if self.health_handler is None: return self._no_health_handler(request) health = self.health_handler() response_code = OK if health.healthy else SERVICE_UNAVAILABLE req...
A tool to automatically request renew and distribute Let s Encrypt certificates for apps running on Marathon and served by marathon - lb.
def main(reactor, argv=sys.argv[1:], env=os.environ, acme_url=LETSENCRYPT_DIRECTORY.asText()): """ A tool to automatically request, renew and distribute Let's Encrypt certificates for apps running on Marathon and served by marathon-lb. """ parser = argparse.ArgumentParser( descripti...
Parse an address of the form [ ipaddress ]: port into a tcp or tcp6 Twisted endpoint description string for use with twisted. internet. endpoints. serverFromString.
def parse_listen_addr(listen_addr): """ Parse an address of the form [ipaddress]:port into a tcp or tcp6 Twisted endpoint description string for use with ``twisted.internet.endpoints.serverFromString``. """ if ':' not in listen_addr: raise ValueError( "'%s' does not have the ...
Create a marathon - acme instance.
def create_marathon_acme( client_creator, cert_store, acme_email, allow_multiple_certs, marathon_addrs, marathon_timeout, sse_timeout, mlb_addrs, group, reactor): """ Create a marathon-acme instance. :param client_creator: The txacme client creator function. :param cert_store: ...
Initialise the storage directory with the certificates directory and a default wildcard self - signed certificate for HAProxy.
def init_storage_dir(storage_dir): """ Initialise the storage directory with the certificates directory and a default wildcard self-signed certificate for HAProxy. :return: the storage path and certs path """ storage_path = FilePath(storage_dir) # Create the default wildcard certificate if...