code
stringlengths
1
18.2k
def import_data(self, data): """ Set the fields established in data to the instance """ if self.get_read_only() and self.is_locked(): return if isinstance(data, BaseModel): data = data.export_data() if not isinstance(data, (dict, Mapping)): raise TypeError('Impossible to import data') self._import_data(data)
def import_deleted_fields(self, data): """ Set data fields to deleted """ if self.get_read_only() and self.is_locked(): return if isinstance(data, str): data = [data] for key in data: if hasattr(self, key): delattr(self, key) continue keys = key.split('.', 1) if len(keys) != 2: continue child = getattr(self, keys[0]) c...
def export_data(self): """ Get the results with the modified_data """ result = {} data = self.__original_data__.copy() data.update(self.__modified_data__) for key, value in data.items(): if key in self.__deleted_fields__: continue try: result[key] = value.export_data() except AttributeError: result[key] = value return ...
def export_modified_data(self): """ Get the modified data """ # TODO: why None? Try to get a better flag result = {key: None for key in self.__deleted_fields__} for key, value in self.__modified_data__.items(): if key in result.keys(): continue try: result[key] = value.export_modified_data() except AttributeError: resu...
def export_modifications(self): """ Returns model modifications. """ result = {} for key, value in self.__modified_data__.items(): try: result[key] = value.export_data() except AttributeError: result[key] = value for key, value in self.__original_data__.items(): if key in result.keys() or key in self.__deleted_fields__...
def get_original_field_value(self, name): """ Returns original field value or None """ name = self.get_real_name(name) try: value = self.__original_data__[name] except KeyError: return None try: return value.export_original_data() except AttributeError: return value
def export_original_data(self): """ Get the original data """ return {key: self.get_original_field_value(key) for key in self.__original_data__.keys()}
def export_deleted_fields(self): """ Resturns a list with any deleted fields form original data. In tree models, deleted fields on children will be appended. """ result = self.__deleted_fields__.copy() for key, value in self.__original_data__.items(): if key in result: continue try: partial = value.export_deleted_field...
def flat_data(self): """ Pass all the data from modified_data to original_data """ def flat_field(value): """ Flat field data """ try: value.flat_data() return value except AttributeError: return value modified_dict = self.__original_data__ modified_dict.update(self.__modified_data__) self.__original_data__ = {k: flat_...
def clear_modified_data(self): """ Clears only the modified data """ self.__modified_data__ = {} self.__deleted_fields__ = [] for value in self.__original_data__.values(): try: value.clear_modified_data() except AttributeError: pass
def clear(self): """ Clears all the data in the object, keeping original data """ self.__modified_data__ = {} self.__deleted_fields__ = [field for field in self.__original_data__.keys()]
def get_fields(self): """ Returns used fields of model """ result = [key for key in self.__original_data__.keys() if key not in self.__deleted_fields__] result.extend([key for key in self.__modified_data__.keys() if key not in result and key not in self.__deleted_fields__]) return result
def is_modified(self): """ Returns whether model is modified or not """ if len(self.__modified_data__) or len(self.__deleted_fields__): return True for value in self.__original_data__.values(): try: if value.is_modified(): return True except AttributeError: pass return False
def get_attrs_by_path(self, field_path, stop_first=False): """ It returns list of values looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: list or None. :param stop_first: Stop iteration on first ...
def get_1st_attr_by_path(self, field_path, **kwargs): """ It returns first value looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: str :param default: Default value if field does not exist. If it ...
def delete_attr_by_path(self, field_path): """ It deletes fields looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: str """ fields, next_field = self._get_fields_by_path(field_path) for field in fi...
def reset_attr_by_path(self, field_path): """ It restores original values for fields looked up by field path. Field path is dot-formatted string path: ``parent_field.child_field``. :param field_path: field path. It allows ``*`` as wildcard. :type field_path: str """ fields, next_field = self._get_fields_by_path(field_p...
def _get_field_type(self, key, value): """ Helper to create field object based on value type """ if isinstance(value, bool): return BooleanField(name=key) elif isinstance(value, int): return IntegerField(name=key) elif isinstance(value, float): return FloatField(name=key) elif isinstance(value, str): return StringField...
def _import_data(self, data): """ Set the fields established in data to the instance """ for key, value in data.items(): if key.startswith('__'): self._not_allowed_field(key) continue if not self.get_field_obj(key) and not self._define_new_field_by_value(key, value): self._not_allowed_value(key, value) continue setattr...
def copy(self): """ Creates a copy of model """ return self.__class__(field_type=self.get_field_type(), data=self.export_data())
def get_validated_object(self, value): """ Returns the value validated by the field_type """ try: if self.get_field_type().check_value(value) or self.get_field_type().can_use_value(value): data = self.get_field_type().use_value(value) self._prepare_child(data) return data else: return None except AttributeError: return...
def get_validated_object(self, field_type, value): """ Returns the value validated by the field_type """ if field_type.check_value(value) or field_type.can_use_value(value): data = field_type.use_value(value) self._prepare_child(data) return data else: return None
def get_current_structure(self): """ Returns a dictionary with model field objects. :return: dict """ struct = self.__class__.get_structure() struct.update(self.__field_types__) return struct
def connect(self): """Connect to host """ try: self.client.connect(self.host, username=self.username, password=self.password, port=self.port, pkey=self.pkey, timeout=self.timeout) except sock_gaierror, ex: raise Exception("Unknown host '%s'" % self.host) except sock_error, ex: raise Exception("Error connecting to host ...
def exec_command(self, command, sudo=False, **kwargs): """Wrapper to paramiko.SSHClient.exec_command """ channel = self.client.get_transport().open_session() # stdin = channel.makefile('wb') stdout = channel.makefile('rb') stderr = channel.makefile_stderr('rb') if sudo: command = 'sudo -S bash -c \'%s\'' % command else...
def make_sftp(self): """Make SFTP client from open transport""" transport = self.client.get_transport() transport.open_session() return paramiko.SFTPClient.from_transport(transport)
def put(self, local, remote, sudo=False): """Copy local file to host via SFTP/SCP Copy is done natively using SFTP/SCP version 2 protocol, no scp command is used or required. """ if(os.path.isdir(local)): self.put_dir(local, remote, sudo=sudo) else: self.put_single(local, remote, sudo=sudo)
def staticbundle(bundle, mimetype=None, **attrs): """ >>> {% staticbundle 'bundlename.css' %} >>> {% staticbundle 'bundlename.css' media='screen' %} >>> {% staticbundle 'bundlename' mimetype='text/css' %} """ config = getattr(settings, 'STATIC_BUNDLES', {}) if settings.DEBUG and 'packages' in config and bundle in confi...
could not be located." % src_path) if changed: logger.info('Regenerating %s due to changes: %s', bundle, ' '.join(changed)) call_command('compilestatic', bundle) # if isinstance(src_list, dict): # src_list = src_list.values() src_list = [bundle] output = [] for src_path in src_list: url = staticfiles_storage.url(src_pa...
def str_to_time(self): """ Formats a XCCDF dateTime string to a datetime object. :returns: datetime object. :rtype: datetime.datetime """ return datetime(*list(map(int, re.split(r'-|:|T', self.time))))
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents :returns: Updated XML element :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) if hasattr(self, 'time'): self.xml_element.set('time', self.time...
def compile(pattern, flags=0, sep=None, split_prefix=False): ''' Converts a glob-matching pattern (using Apache Cocoon style rules) to a regular expression, which basically means that the following characters have special meanings: * ``?``: matches any single character excluding the separator character * ``*``: matches...
hierarchical path component separator characters. Note that although `sep` *could* be set to both forward- and back- slashes (i.e. ``"/\\"``) to, theoretically, support either unix- and windows-style path components, this has the significant flaw that then *both* characters can be used within the same path as separator...
second element remains the regex object as before. For example, the pattern ``foo/**.ini`` would result in a tuple equivalent to ``('foo/', re.compile('foo/.*\\.ini'))``. ''' prefix = None expr = '' if sep is None: sep = '/' if not sep: TypeError('invalid parameter "sep" value: %r' % (sep,)) if set(sep) & set(SPECIAL_C...
+ sep + ']' elif token[0] == Tokenizer.MULTIPLE: expr += '[^' + sep + ']*?' elif token[0] == Tokenizer.ANY: expr += '.*?' elif token[0] == Tokenizer.RANGE: expr += '[' + token[1] + ']' elif token[0] == Tokenizer.REGEX: expr += token[1] else: ValueError('unexpected token %r from globre.Tokenizer for glob: %s' % (token, ...
def parse_value(type: str, val: str): """ Parses a given OBD value of a given type (PID) and returns the parsed value. If the PID is unknown / not implemented a PIDParserUnknownError will be raised including the type which was unknown :param type: :param val: :return: """ if type.upper() in PARSER_MAP: #prep_val = prep...
def parse_obj(o): """ Parses a given dictionary with the key being the OBD PID and the value its returned value by the OBD interface :param dict o: :return: """ r = {} for k, v in o.items(): if is_unable_to_connect(v): r[k] = None try: r[k] = parse_value(k, v) except (ObdPidParserUnknownError, AttributeError, TypeError...
def parse_0101(v): """ Parses the DTC status and returns two elements. https://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_1_PID_01 :param v: :return bool, int: """ tv = trim_obd_value(v) mil_status = None # type: bool num_dtc = None # type: int try: byte_a = int(v[:2], 16) mil_status = byte_a / 0xF >= 1 num_dtc = mil_statu...
def parse_0103(v): """ Parses the fuel system status and returns an array with two elements (one for each fuel system). The returned values are converted to decimal integers and returned as is. The fuel system values are described here: https://en.wikipedia.org/wiki/OBD-II_PIDs#Mode_1_PID_03 1 Open loop due to insuffic...
status_2 = int(v[2:4], 16) except ValueError: status_2 = None return status_1, status_2
def parse_010c(v) -> int: """ Parses Engine RPM and returns it in [RPM] as a float from 0 - 16383.75 :param str v: :return int: """ try: val = int(trim_obd_value(v), 16) return int(val / 4) except ValueError: return None
def parse_0134_013b(v): """ Parses the O2 Sensor Value (0134 - 013B) and returns two values parsed from it: 1. Fuel-Air Equivalence [Ratio] as a float from 0 - 2 2. Current in [mA] as a float from -128 - 128 :param str v: :return tuple of float, float: """ try: trim_val = trim_obd_value(v) val_ab = int(trim_val[0:2], 1...
def run(debug=False): """PURPOSE: start a starcraft2 process using the defined the config parameters""" FLAGS(sys.argv) config = gameConfig.Config( version=None, # vers is None... unless a specific game version is desired themap=selectMap(ladder=True), # pick a random ladder map players=["defaulthuman", "blizzbot2_easy...
= config.interfaces interface.raw = raw # whether raw data is reported in observations interface.score = score # whether score data is reported in observations interface.feature_layer.width = 24 joinReq = sc_pb.RequestJoinGame(options=interface) # SC2APIProtocol.RequestJoinGame joinReq.race = joinRace # update joinGame...
host server.") finally: config.disable() # if the saved cfg file still exists, always remove it controller.quit()
def get_project_templates(path): " Get list of installed templates. " try: return open(op.join(path, TPLNAME)).read().strip().split(',') except IOError: raise MakesiteException("Invalid makesite-project: %s" % path)
def get_base_modules(): " Get list of installed modules. " return sorted(filter( lambda x: op.isdir(op.join(MOD_DIR, x)), listdir(MOD_DIR)))
def get_base_templates(): " Get list of installed templates. " return sorted(filter( lambda x: op.isdir(op.join(TPL_DIR, x)), listdir(TPL_DIR)))
def print_header(msg, sep='='): " More strong message " LOGGER.info("\n%s\n%s" % (msg, ''.join(sep for _ in msg)))
def which(program): " Check program is exists. " head, _ = op.split(program) if head: if is_exe(program): return program else: for path in environ["PATH"].split(pathsep): exe_file = op.join(path, program) if is_exe(exe_file): return exe_file return None
def call(cmd, shell=True, **kwargs): " Run shell command. " LOGGER.debug("Cmd: %s" % cmd) check_call(cmd, shell=shell, stdout=LOGFILE_HANDLER.stream, **kwargs)
def gen_template_files(path): " Generate relative template pathes. " path = path.rstrip(op.sep) for root, _, files in walk(path): for f in filter(lambda x: not x in (TPLNAME, CFGNAME), files): yield op.relpath(op.join(root, f), path)
def get_config( config_path=CONFIG_PATH ): """ Get the config """ parser = SafeConfigParser() parser.read( config_path ) config_dir = os.path.dirname(config_path) immutable_key = False key_id = None blockchain_id = None hostname = socket.gethostname() wallet = None if parser.has_section('blockstack-file'): if parser.ha...
def file_key_lookup( blockchain_id, index, hostname, key_id=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Get the file-encryption GPG key for the given blockchain ID, by index. if index == 0, then give back the current key if index > 0, then give back an older (revoked) key. if key_id is given, index and hostn...
in hosts_listing: log.error("Failed to list hosts for %s: %s" % (blockchain_id, hosts_listing['error'])) return {'error': 'Failed to look up hosts'} hosts = hosts_listing['hosts'] for hostname in hosts: file_key = blockstack_gpg.gpg_app_get_key( blockchain_id, APP_NAME, hostname, immutable=immutable, key_id=key_id, con...
file_key else: # get the bundle of revoked keys url = file_url_expired_keys( blockchain_id ) old_key_bundle_res = blockstack_client.data_get( url, wallet_keys=wallet_keys, proxy=proxy ) if 'error' in old_key_bundle_res: return old_key_bundle_res old_key_list = old_key_bundle_res['data']['old_keys'] if index >= len(old_...
def file_key_retire( blockchain_id, file_key, config_path=CONFIG_PATH, wallet_keys=None ): """ Retire the given key. Move it to the head of the old key bundle list @file_key should be data returned by file_key_lookup Return {'status': True} on success Return {'error': ...} on error """ config_dir = os.path.dirname(conf...
return {'error': 'Failed to append to expired key list'} return {'status': True}
def file_key_regenerate( blockchain_id, hostname, config_path=CONFIG_PATH, wallet_keys=None ): """ Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error """ config_dir = os.path.dirname(config_path) current_key = file_key_lookup( blockcha...
def file_encrypt( blockchain_id, hostname, recipient_blockchain_id_and_hosts, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Encrypt a file for a set of recipients. @recipient_blockchain_id_and_hosts must contain a list of (blockchain_id, hostname) Return {'status': True, 'se...
recipient_id} recipient_keys.append(recipient_info) # encrypt res = None with open(input_path, "r") as f: res = blockstack_gpg.gpg_encrypt( f, output_path, key_info, recipient_keys, passphrase=passphrase, config_dir=config_dir ) if 'error' in res: log.error("Failed to encrypt: %s" % res['error']) return {'error': 'Fail...
def file_decrypt_from_key_info( sender_key_info, blockchain_id, key_index, hostname, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Try to decrypt data with one of the receiver's keys Return {'status': True} if we succeeded Return {'error': ..., 'status': False} if we failed ...
% my_key_info['key_id']) return {'status': True, 'error': 'Failed to decrypt with key'} else: log.error("Failed to decrypt: %s" % res['error']) return {'status': False, 'error': 'GPG error (%s)' % res['error']} return {'status': True}
def file_decrypt( blockchain_id, hostname, sender_blockchain_id, sender_key_id, input_path, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Decrypt a file from a sender's blockchain ID. Try our current key, and then the old keys (but warn if there are revoked keys) Return {'status': True}...
config_path=config_path, wallet_keys=wallet_keys ) if 'error' not in key_info: res = file_decrypt_from_key_info( sender_key_info, blockchain_id, 0, hostname, input_path, output_path, passphrase=passphrase, config_path=config_path, wallet_keys=wallet_keys ) if 'error' in res: if not res['status']: # permanent failure lo...
ret = {'status': True} if old_key: ret['warning'] = "Used stale key" ret['stale_key_index'] = old_key_index ret['stale_sender_key_index'] = sender_old_key_index return ret else: return {'error': 'No keys could decrypt'}
def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Sign a file with the current blockchain ID's host's public key. @config_path should be for the *client*, not blockstack-file Return {'status': True, 'sender_key_id': ..., 'sig': ...} on success, and wri...
def file_verify( sender_blockchain_id, sender_key_id, input_path, sig, config_path=CONFIG_PATH, wallet_keys=None ): """ Verify that a file was signed with the given blockchain ID @config_path should be for the *client*, not blockstack-file Return {'status': True} on succes Return {'error': ...} on error """ config_dir ...
True}
def file_list_hosts( blockchain_id, wallet_keys=None, config_path=CONFIG_PATH ): """ Given a blockchain ID, find out the hosts the blockchain ID owner has registered keys for. Return {'status': True, 'hosts': hostnames} on success Return {'error': ...} on failure """ config_dir = os.path.dirname(config_path) try: ret =...
def file_put( blockchain_id, hostname, recipient_blockchain_ids, data_name, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Send a file to the given recipient, encrypted and signed with the given blockchain ID. Allow each recipient to receive the data on each of their hosts. Return {'statu...
make available to all hosts for each recipient for recipient_blockchain_id in recipient_blockchain_ids: their_hosts = file_list_hosts( recipient_blockchain_id, wallet_keys=wallet_keys, config_path=config_path ) if 'error' in their_hosts: log.error("Failed to list hosts for %s: %s" % (recipient_blockchain_id, their_host...
log.error("Failed to put data: %s" % res['error']) os.unlink(output_path) return {'error': 'Failed to replicate data'} os.unlink(output_path) return {'status': True}
def file_get( blockchain_id, hostname, sender_blockchain_id, data_name, output_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Get a file from a known sender. Store it to output_path Return {'status': True} on success Return {'error': error} on failure """ config_dir = os.path.dirname(config_pat...
if 'error' in res: log.error("Failed to decrypt: %s" % res['error']) return {'error': 'Failed to decrypt data'} else: # success! return res
def file_delete( blockchain_id, data_name, config_path=CONFIG_PATH, wallet_keys=None ): """ Remove a file Return {'status': True} on success Return {'error': error} on failure """ config_dir = os.path.dirname(config_path) client_config_path = os.path.join(config_dir, blockstack_client.CONFIG_FILENAME ) proxy = blocksta...
def file_list( blockchain_id, config_path=CONFIG_PATH, wallet_keys=None ): """ List all files uploaded to a particular blockchain ID Return {'status': True, 'listing': list} on success Return {'error': ...} on error """ config_dir = os.path.dirname(config_path) client_config_path = os.path.join(config_dir, blockstack_c...
def main(): """ Entry point for the CLI interface """ argparser = argparse.ArgumentParser( description='Blockstack-file version {}'.format(__version__)) subparsers = argparser.add_subparsers( dest='action', help='The file command to take [get/put/delete]') parser = subparsers.add_parser( 'init', help='Initialize this h...
(default is %s)' % CONFIG_PATH) parser.add_argument( '--blockchain_id', action='store', help='the recipient blockchain ID to use'), parser.add_argument( '--hostname', action='store', help='the recipient hostname to use') parser.add_argument( '--passphrase', action='store', help='decryption passphrase') parser.add_argum...
'data_name', action='store', help='Public name of the file to store') # recipients come afterwards parser = subparsers.add_parser( 'delete', help='Delete a shared file') parser.add_argument( '--config', action='store', help='path to the config file to use (default is %s)' % CONFIG_PATH) parser.add_argument( '--blockcha...
conf['blockchain_id'] if hostname is None: hostname = conf['hostname'] if wallet_path is None: wallet_path = conf['wallet'] if wallet_path is None and config_dir is not None: wallet_path = os.path.join(config_dir, blockstack_client.config.WALLET_FILENAME) # load wallet if wallet_path is not None and os.path.exists( wal...
args.action == 'get': # get a file sender_blockchain_id = args.sender_blockchain_id output_path = args.output_path tmp = False if output_path is None: fd, path = tempfile.mkstemp( prefix='blockstack-file-', dir=config_dir ) os.close(fd) output_path = path tmp = True res = file_get( blockchain_id, hostname, sender_block...
= file_delete( blockchain_id, data_name, config_path=config_path, wallet_keys=wallet ) if 'error' in res: print >> sys.stderr, json.dumps(res, sort_keys=True, indent=4 ) sys.exit(1) print >> sys.stderr, json.dumps({'status': True}, sort_keys=True, indent=4 ) sys.exit(0)
def cancelMatchRequest(cfg): """obtain information housed on the ladder about playerName""" payload = json.dumps([cfg.thePlayer]) ladder = cfg.ladder return requests.post( url = c.URL_BASE%(ladder.ipAddress, ladder.serverPort, "cancelmatch"), data = payload, #headers=headers, )
def ladderPlayerInfo(cfg, playerName, getMatchHistory=False): """obtain information housed on the ladder about playerName""" payload = json.dumps([playerName, getMatchHistory]) # if playerName == None, info on all players is retrieved ladder = cfg.ladder return requests.post( url = c.URL_BASE%(ladder.ipAddress, ladder....
def reportMatchCompletion(cfg, results, replayData): """send information back to the server about the match's winners/losers""" payload = json.dumps([cfg.flatten(), results, replayData]) ladder = cfg.ladder return requests.post( url = c.URL_BASE%(ladder.ipAddress, ladder.serverPort, "matchfinished"), data = payload, #h...
def process_response(self, request, response): """ Adds WWW-Authenticate: Basic headers to 401 responses, and rewrites redirects the login page to be 401 responses if it's a non-browser agent. """ process = False # Don't do anything for unsecure requests, unless DEBUG is on if not self.allow_http and not request.is_sec...
authenticate = 'Basic realm="%s"' % realm response['WWW-Authenticate'] = authenticate return response
def verbose_print(message, *, operation, verbosity): """ Prints *message* to stderr only if the given *operation* is in the list *verbosity*. If "all" is in *verbosity*, all operations are printed. **Parameters** message : str The message to print. operation : str The type of operation being performed. verbosity : [str...
def pmap(func, args, processes=None, callback=lambda *_, **__: None, **kwargs): """pmap(func, args, processes=None, callback=do_nothing, **kwargs) Parallel equivalent of ``map(func, args)``, with the additional ability of providing keyword arguments to func, and a callback function which is applied to each element in t...
of ``func(arg)`` for each *arg* in *args* (default do_nothing). kwargs : dict Extra keyword arguments are unpacked in each call of *func*. **Returns** results : list A list equivalent to ``[func(x, **kwargs) for x in args]``. """ if processes is 1: results = [] for arg in args: result = func(arg, **kwargs) results.appe...
def mad(data, axis=None): """ Computes the median absolute deviation of *data* along a given *axis*. See `link <https://en.wikipedia.org/wiki/Median_absolute_deviation>`_ for details. **Parameters** data : array-like **Returns** mad : number or array-like """ return median(absolute(data - median(data, axis)), axis)
def autocorrelation(X, lag=1): """ Computes the autocorrelation of *X* with the given *lag*. Autocorrelation is simply autocovariance(X) / covariance(X-mean, X-mean), where autocovariance is simply covariance((X-mean)[:-lag], (X-mean)[lag:]). See `link <https://en.wikipedia.org/wiki/Autocorrelation>`_ for details. **Pa...
def sanitize_latex(string): """ Sanitize a string for input to LaTeX. Replacements taken from `Stack Overflow <http://stackoverflow.com/questions/2627135/how-do-i-sanitize-latex-input>`_ **Parameters** string: str **Returns** sanitized_string: str """ sanitized_string = string for old, new in _latex_replacements: sanit...
def get_renderers(self, request, context=None, template_name=None, accept_header=None, formats=None, default_format=None, fallback_formats=None, early=False): """ Returns a list of renderer functions in the order they should be tried. Tries the format override parameter first, then the Accept header. If neither is pres...
renderers = [] fallback_formats = fallback_formats if isinstance(fallback_formats, (list, tuple)) else (fallback_formats,) for format in fallback_formats: for renderer in self.renderers_by_format[format]: if renderer not in renderers: renderers.append(renderer) if not early and context is not None and template_name: re...
def register_app(app): " Configure application. " from .views import users app.register_blueprint(users) from .oauth import config_oauth config_oauth(app)
def set_secret_key(token): """ Initializes a Authentication and sets it as the new default global authentication. It also performs some checks before saving the authentication. :Example >>> # Expected format for secret key: >>> import payplug >>> payplug.set_secret_key('sk_test_somerandomcharacters') :param token: your...
def retrieve(payment_id): """ Retrieve a payment from its id. :param payment_id: The payment id :type payment_id: string :return: The payment resource :rtype: resources.Payment """ http_client = HttpClient() response, __ = http_client.get(routes.url(routes.PAYMENT_RESOURCE, resource_id=payment_id)) return resources.Pay...
def abort(payment): """ Abort a payment from its id. :param payment: The payment id or payment object :type payment: string|Payment :return: The payment resource :rtype: resources.Payment """ if isinstance(payment, resources.Payment): payment = payment.id http_client = HttpClient() response, __ = http_client.patch(rout...