INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns if instance with an wal should consider itself unhealthy to be promoted due to replication lag.
def is_lagging(self, wal_position): """Returns if instance with an wal should consider itself unhealthy to be promoted due to replication lag. :param wal_position: Current wal position. :returns True when node is lagging """ lag = (self.cluster.last_leader_operation or 0) - wal_...
This method tries to determine whether I am healthy enough to became a new leader candidate or not.
def _is_healthiest_node(self, members, check_replication_lag=True): """This method tries to determine whether I am healthy enough to became a new leader candidate or not.""" _, my_wal_position = self.state_handler.timeline_wal_position() if check_replication_lag and self.is_lagging(my_wal_posit...
Demote PostgreSQL running as master.
def demote(self, mode): """Demote PostgreSQL running as master. :param mode: One of offline, graceful or immediate. offline is used when connection to DCS is not available. graceful is used when failing over to another node due to user request. May only be called running async. ...
Checks if manual failover is requested and takes action if appropriate.
def process_manual_failover_from_leader(self): """Checks if manual failover is requested and takes action if appropriate. Cleans up failover key if failover conditions are not matched. :returns: action message if demote was initiated, None if no action was taken""" failover = self.clus...
Cluster has no leader key
def process_unhealthy_cluster(self): """Cluster has no leader key""" if self.is_healthiest_node(): if self.acquire_lock(): failover = self.cluster.failover if failover: if self.is_paused() and failover.leader and failover.candidate: ...
conditional and unconditional restart
def restart(self, restart_data, run_async=False): """ conditional and unconditional restart """ assert isinstance(restart_data, dict) if (not self.restart_matches(restart_data.get('role'), restart_data.get('postgres_version'), ...
Starting up PostgreSQL may take a long time. In case we are the leader we may want to fail over to.
def handle_starting_instance(self): """Starting up PostgreSQL may take a long time. In case we are the leader we may want to fail over to.""" # Check if we are in startup, when paused defer to main loop for manual failovers. if not self.state_handler.check_for_startup() or self.is_pause...
In case of standby cluster this will tel us from which remote master to stream. Config can be both patroni config or cluster. config. data
def get_remote_member(self, member=None): """ In case of standby cluster this will tel us from which remote master to stream. Config can be both patroni config or cluster.config.data """ cluster_params = self.get_standby_cluster_config() if cluster_params: ...
Original machines method ( property ) of etcd. Client class raise exception when it failed to get list of etcd cluster members. This method is being called only when request failed on one of the etcd members during api_execute call. For us it s more important to execute original request rather then get new topology of ...
def machines(self): """Original `machines` method(property) of `etcd.Client` class raise exception when it failed to get list of etcd cluster members. This method is being called only when request failed on one of the etcd members during `api_execute` call. For us it's more important to ...
Fetch list of etcd - cluster member by resolving _etcd - server. _tcp. SRV record. This record should contain list of host and peer ports which could be used to run GET http:// { host }: { port }/ members request ( peer protocol )
def _get_machines_cache_from_srv(self, srv): """Fetch list of etcd-cluster member by resolving _etcd-server._tcp. SRV record. This record should contain list of host and peer ports which could be used to run 'GET http://{host}:{port}/members' request (peer protocol)""" ret = [] ...
One host might be resolved into multiple ip addresses. We will make list out of it
def _get_machines_cache_from_dns(self, host, port): """One host might be resolved into multiple ip addresses. We will make list out of it""" if self.protocol == 'http': ret = [] for af, _, _, _, sa in self._dns_resolver.resolve(host, port): host, port = sa[:2] ...
This method should fill up _machines_cache from scratch. It could happen only in two cases: 1. During class initialization 2. When all etcd members failed
def _load_machines_cache(self): """This method should fill up `_machines_cache` from scratch. It could happen only in two cases: 1. During class initialization 2. When all etcd members failed""" self._update_machines_cache = True if 'srv' not in self._config and 'host' ...
Builds and executes pg_ctl command
def pg_ctl(self, cmd, *args, **kwargs): """Builds and executes pg_ctl command :returns: `!True` when return_code == 0, otherwise `!False`""" pg_ctl = [self._pgcommand('pg_ctl'), cmd] return subprocess.call(pg_ctl + ['-D', self._data_dir] + list(args), **kwargs) == 0
Runs pg_isready to see if PostgreSQL is accepting connections.
def pg_isready(self): """Runs pg_isready to see if PostgreSQL is accepting connections. :returns: 'ok' if PostgreSQL is up, 'reject' if starting up, 'no_resopnse' if not up.""" cmd = [self._pgcommand('pg_isready'), '-p', self._local_address['port'], '-d', self._database] # Host is not...
check if pg_rewind executable is there and that pg_controldata indicates we have either wal_log_hints or checksums turned on
def can_rewind(self): """ check if pg_rewind executable is there and that pg_controldata indicates we have either wal_log_hints or checksums turned on """ # low-hanging fruit: check if pg_rewind configuration is there if not self.config.get('use_pg_rewind'): retur...
We are always using the same cursor therefore this method is not thread - safe!!! You can call it from different threads only if you are holding explicit AsyncExecutor lock because the main thread is always holding this lock when running HA cycle.
def _query(self, sql, *params): """We are always using the same cursor, therefore this method is not thread-safe!!! You can call it from different threads only if you are holding explicit `AsyncExecutor` lock, because the main thread is always holding this lock when running HA cycle.""" ...
runs a script after initdb or custom bootstrap script is called and waits until completion.
def run_bootstrap_post_init(self, config): """ runs a script after initdb or custom bootstrap script is called and waits until completion. """ cmd = config.get('post_bootstrap') or config.get('post_init') if cmd: r = self._local_connect_kwargs if 'host' i...
go through the replication methods to see if there are ones that does not require a working replication connection.
def can_create_replica_without_replication_connection(self): """ go through the replication methods to see if there are ones that does not require a working replication connection. """ replica_methods = self._create_replica_methods return any(self.replica_method_can_work_with...
create the replica according to the replica_method defined by the user. this is a list so we need to loop through all methods the user supplies
def create_replica(self, clone_member): """ create the replica according to the replica_method defined by the user. this is a list, so we need to loop through all methods the user supplies """ self.set_state('creating replica') self._sysid = None ...
Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process is running updates the cached process based on pid file.
def is_running(self): """Returns PostmasterProcess if one is running on the data directory or None. If most recently seen process is running updates the cached process based on pid file.""" if self._postmaster_proc: if self._postmaster_proc.is_running(): return self._...
pick a callback command and call it without waiting for it to finish
def call_nowait(self, cb_name): """ pick a callback command and call it without waiting for it to finish """ if self.bootstrapping: return if cb_name in (ACTION_ON_START, ACTION_ON_STOP, ACTION_ON_RESTART, ACTION_ON_ROLE_CHANGE): self.__cb_called = True if self.c...
Waits until PostgreSQL opens ports.
def wait_for_port_open(self, postmaster, timeout): """Waits until PostgreSQL opens ports.""" for _ in polling_loop(timeout): with self._cancellable_lock: if self._is_cancelled: return False if not postmaster.is_running(): logge...
It might happen that the current value of one ( or more ) below parameters stored in the controldata is higher than the value stored in the global cluster configuration.
def _build_effective_configuration(self): """It might happen that the current value of one (or more) below parameters stored in the controldata is higher than the value stored in the global cluster configuration. Example: max_connections in global configuration is 100, but in controldata ...
Start PostgreSQL
def start(self, timeout=None, task=None, block_callbacks=False, role=None): """Start PostgreSQL Waits for postmaster to open ports or terminate so pg_isready can be used to check startup completion or failure. :returns: True if start was initiated and postmaster ports are open, False i...
Stop PostgreSQL
def stop(self, mode='fast', block_callbacks=False, checkpoint=None, on_safepoint=None): """Stop PostgreSQL Supports a callback when a safepoint is reached. A safepoint is when no user backend can return a successful commit to users. Currently this means we wait for user backends to close. But i...
Checks if PostgreSQL has completed starting up or failed or still starting.
def check_startup_state_changed(self): """Checks if PostgreSQL has completed starting up or failed or still starting. Should only be called when state == 'starting' :returns: True if state was changed from 'starting' """ ready = self.pg_isready() if ready == STATE_REJE...
Waits for PostgreSQL startup to complete or fail.
def wait_for_startup(self, timeout=None): """Waits for PostgreSQL startup to complete or fail. :returns: True if start was successful, False otherwise""" if not self.is_starting(): # Should not happen logger.warning("wait_for_startup() called when not in starting state")...
Restarts PostgreSQL.
def restart(self, timeout=None, task=None, block_callbacks=False, role=None): """Restarts PostgreSQL. When timeout parameter is set the call will block either until PostgreSQL has started, failed to start or timeout arrives. :returns: True when restart was successful and timeout did no...
Replace pg_hba. conf content in the PGDATA if hba_file is not defined in the postgresql. parameters and pg_hba is defined in postgresql configuration section.
def _replace_pg_hba(self): """ Replace pg_hba.conf content in the PGDATA if hba_file is not defined in the `postgresql.parameters` and pg_hba is defined in `postgresql` configuration section. :returns: True if pg_hba.conf was rewritten. """ # when we are doing custom bo...
Replace pg_ident. conf content in the PGDATA if ident_file is not defined in the postgresql. parameters and pg_ident is defined in the postgresql section.
def _replace_pg_ident(self): """ Replace pg_ident.conf content in the PGDATA if ident_file is not defined in the `postgresql.parameters` and pg_ident is defined in the `postgresql` section. :returns: True if pg_ident.conf was rewritten. """ if not self._server_parameter...
return the contents of pg_controldata or non - True value if pg_controldata call failed
def controldata(self): """ return the contents of pg_controldata, or non-True value if pg_controldata call failed """ result = {} # Don't try to call pg_controldata during backup restore if self._version_file_exists() and self.state != 'creating replica': try: ...
copy postgresql. conf to postgresql. conf. backup to be able to retrive configuration files - originally stored as symlinks those are normally skipped by pg_basebackup - in case of WAL - E basebackup ( see http:// comments. gmane. org/ gmane. comp. db. postgresql. wal - e/ 239 )
def save_configuration_files(self): """ copy postgresql.conf to postgresql.conf.backup to be able to retrive configuration files - originally stored as symlinks, those are normally skipped by pg_basebackup - in case of WAL-E basebackup (see http://comments.gmane.org/gmane.com...
restore a previously saved postgresql. conf
def restore_configuration_files(self): """ restore a previously saved postgresql.conf """ try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if no...
- initialize the replica from an existing member ( master or replica ) - initialize the replica using the replica creation method that works without the replication connection ( i. e. restore from on - disk base backup )
def clone(self, clone_member): """ - initialize the replica from an existing member (master or replica) - initialize the replica using the replica creation method that works without the replication connection (i.e. restore from on-disk base backup) ...
Initialize a new node from scratch and start it.
def bootstrap(self, config): """ Initialize a new node from scratch and start it. """ pg_hba = config.get('pg_hba', []) method = config.get('method') or 'initdb' self._running_custom_bootstrap = method != 'initdb' and method in config and 'command' in config[method] if self._runn...
Finds the best candidate to be the synchronous standby.
def pick_synchronous_standby(self, cluster): """Finds the best candidate to be the synchronous standby. Current synchronous standby is always preferred, unless it has disconnected or does not want to be a synchronous standby any longer. :returns tuple of candidate name or None, and boo...
Sets a node to be synchronous standby and if changed does a reload for PostgreSQL.
def set_synchronous_standby(self, name): """Sets a node to be synchronous standby and if changed does a reload for PostgreSQL.""" if name and name != '*': name = quote_ident(name) if name != self._synchronous_standby_names: if name is None: self._server_pa...
Convert the server_version to integer
def postgres_version_to_int(pg_version): """Convert the server_version to integer >>> Postgresql.postgres_version_to_int('9.5.3') 90503 >>> Postgresql.postgres_version_to_int('9.3.13') 90313 >>> Postgresql.postgres_version_to_int('10.1') 100001 >>> Postgr...
returns the list of option names/ values from postgres. opts Empty dict if read failed or no file
def read_postmaster_opts(self): """returns the list of option names/values from postgres.opts, Empty dict if read failed or no file""" result = {} try: with open(os.path.join(self._data_dir, 'postmaster.opts')) as f: data = f.read() for opt in data.spl...
run a given command in a single - user mode. If the command is empty - then just start and stop
def single_user_mode(self, command=None, options=None): """run a given command in a single-user mode. If the command is empty - then just start and stop""" cmd = [self._pgcommand('postgres'), '--single', '-D', self._data_dir] for opt, val in sorted((options or {}).items()): cmd.exten...
>>> deep_compare ( { 1: None } {} ) False >>> deep_compare ( { 1: {} } { 1: None } ) False >>> deep_compare ( { 1: [ 1 ] } { 1: [ 2 ] } ) False >>> deep_compare ( { 1: 2 } { 1: 2 } ) True >>> deep_compare ( { 1: { 2: [ 3 4 ] }} { 1: { 2: [ 3 4 ] }} ) True
def deep_compare(obj1, obj2): """ >>> deep_compare({'1': None}, {}) False >>> deep_compare({'1': {}}, {'1': None}) False >>> deep_compare({'1': [1]}, {'1': [2]}) False >>> deep_compare({'1': 2}, {'1': '2'}) True >>> deep_compare({'1': {'2': [3, 4]}}, {'1': {'2': [3, 4]}}) Tru...
recursively patch config with data: returns: !True if the config was changed
def patch_config(config, data): """recursively 'patch' `config` with `data` :returns: `!True` if the `config` was changed""" is_changed = False for name, value in data.items(): if value is None: if config.pop(name, None) is not None: is_changed = True elif nam...
>>> parse_bool ( 1 ) True >>> parse_bool ( off ) False >>> parse_bool ( foo )
def parse_bool(value): """ >>> parse_bool(1) True >>> parse_bool('off') False >>> parse_bool('foo') """ value = str(value).lower() if value in ('on', 'true', 'yes', '1'): return True if value in ('off', 'false', 'no', '0'): return False
As most as possible close equivalent of strtol ( 3 ) function ( with base = 0 ) used by postgres to parse parameter values. >>> strtol ( 0 ) == ( 0 ) True >>> strtol ( 1 ) == ( 1 ) True >>> strtol ( 9 ) == ( 9 ) True >>> strtol ( + 0x400MB ) == ( 1024 MB ) True >>> strtol ( - 070d ) == ( - 56 d ) True >>> strtol ( d ) ...
def strtol(value, strict=True): """As most as possible close equivalent of strtol(3) function (with base=0), used by postgres to parse parameter values. >>> strtol(0) == (0, '') True >>> strtol(1) == (1, '') True >>> strtol(9) == (9, '') True >>> strtol(' +0x400MB') == (1024, 'MB'...
>>> parse_int ( 1 ) == 1 True >>> parse_int ( 0x400 MB 16384kB ) == 64 True >>> parse_int ( 1MB kB ) == 1024 True >>> parse_int ( 1000 ms s ) == 1 True >>> parse_int ( 1GB MB ) is None True >>> parse_int ( 0 ) == 0 True
def parse_int(value, base_unit=None): """ >>> parse_int('1') == 1 True >>> parse_int(' 0x400 MB ', '16384kB') == 64 True >>> parse_int('1MB', 'kB') == 1024 True >>> parse_int('1000 ms', 's') == 1 True >>> parse_int('1GB', 'MB') is None True >>> parse_int(0) == 0 True ...
>>> compare_values ( enum None remote_write REMOTE_WRITE ) True >>> compare_values ( real None 1. 23 1. 23 ) True
def compare_values(vartype, unit, old_value, new_value): """ >>> compare_values('enum', None, 'remote_write', 'REMOTE_WRITE') True >>> compare_values('real', None, '1.23', 1.23) True """ # if the integer or bool new_value is not correct this function will return False if vartype == 'boo...
Returns an iterator that returns values until timeout has passed. Timeout is measured from start of iteration.
def polling_loop(timeout, interval=1): """Returns an iterator that returns values until timeout has passed. Timeout is measured from start of iteration.""" start_time = time.time() iteration = 0 end_time = start_time + timeout while time.time() < end_time: yield iteration iteration +...
Reset the attempt counter
def reset(self): """Reset the attempt counter""" self._attempts = 0 self._cur_delay = self.delay self._cur_stoptime = None
Return a clone of this retry manager
def copy(self): """Return a clone of this retry manager""" return Retry(max_tries=self.max_tries, delay=self.delay, backoff=self.backoff, max_jitter=self.max_jitter / 100.0, max_delay=self.max_delay, sleep_func=self.sleep_func, deadline=self.deadline, retry_exce...
Decorator function to check authorization header.
def check_auth(func): """Decorator function to check authorization header. Usage example: @check_auth def do_PUT_foo(): pass """ def wrapper(handler, *args, **kwargs): if handler.check_auth_header(): return func(handler, *args, **kwargs) return wrapper
Default method for processing all GET requests which can not be routed to other methods
def do_GET(self, write_status_code_only=False): """Default method for processing all GET requests which can not be routed to other methods""" path = '/master' if self.path == '/' else self.path response = self.get_postgresql_status() patroni = self.server.patroni cluster = patr...
parses the given schedule and validates at
def parse_schedule(schedule, action): """ parses the given schedule and validates at """ error = None scheduled_at = None try: scheduled_at = dateutil.parser.parse(schedule) if scheduled_at.tzinfo is None: error = 'Timezone information is mandatory...
Override parse_request method to enrich basic functionality of BaseHTTPRequestHandler class
def parse_request(self): """Override parse_request method to enrich basic functionality of `BaseHTTPRequestHandler` class Original class can only invoke do_GET, do_POST, do_PUT, etc method implementations if they are defined. But we would like to have at least some simple routing mechanism, i.e...
Loads config. yaml from filesystem and applies some values which were set via ENV
def _load_config_file(self): """Loads config.yaml from filesystem and applies some values which were set via ENV""" with open(self._config_file) as f: config = yaml.safe_load(f) patch_config(config, self.__environment_configuration) return config
Translate member name to valid PostgreSQL slot name.
def slot_name_from_member_name(member_name): """Translate member name to valid PostgreSQL slot name. PostgreSQL replication slot names must be valid PostgreSQL names. This function maps the wider space of member names to valid PostgreSQL names. Names are lowercased, dashes and periods common in hostnames ...
Original Governor stores connection strings for each cluster members if a following format: postgres:// { username }: { password } @ { connect_address }/ postgres Since each of our patroni instances provides own REST API endpoint it s good to store this information in DCS among with postgresql connection string. In ord...
def parse_connection_string(value): """Original Governor stores connection strings for each cluster members if a following format: postgres://{username}:{password}@{connect_address}/postgres Since each of our patroni instances provides own REST API endpoint it's good to store this information in DCS...
Get names of DCS modules depending on execution environment. If being packaged with PyInstaller modules aren t discoverable dynamically by scanning source directory because FrozenImporter doesn t implement iter_modules method. But it is still possible to find all potential DCS modules by iterating through toc which con...
def dcs_modules(): """Get names of DCS modules, depending on execution environment. If being packaged with PyInstaller, modules aren't discoverable dynamically by scanning source directory because `FrozenImporter` doesn't implement `iter_modules` method. But it is still possible to find all potential DCS mo...
>>> Member. from_node ( - 1 { conn_url: postgres:// foo
def from_node(index, name, session, data): """ >>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None True >>> Member.from_node(-1, '', '', '{') Member(index=-1, name='', session='', data={}) """ if data.startswith('postgres'):...
>>> ClusterConfig. from_node ( 1 { ) is None False
def from_node(index, data, modify_index=None): """ >>> ClusterConfig.from_node(1, '{') is None False """ try: data = json.loads(data) except (TypeError, ValueError): data = None modify_index = 0 if not isinstance(data, dict): ...
>>> SyncState. from_node ( 1 None ). leader is None True >>> SyncState. from_node ( 1 {} ). leader is None True >>> SyncState. from_node ( 1 { ). leader is None True >>> SyncState. from_node ( 1 [] ). leader is None True >>> SyncState. from_node ( 1 { leader: leader } ). leader == leader True >>> SyncState. from_node (...
def from_node(index, value): """ >>> SyncState.from_node(1, None).leader is None True >>> SyncState.from_node(1, '{}').leader is None True >>> SyncState.from_node(1, '{').leader is None True >>> SyncState.from_node(1, '[]').leader is None True ...
>>> h = TimelineHistory. from_node ( 1 2 ) >>> h. lines []
def from_node(index, value): """ >>> h = TimelineHistory.from_node(1, 2) >>> h.lines [] """ try: lines = json.loads(value) except (TypeError, ValueError): lines = None if not isinstance(lines, list): lines = [] r...
>>> Cluster ( 0 0 0 0 0 0 0 0 ). timeline 0 >>> Cluster ( 0 0 0 0 0 0 0 TimelineHistory. from_node ( 1 [] )). timeline 1 >>> Cluster ( 0 0 0 0 0 0 0 TimelineHistory. from_node ( 1 [[ a ]] )). timeline 0
def timeline(self): """ >>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline 0 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline 1 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline 0 """ if self....
>>> Kubernetes. subsets_changed ( [] [] ) False >>> Kubernetes. subsets_changed ( [] [ k8s_client. V1EndpointSubset () ] ) True >>> s1 = [ k8s_client. V1EndpointSubset ( addresses = [ k8s_client. V1EndpointAddress ( ip = 1. 2. 3. 4 ) ] ) ] >>> s2 = [ k8s_client. V1EndpointSubset ( addresses = [ k8s_client. V1EndpointAd...
def subsets_changed(last_observed_subsets, subsets): """ >>> Kubernetes.subsets_changed([], []) False >>> Kubernetes.subsets_changed([], [k8s_client.V1EndpointSubset()]) True >>> s1 = [k8s_client.V1EndpointSubset(addresses=[k8s_client.V1EndpointAddress(ip='1.2.3.4')])] ...
stop all Patronis remove their data directory and cleanup the keys in etcd
def after_feature(context, feature): """ stop all Patronis, remove their data directory and cleanup the keys in etcd """ context.pctl.stop_all() shutil.rmtree(os.path.join(context.pctl.patroni_path, 'data')) context.dcs_ctl.cleanup_service_tree() if feature.status == 'failed': shutil.copytre...
terminate process and wipe out the temp work directory but only if we actually started it
def stop(self, kill=False, timeout=15): """ terminate process and wipe out the temp work directory, but only if we actually started it""" super(AbstractDcsController, self).stop(kill=kill, timeout=timeout) if self._work_directory: shutil.rmtree(self._work_directory)
Runs the specified ioctl on the underlying fd.
def _ioctl(self, func, arg): """Runs the specified ioctl on the underlying fd. Raises WatchdogError if the device is closed. Raises OSError or IOError (Python 2) when the ioctl fails.""" if self._fd is None: raise WatchdogError("Watchdog device is closed") if os.name...
Returns JSON - safe version of string.
def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base64-encoded, formatted and ...
Returns files dict from request context.
def get_files(): """Returns files dict from request context.""" files = dict() for k, v in request.files.items(): content_type = request.files[k].content_type or 'application/octet-stream' val = json_safe(v.read(), content_type) if files.get(k): if not isinstance(files[...
Returns headers dict from request context.
def get_headers(hide_env=True): """Returns headers dict from request context.""" headers = dict(request.headers.items()) if hide_env and ('show_env' not in request.args): for key in ENV_HEADERS: try: del headers[key] except KeyError: pass ...
Convert a MutiDict into a regular dict. If there are more than one value for a key the result will have a list of values for the key. Otherwise it will have the plain value.
def semiflatten(multi): """Convert a MutiDict into a regular dict. If there are more than one value for a key, the result will have a list of values for the key. Otherwise it will have the plain value.""" if multi: result = multi.to_dict(flat=False) for k, v in result.items(): ...
Since we might be hosted behind a proxy we need to check the X - Forwarded - Proto X - Forwarded - Protocol or X - Forwarded - SSL headers to find out what protocol was used to access us.
def get_url(request): """ Since we might be hosted behind a proxy, we need to check the X-Forwarded-Proto, X-Forwarded-Protocol, or X-Forwarded-SSL headers to find out what protocol was used to access us. """ protocol = request.headers.get('X-Forwarded-Proto') or request.headers.get('X-Forwarded...
Returns request dict of given keys.
def get_dict(*keys, **extras): """Returns request dict of given keys.""" _keys = ('url', 'args', 'form', 'data', 'origin', 'headers', 'files', 'json', 'method') assert all(map(_keys.__contains__, keys)) data = request.data form = semiflatten(request.form) try: _json = json.loads(data....
Returns response object of given status code.
def status_code(code): """Returns response object of given status code.""" redirect = dict(headers=dict(location=REDIRECT_LOCATION)) code_map = { 301: redirect, 302: redirect, 303: redirect, 304: dict(data=''), 305: redirect, 307: redirect, 401: dict...
Checks user authentication using HTTP Basic Auth.
def check_basic_auth(user, passwd): """Checks user authentication using HTTP Basic Auth.""" auth = request.authorization return auth and auth.username == user and auth.password == passwd
Create HA1 hash by realm username password
def HA1(realm, username, password, algorithm): """Create HA1 hash by realm, username, password HA1 = md5(A1) = MD5(username:realm:password) """ if not realm: realm = u'' return H(b":".join([username.encode('utf-8'), realm.encode('utf-8'), ...
Create HA2 md5 hash
def HA2(credentials, request, algorithm): """Create HA2 md5 hash If the qop directive's value is "auth" or is unspecified, then HA2: HA2 = md5(A2) = MD5(method:digestURI) If the qop directive's value is "auth-int" , then HA2 is HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody)) """ ...
Compile digest auth response
def response(credentials, password, request): """Compile digest auth response If the qop directive's value is "auth" or "auth-int" , then compute the response as follows: RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2) Else if the qop directive is unspecified, then compute the response as fo...
Check user authentication using HTTP Digest auth
def check_digest_auth(user, passwd): """Check user authentication using HTTP Digest auth""" if request.headers.get('Authorization'): credentials = parse_authorization_header(request.headers.get('Authorization')) if not credentials: return request_uri = request.script_root + ...
Return a tuple describing the byte range requested in a GET request If the range is open ended on the left or right side then a value of None will be set. RFC7233: http:// svn. tools. ietf. org/ svn/ wg/ httpbis/ specs/ rfc7233. html#header. range Examples: Range: bytes = 1024 - Range: bytes = 10 - 20 Range: bytes = - ...
def __parse_request_range(range_header_text): """ Return a tuple describing the byte range requested in a GET request If the range is open ended on the left or right side, then a value of None will be set. RFC7233: http://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7233.html#header.range Examples: ...
Break apart an HTTP header string that is potentially a quoted comma separated list as used in entity headers in RFC2616.
def parse_multi_value_header(header_str): """Break apart an HTTP header string that is potentially a quoted, comma separated list as used in entity headers in RFC2616.""" parsed_parts = [] if header_str: parts = header_str.split(',') for part in parts: match = re.search('\s*(W/)?...
302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/ html responses: 302: description: A redirection.
def redirect_n_times(n): """302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 absolute = request.args.get("absolute"...
302/ 3XX Redirects to the given URL. --- tags: - Redirects produces: - text/ html get: parameters: - in: query name: url type: string required: true - in: query name: status_code type: int post: consumes: - application/ x - www - form - urlencoded parameters: - in: formData name: url type: string required: true - in: f...
def redirect_to(): """302/3XX Redirects to the given URL. --- tags: - Redirects produces: - text/html get: parameters: - in: query name: url type: string required: true - in: query name: status_code type: int pos...
Relatively 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/ html responses: 302: description: A redirection.
def relative_redirect_n_times(n): """Relatively 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 response = app.ma...
Absolutely 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/ html responses: 302: description: A redirection.
def absolute_redirect_n_times(n): """Absolutely 302 Redirects n times. --- tags: - Redirects parameters: - in: path name: n type: int produces: - text/html responses: 302: description: A redirection. """ assert n > 0 if n == 1: ...
Stream n JSON responses --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/ json responses: 200: description: Streamed JSON responses.
def stream_n_messages(n): """Stream n JSON responses --- tags: - Dynamic data parameters: - in: path name: n type: int produces: - application/json responses: 200: description: Streamed JSON responses. """ response = get_dict("url", "args",...
Return status code or random status code if more than one are given --- tags: - Status codes parameters: - in: path name: codes produces: - text/ plain responses: 100: description: Informational responses 200: description: Success 300: description: Redirection 400: description: Client Errors 500: description: Server Er...
def view_status_code(codes): """Return status code or random status code if more than one are given --- tags: - Status codes parameters: - in: path name: codes produces: - text/plain responses: 100: description: Informational responses 200: d...
Returns a set of response headers from the query string. --- tags: - Response inspection parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string style: form produces: - application/ json responses: 200: description: Response headers
def response_headers(): """Returns a set of response headers from the query string. --- tags: - Response inspection parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: ...
Returns cookie data. --- tags: - Cookies produces: - application/ json responses: 200: description: Set cookies.
def view_cookies(hide_env=True): """Returns cookie data. --- tags: - Cookies produces: - application/json responses: 200: description: Set cookies. """ cookies = dict(request.cookies.items()) if hide_env and ("show_env" not in request.args): for key in...
Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/ plain responses: 200: description: Set cookies and redirects to cookie list.
def set_cookie(name, value): """Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/plain responses: 200: descript...
Sets cookie ( s ) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string style: form produces: - text/ plain responses: 200: description: Redirect to cookie list
def set_cookies(): """Sets cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: ...
Deletes cookie ( s ) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalProperties: type: string style: form produces: - text/ plain responses: 200: description: Redirect to cookie li...
def delete_cookies(): """Deletes cookie(s) as provided by the query string and redirects to cookie list. --- tags: - Cookies parameters: - in: query name: freeform explode: true allowEmptyValue: true schema: type: object additionalPropertie...
Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/ json responses: 200: description: Sucessful authentication. 401: description: Unsuccessful authentication.
def basic_auth(user="user", passwd="passwd"): """Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json res...
Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/ json responses: 200: description: Sucessful authentication. 404: description: Unsuccessful authentication.
def hidden_basic_auth(user="user", passwd="passwd"): """Prompts the user for authorization using HTTP Basic Auth. --- tags: - Auth parameters: - in: path name: user type: string - in: path name: passwd type: string produces: - application/json ...
Prompts the user for authorization using bearer authentication. --- tags: - Auth parameters: - in: header name: Authorization schema: type: string produces: - application/ json responses: 200: description: Sucessful authentication. 401: description: Unsuccessful authentication.
def bearer_auth(): """Prompts the user for authorization using bearer authentication. --- tags: - Auth parameters: - in: header name: Authorization schema: type: string produces: - application/json responses: 200: description: Sucessful a...
Prompts the user for authorization using Digest Auth + Algorithm. --- tags: - Auth parameters: - in: path name: qop type: string description: auth or auth - int - in: path name: user type: string - in: path name: passwd type: string - in: path name: algorithm type: string description: MD5 SHA - 256 SHA - 512 default: M...
def digest_auth_nostale(qop=None, user="user", passwd="passwd", algorithm="MD5"): """Prompts the user for authorization using Digest Auth + Algorithm. --- tags: - Auth parameters: - in: path name: qop type: string description: auth or auth-int - in: path ...
Prompts the user for authorization using Digest Auth + Algorithm. allow settings the stale_after argument. --- tags: - Auth parameters: - in: path name: qop type: string description: auth or auth - int - in: path name: user type: string - in: path name: passwd type: string - in: path name: algorithm type: string descri...
def digest_auth( qop=None, user="user", passwd="passwd", algorithm="MD5", stale_after="never" ): """Prompts the user for authorization using Digest Auth + Algorithm. allow settings the stale_after argument. --- tags: - Auth parameters: - in: path name: qop type: strin...
Returns a delayed response ( max of 10 seconds ). --- tags: - Dynamic data parameters: - in: path name: delay type: int produces: - application/ json responses: 200: description: A delayed response.
def delay_response(delay): """Returns a delayed response (max of 10 seconds). --- tags: - Dynamic data parameters: - in: path name: delay type: int produces: - application/json responses: 200: description: A delayed response. """ delay = mi...
Drips data over a duration after an optional initial delay. --- tags: - Dynamic data parameters: - in: query name: duration type: number description: The amount of time ( in seconds ) over which to drip each byte default: 2 required: false - in: query name: numbytes type: integer description: The number of bytes to res...
def drip(): """Drips data over a duration after an optional initial delay. --- tags: - Dynamic data parameters: - in: query name: duration type: number description: The amount of time (in seconds) over which to drip each byte default: 2 required: false...
Returns a 304 if an If - Modified - Since header or If - None - Match is present. Returns the same as a GET otherwise. --- tags: - Response inspection parameters: - in: header name: If - Modified - Since - in: header name: If - None - Match produces: - application/ json responses: 200: description: Cached response 304:...
def cache(): """Returns a 304 if an If-Modified-Since header or If-None-Match is present. Returns the same as a GET otherwise. --- tags: - Response inspection parameters: - in: header name: If-Modified-Since - in: header name: If-None-Match produces: - applica...
Assumes the resource has the given etag and responds to If - None - Match and If - Match headers appropriately. --- tags: - Response inspection parameters: - in: header name: If - None - Match - in: header name: If - Match produces: - application/ json responses: 200: description: Normal response 412: description: matc...
def etag(etag): """Assumes the resource has the given etag and responds to If-None-Match and If-Match headers appropriately. --- tags: - Response inspection parameters: - in: header name: If-None-Match - in: header name: If-Match produces: - application/json ...