idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
55,800 | def transfer ( self , user ) : r = self . _h . _http_resource ( method = 'PUT' , resource = ( 'apps' , self . name ) , data = { 'app[transfer_owner]' : user } ) return r . ok | Transfers app to given username s account . |
55,801 | def maintenance ( self , on = True ) : r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . name , 'server' , 'maintenance' ) , data = { 'maintenance_mode' : int ( on ) } ) return r . ok | Toggles maintenance mode . |
55,802 | def destroy ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'apps' , self . name ) ) return r . ok | Destoys the app . Do be careful . |
55,803 | def logs ( self , num = None , source = None , ps = None , tail = False ) : payload = { 'logplex' : 'true' } if num : payload [ 'num' ] = num if source : payload [ 'source' ] = source if ps : payload [ 'ps' ] = ps if tail : payload [ 'tail' ] = 1 r = self . _h . _http_resource ( method = 'GET' , resource = ( 'apps' , self . name , 'logs' ) , data = payload ) r = requests . get ( r . content . decode ( "utf-8" ) , verify = False , stream = True ) if not tail : return r . content else : return r . iter_lines ( ) | Returns the requested log . |
55,804 | def delete ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'user' , 'keys' , self . id ) ) r . raise_for_status ( ) | Deletes the key . |
55,805 | def restart ( self , all = False ) : if all : data = { 'type' : self . type } else : data = { 'ps' : self . process } r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . app . name , 'ps' , 'restart' ) , data = data ) r . raise_for_status ( ) | Restarts the given process . |
55,806 | def scale ( self , quantity ) : r = self . _h . _http_resource ( method = 'POST' , resource = ( 'apps' , self . app . name , 'ps' , 'scale' ) , data = { 'type' : self . type , 'qty' : quantity } ) r . raise_for_status ( ) try : return self . app . processes [ self . type ] except KeyError : return ProcessListResource ( ) | Scales the given process to the given number of dynos . |
55,807 | def is_collection ( obj ) : col = getattr ( obj , '__getitem__' , False ) val = False if ( not col ) else True if isinstance ( obj , basestring ) : val = False return val | Tests if an object is a collection . |
55,808 | def to_python ( obj , in_dict , str_keys = None , date_keys = None , int_keys = None , object_map = None , bool_keys = None , dict_keys = None , ** kwargs ) : d = dict ( ) if str_keys : for in_key in str_keys : d [ in_key ] = in_dict . get ( in_key ) if date_keys : for in_key in date_keys : in_date = in_dict . get ( in_key ) try : out_date = parse_datetime ( in_date ) except TypeError as e : raise e out_date = None d [ in_key ] = out_date if int_keys : for in_key in int_keys : if ( in_dict is not None ) and ( in_dict . get ( in_key ) is not None ) : d [ in_key ] = int ( in_dict . get ( in_key ) ) if bool_keys : for in_key in bool_keys : if in_dict . get ( in_key ) is not None : d [ in_key ] = bool ( in_dict . get ( in_key ) ) if dict_keys : for in_key in dict_keys : if in_dict . get ( in_key ) is not None : d [ in_key ] = dict ( in_dict . get ( in_key ) ) if object_map : for ( k , v ) in object_map . items ( ) : if in_dict . get ( k ) : d [ k ] = v . new_from_dict ( in_dict . get ( k ) ) obj . __dict__ . update ( d ) obj . __dict__ . update ( kwargs ) return obj | Extends a given object for API Consumption . |
55,809 | def to_api ( in_dict , int_keys = None , date_keys = None , bool_keys = None ) : if int_keys : for in_key in int_keys : if ( in_key in in_dict ) and ( in_dict . get ( in_key , None ) is not None ) : in_dict [ in_key ] = int ( in_dict [ in_key ] ) if date_keys : for in_key in date_keys : if ( in_key in in_dict ) and ( in_dict . get ( in_key , None ) is not None ) : _from = in_dict [ in_key ] if isinstance ( _from , basestring ) : dtime = parse_datetime ( _from ) elif isinstance ( _from , datetime ) : dtime = _from in_dict [ in_key ] = dtime . isoformat ( ) elif ( in_key in in_dict ) and in_dict . get ( in_key , None ) is None : del in_dict [ in_key ] for k , v in in_dict . items ( ) : if v is None : del in_dict [ k ] return in_dict | Extends a given object for API Production . |
55,810 | def clear ( self ) : r = self . _h . _http_resource ( method = 'DELETE' , resource = ( 'user' , 'keys' ) , ) return r . ok | Removes all SSH keys from a user s system . |
55,811 | def authenticate ( self , api_key ) : self . _api_key = api_key self . _session . auth = ( '' , self . _api_key ) return self . _verify_api_key ( ) | Logs user into Heroku with given api_key . |
55,812 | def _get_resource ( self , resource , obj , params = None , ** kwargs ) : r = self . _http_resource ( 'GET' , resource , params = params ) item = self . _resource_deserialize ( r . content . decode ( "utf-8" ) ) return obj . new_from_dict ( item , h = self , ** kwargs ) | Returns a mapped object from an HTTP resource . |
55,813 | def _get_resources ( self , resource , obj , params = None , map = None , ** kwargs ) : r = self . _http_resource ( 'GET' , resource , params = params ) d_items = self . _resource_deserialize ( r . content . decode ( "utf-8" ) ) items = [ obj . new_from_dict ( item , h = self , ** kwargs ) for item in d_items ] if map is None : map = KeyedListResource list_resource = map ( items = items ) list_resource . _h = self list_resource . _obj = obj list_resource . _kwargs = kwargs return list_resource | Returns a list of mapped objects from an HTTP resource . |
55,814 | def from_key ( api_key , ** kwargs ) : h = Heroku ( ** kwargs ) h . authenticate ( api_key ) return h | Returns an authenticated Heroku instance via API Key . |
55,815 | def abbrev ( self , dev_suffix = "" ) : return '.' . join ( str ( el ) for el in self . release ) + ( dev_suffix if self . commit_count > 0 or self . dirty else "" ) | Abbreviated string representation optionally declaring whether it is a development version . |
55,816 | def verify ( self , string_version = None ) : if string_version and string_version != str ( self ) : raise Exception ( "Supplied string version does not match current version." ) if self . dirty : raise Exception ( "Current working directory is dirty." ) if self . release != self . expected_release : raise Exception ( "Declared release does not match current release tag." ) if self . commit_count != 0 : raise Exception ( "Please update the VCS version tag before release." ) if self . _expected_commit not in [ None , "$Format:%h$" ] : raise Exception ( "Declared release does not match the VCS version tag" ) | Check that the version information is consistent with the VCS before doing a release . If supplied with a string version this is also checked against the current version . Should be called from setup . py with the declared package version before releasing to PyPI . |
55,817 | def _check_time_fn ( self , time_instance = False ) : if time_instance and not isinstance ( self . time_fn , param . Time ) : raise AssertionError ( "%s requires a Time object" % self . __class__ . __name__ ) if self . time_dependent : global_timefn = self . time_fn is param . Dynamic . time_fn if global_timefn and not param . Dynamic . time_dependent : raise AssertionError ( "Cannot use Dynamic.time_fn as" " parameters are ignoring time." ) | If time_fn is the global time function supplied by param . Dynamic . time_fn make sure Dynamic parameters are using this time function to control their behaviour . |
55,818 | def _rational ( self , val ) : I32 = 4294967296 if isinstance ( val , int ) : numer , denom = val , 1 elif isinstance ( val , fractions . Fraction ) : numer , denom = val . numerator , val . denominator elif hasattr ( val , 'numer' ) : ( numer , denom ) = ( int ( val . numer ( ) ) , int ( val . denom ( ) ) ) else : param . main . param . warning ( "Casting type '%s' to Fraction.fraction" % type ( val ) . __name__ ) frac = fractions . Fraction ( str ( val ) ) numer , denom = frac . numerator , frac . denominator return numer % I32 , denom % I32 | Convert the given value to a rational if necessary . |
55,819 | def _initialize_random_state ( self , seed = None , shared = True , name = None ) : if seed is None : seed = random . Random ( ) . randint ( 0 , 1000000 ) suffix = '' else : suffix = str ( seed ) if self . time_dependent or not shared : self . random_generator = type ( self . random_generator ) ( seed ) if not shared : self . random_generator . seed ( seed ) if name is None : self . _verify_constrained_hash ( ) hash_name = name if name else self . name if not shared : hash_name += suffix self . _hashfn = Hash ( hash_name , input_count = 2 ) if self . time_dependent : self . _hash_and_seed ( ) | Initialization method to be called in the constructor of subclasses to initialize the random state correctly . |
55,820 | def _verify_constrained_hash ( self ) : changed_params = dict ( self . param . get_param_values ( onlychanged = True ) ) if self . time_dependent and ( 'name' not in changed_params ) : self . param . warning ( "Default object name used to set the seed: " "random values conditional on object instantiation order." ) | Warn if the object name is not explicitly set . |
55,821 | def get_setup_version ( reponame ) : from param . version import Version return Version . setup_version ( os . path . dirname ( __file__ ) , reponame , archive_commit = "$Format:%h$" ) | Use autover to get up to date version . |
55,822 | def get_param_info ( self , obj , include_super = True ) : params = dict ( obj . param . objects ( 'existing' ) ) if isinstance ( obj , type ) : changed = [ ] val_dict = dict ( ( k , p . default ) for ( k , p ) in params . items ( ) ) self_class = obj else : changed = [ name for ( name , _ ) in obj . param . get_param_values ( onlychanged = True ) ] val_dict = dict ( obj . param . get_param_values ( ) ) self_class = obj . __class__ if not include_super : params = dict ( ( k , v ) for ( k , v ) in params . items ( ) if k in self_class . __dict__ ) params . pop ( 'name' ) return ( params , val_dict , changed ) | Get the parameter dictionary the list of modifed parameters and the dictionary or parameter values . If include_super is True parameters are also collected from the super classes . |
55,823 | def _build_table ( self , info , order , max_col_len = 40 , only_changed = False ) : info_dict , bounds_dict = { } , { } ( params , val_dict , changed ) = info col_widths = dict ( ( k , 0 ) for k in order ) for name , p in params . items ( ) : if only_changed and not ( name in changed ) : continue constant = 'C' if p . constant else 'V' readonly = 'RO' if p . readonly else 'RW' allow_None = ' AN' if hasattr ( p , 'allow_None' ) and p . allow_None else '' mode = '%s %s%s' % ( constant , readonly , allow_None ) info_dict [ name ] = { 'name' : name , 'type' : p . __class__ . __name__ , 'mode' : mode } if hasattr ( p , 'bounds' ) : lbound , ubound = ( None , None ) if p . bounds is None else p . bounds mark_lbound , mark_ubound = False , False if hasattr ( p , 'get_soft_bounds' ) : soft_lbound , soft_ubound = p . get_soft_bounds ( ) if lbound is None and soft_lbound is not None : lbound = soft_lbound mark_lbound = True if ubound is None and soft_ubound is not None : ubound = soft_ubound mark_ubound = True if ( lbound , ubound ) != ( None , None ) : bounds_dict [ name ] = ( mark_lbound , mark_ubound ) info_dict [ name ] [ 'bounds' ] = '(%s, %s)' % ( lbound , ubound ) value = repr ( val_dict [ name ] ) if len ( value ) > ( max_col_len - 3 ) : value = value [ : max_col_len - 3 ] + '...' info_dict [ name ] [ 'value' ] = value for col in info_dict [ name ] : max_width = max ( [ col_widths [ col ] , len ( info_dict [ name ] [ col ] ) ] ) col_widths [ col ] = max_width return self . _tabulate ( info_dict , col_widths , changed , order , bounds_dict ) | Collect the information about parameters needed to build a properly formatted table and then tabulate it . |
55,824 | def _tabulate ( self , info_dict , col_widths , changed , order , bounds_dict ) : contents , tail = [ ] , [ ] column_set = set ( k for row in info_dict . values ( ) for k in row ) columns = [ col for col in order if col in column_set ] title_row = [ ] for i , col in enumerate ( columns ) : width = col_widths [ col ] + 2 col = col . capitalize ( ) formatted = col . ljust ( width ) if i == 0 else col . center ( width ) title_row . append ( formatted ) contents . append ( blue % '' . join ( title_row ) + "\n" ) for row in sorted ( info_dict ) : row_list = [ ] info = info_dict [ row ] for i , col in enumerate ( columns ) : width = col_widths [ col ] + 2 val = info [ col ] if ( col in info ) else '' formatted = val . ljust ( width ) if i == 0 else val . center ( width ) if col == 'bounds' and bounds_dict . get ( row , False ) : ( mark_lbound , mark_ubound ) = bounds_dict [ row ] lval , uval = formatted . rsplit ( ',' ) lspace , lstr = lval . rsplit ( '(' ) ustr , uspace = uval . rsplit ( ')' ) lbound = lspace + '(' + ( cyan % lstr ) if mark_lbound else lval ubound = ( cyan % ustr ) + ')' + uspace if mark_ubound else uval formatted = "%s,%s" % ( lbound , ubound ) row_list . append ( formatted ) row_text = '' . join ( row_list ) if row in changed : row_text = red % row_text contents . append ( row_text ) return '\n' . join ( contents + tail ) | Returns the supplied information as a table suitable for printing or paging . |
55,825 | def is_ordered_dict ( d ) : py3_ordered_dicts = ( sys . version_info . major == 3 ) and ( sys . version_info . minor >= 6 ) vanilla_odicts = ( sys . version_info . major > 3 ) or py3_ordered_dicts return isinstance ( d , ( OrderedDict ) ) or ( vanilla_odicts and isinstance ( d , dict ) ) | Predicate checking for ordered dictionaries . OrderedDict is always ordered and vanilla Python dictionaries are ordered for Python 3 . 6 + |
55,826 | def named_objs ( objlist , namesdict = None ) : objs = OrderedDict ( ) if namesdict is not None : objtoname = { hashable ( v ) : k for k , v in namesdict . items ( ) } for obj in objlist : if namesdict is not None and hashable ( obj ) in objtoname : k = objtoname [ hashable ( obj ) ] elif hasattr ( obj , "name" ) : k = obj . name elif hasattr ( obj , '__name__' ) : k = obj . __name__ else : k = as_unicode ( obj ) objs [ k ] = obj return objs | Given a list of objects returns a dictionary mapping from string name for the object to the object itself . Accepts an optional name obj dictionary which will override any other name if that item is present in the dictionary . |
55,827 | def guess_param_types ( ** kwargs ) : params = { } for k , v in kwargs . items ( ) : kws = dict ( default = v , constant = True ) if isinstance ( v , Parameter ) : params [ k ] = v elif isinstance ( v , dt_types ) : params [ k ] = Date ( ** kws ) elif isinstance ( v , bool ) : params [ k ] = Boolean ( ** kws ) elif isinstance ( v , int ) : params [ k ] = Integer ( ** kws ) elif isinstance ( v , float ) : params [ k ] = Number ( ** kws ) elif isinstance ( v , str ) : params [ k ] = String ( ** kws ) elif isinstance ( v , dict ) : params [ k ] = Dict ( ** kws ) elif isinstance ( v , tuple ) : if all ( _is_number ( el ) for el in v ) : params [ k ] = NumericTuple ( ** kws ) elif all ( isinstance ( el . dt_types ) for el in v ) and len ( v ) == 2 : params [ k ] = DateRange ( ** kws ) else : params [ k ] = Tuple ( ** kws ) elif isinstance ( v , list ) : params [ k ] = List ( ** kws ) elif isinstance ( v , np . ndarray ) : params [ k ] = Array ( ** kws ) else : from pandas import DataFrame as pdDFrame from pandas import Series as pdSeries if isinstance ( v , pdDFrame ) : params [ k ] = DataFrame ( ** kws ) elif isinstance ( v , pdSeries ) : params [ k ] = Series ( ** kws ) else : params [ k ] = Parameter ( ** kws ) return params | Given a set of keyword literals promote to the appropriate parameter type based on some simple heuristics . |
55,828 | def guess_bounds ( params , ** overrides ) : guessed = { } for name , p in params . items ( ) : new_param = copy . copy ( p ) if isinstance ( p , ( Integer , Number ) ) : if name in overrides : minv , maxv = overrides [ name ] else : minv , maxv , _ = _get_min_max_value ( None , None , value = p . default ) new_param . bounds = ( minv , maxv ) guessed [ name ] = new_param return guessed | Given a dictionary of Parameter instances return a corresponding set of copies with the bounds appropriately set . |
55,829 | def _initialize_generator ( self , gen , obj = None ) : if hasattr ( obj , "_Dynamic_time_fn" ) : gen . _Dynamic_time_fn = obj . _Dynamic_time_fn gen . _Dynamic_last = None gen . _Dynamic_time = - 1 gen . _saved_Dynamic_last = [ ] gen . _saved_Dynamic_time = [ ] | Add last time and last value attributes to the generator . |
55,830 | def _produce_value ( self , gen , force = False ) : if hasattr ( gen , "_Dynamic_time_fn" ) : time_fn = gen . _Dynamic_time_fn else : time_fn = self . time_fn if ( time_fn is None ) or ( not self . time_dependent ) : value = produce_value ( gen ) gen . _Dynamic_last = value else : time = time_fn ( ) if force or time != gen . _Dynamic_time : value = produce_value ( gen ) gen . _Dynamic_last = value gen . _Dynamic_time = time else : value = gen . _Dynamic_last return value | Return a value from gen . |
55,831 | def _inspect ( self , obj , objtype = None ) : gen = super ( Dynamic , self ) . __get__ ( obj , objtype ) if hasattr ( gen , '_Dynamic_last' ) : return gen . _Dynamic_last else : return gen | Return the last generated value for this parameter . |
55,832 | def _force ( self , obj , objtype = None ) : gen = super ( Dynamic , self ) . __get__ ( obj , objtype ) if hasattr ( gen , '_Dynamic_last' ) : return self . _produce_value ( gen , force = True ) else : return gen | Force a new value to be generated and return it . |
55,833 | def set_in_bounds ( self , obj , val ) : if not callable ( val ) : bounded_val = self . crop_to_bounds ( val ) else : bounded_val = val super ( Number , self ) . __set__ ( obj , bounded_val ) | Set to the given value but cropped to be within the legal bounds . All objects are accepted and no exceptions will be raised . See crop_to_bounds for details on how cropping is done . |
55,834 | def crop_to_bounds ( self , val ) : if _is_number ( val ) : if self . bounds is None : return val vmin , vmax = self . bounds if vmin is not None : if val < vmin : return vmin if vmax is not None : if val > vmax : return vmax elif self . allow_None and val is None : return val else : return self . default return val | Return the given value cropped to be within the hard bounds for this parameter . |
55,835 | def _validate ( self , val ) : if not self . check_on_set : self . _ensure_value_is_in_objects ( val ) return if not ( val in self . objects or ( self . allow_None and val is None ) ) : try : attrib_name = self . name except AttributeError : attrib_name = "" items = [ ] limiter = ']' length = 0 for item in self . objects : string = str ( item ) length += len ( string ) if length < 200 : items . append ( string ) else : limiter = ', ...]' break items = '[' + ', ' . join ( items ) + limiter raise ValueError ( "%s not in Parameter %s's list of possible objects, " "valid options include %s" % ( val , attrib_name , items ) ) | val must be None or one of the objects in self . objects . |
55,836 | def _ensure_value_is_in_objects ( self , val ) : if not ( val in self . objects ) : self . objects . append ( val ) | Make sure that the provided value is present on the objects list . Subclasses can override if they support multiple items on a list to check each item instead . |
55,837 | def _validate ( self , val ) : if isinstance ( self . class_ , tuple ) : class_name = ( '(%s)' % ', ' . join ( cl . __name__ for cl in self . class_ ) ) else : class_name = self . class_ . __name__ if self . is_instance : if not ( isinstance ( val , self . class_ ) ) and not ( val is None and self . allow_None ) : raise ValueError ( "Parameter '%s' value must be an instance of %s, not '%s'" % ( self . name , class_name , val ) ) else : if not ( val is None and self . allow_None ) and not ( issubclass ( val , self . class_ ) ) : raise ValueError ( "Parameter '%s' must be a subclass of %s, not '%s'" % ( val . __name__ , class_name , val . __class__ . __name__ ) ) | val must be None an instance of self . class_ if self . is_instance = True or a subclass of self_class if self . is_instance = False |
55,838 | def get_range ( self ) : classes = concrete_descendents ( self . class_ ) d = OrderedDict ( ( name , class_ ) for name , class_ in classes . items ( ) ) if self . allow_None : d [ 'None' ] = None return d | Return the possible types for this parameter s value . |
55,839 | def _validate ( self , val ) : if self . allow_None and val is None : return if not isinstance ( val , list ) : raise ValueError ( "List '%s' must be a list." % ( self . name ) ) if self . bounds is not None : min_length , max_length = self . bounds l = len ( val ) if min_length is not None and max_length is not None : if not ( min_length <= l <= max_length ) : raise ValueError ( "%s: list length must be between %s and %s (inclusive)" % ( self . name , min_length , max_length ) ) elif min_length is not None : if not min_length <= l : raise ValueError ( "%s: list length must be at least %s." % ( self . name , min_length ) ) elif max_length is not None : if not l <= max_length : raise ValueError ( "%s: list length must be at most %s." % ( self . name , max_length ) ) self . _check_type ( val ) | Checks that the list is of the right length and has the right contents . Otherwise an exception is raised . |
55,840 | def logging_level ( level ) : level = level . upper ( ) levels = [ DEBUG , INFO , WARNING , ERROR , CRITICAL , VERBOSE ] level_names = [ 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' , 'CRITICAL' , 'VERBOSE' ] if level not in level_names : raise Exception ( "Level %r not in %r" % ( level , levels ) ) param_logger = get_logger ( ) logging_level = param_logger . getEffectiveLevel ( ) param_logger . setLevel ( levels [ level_names . index ( level ) ] ) try : yield None finally : param_logger . setLevel ( logging_level ) | Temporarily modify param s logging level . |
55,841 | def batch_watch ( parameterized , run = True ) : BATCH_WATCH = parameterized . param . _BATCH_WATCH parameterized . param . _BATCH_WATCH = True try : yield finally : parameterized . param . _BATCH_WATCH = BATCH_WATCH if run and not BATCH_WATCH : parameterized . param . _batch_call_watchers ( ) | Context manager to batch watcher events on a parameterized object . The context manager will queue any events triggered by setting a parameter on the supplied parameterized object and dispatch them all at once when the context manager exits . If run = False the queued events are not dispatched and should be processed manually . |
55,842 | def get_all_slots ( class_ ) : all_slots = [ ] parent_param_classes = [ c for c in classlist ( class_ ) [ 1 : : ] ] for c in parent_param_classes : if hasattr ( c , '__slots__' ) : all_slots += c . __slots__ return all_slots | Return a list of slot names for slots defined in class_ and its superclasses . |
55,843 | def get_occupied_slots ( instance ) : return [ slot for slot in get_all_slots ( type ( instance ) ) if hasattr ( instance , slot ) ] | Return a list of slots for which values have been set . |
55,844 | def all_equal ( arg1 , arg2 ) : if all ( hasattr ( el , '_infinitely_iterable' ) for el in [ arg1 , arg2 ] ) : return arg1 == arg2 try : return all ( a1 == a2 for a1 , a2 in zip ( arg1 , arg2 ) ) except TypeError : return arg1 == arg2 | Return a single boolean for arg1 == arg2 even for numpy arrays using element - wise comparison . |
55,845 | def output ( func , * output , ** kw ) : if output : outputs = [ ] for i , out in enumerate ( output ) : i = i if len ( output ) > 1 else None if isinstance ( out , tuple ) and len ( out ) == 2 and isinstance ( out [ 0 ] , str ) : outputs . append ( out + ( i , ) ) elif isinstance ( out , str ) : outputs . append ( ( out , Parameter ( ) , i ) ) else : outputs . append ( ( None , out , i ) ) elif kw : py_major = sys . version_info . major py_minor = sys . version_info . minor if ( py_major < 3 or ( py_major == 3 and py_minor < 6 ) ) and len ( kw ) > 1 : raise ValueError ( 'Multiple output declaration using keywords ' 'only supported in Python >= 3.6.' ) outputs = [ ( name , otype , i if len ( kw ) > 1 else None ) for i , ( name , otype ) in enumerate ( kw . items ( ) ) ] else : outputs = [ ( None , Parameter ( ) , None ) ] names , processed = [ ] , [ ] for name , otype , i in outputs : if isinstance ( otype , type ) : if issubclass ( otype , Parameter ) : otype = otype ( ) else : from . import ClassSelector otype = ClassSelector ( class_ = otype ) elif isinstance ( otype , tuple ) and all ( isinstance ( t , type ) for t in otype ) : from . import ClassSelector otype = ClassSelector ( class_ = otype ) if not isinstance ( otype , Parameter ) : raise ValueError ( 'output type must be declared with a Parameter class, ' 'instance or a Python object type.' ) processed . append ( ( name , otype , i ) ) names . append ( name ) if len ( set ( names ) ) != len ( names ) : raise ValueError ( 'When declaring multiple outputs each value ' 'must be unique.' ) _dinfo = getattr ( func , '_dinfo' , { } ) _dinfo . update ( { 'outputs' : processed } ) @ wraps ( func ) def _output ( * args , ** kw ) : return func ( * args , ** kw ) _output . _dinfo = _dinfo return _output | output allows annotating a method on a Parameterized class to declare that it returns an output of a specific type . The outputs of a Parameterized class can be queried using the Parameterized . param . outputs method . By default the output will inherit the method name but a custom name can be declared by expressing the Parameter type using a keyword argument . Declaring multiple return types using keywords is only supported in Python > = 3 . 6 . |
55,846 | def _setup_params ( self_ , ** params ) : self = self_ . param . self params_to_instantiate = { } for class_ in classlist ( type ( self ) ) : if not issubclass ( class_ , Parameterized ) : continue for ( k , v ) in class_ . __dict__ . items ( ) : if isinstance ( v , Parameter ) and v . instantiate and k != "name" : params_to_instantiate [ k ] = v for p in params_to_instantiate . values ( ) : self . param . _instantiate_param ( p ) for name , val in params . items ( ) : desc = self . __class__ . get_param_descriptor ( name ) [ 0 ] if not desc : self . param . warning ( "Setting non-parameter attribute %s=%s using a mechanism intended only for parameters" , name , val ) setattr ( self , name , val ) | Initialize default and keyword parameter values . |
55,847 | def deprecate ( cls , fn ) : def inner ( * args , ** kwargs ) : if cls . _disable_stubs : raise AssertionError ( 'Stubs supporting old API disabled' ) elif cls . _disable_stubs is None : pass elif cls . _disable_stubs is False : get_logger ( name = args [ 0 ] . __class__ . __name__ ) . log ( WARNING , 'Use method %r via param namespace ' % fn . __name__ ) return fn ( * args , ** kwargs ) inner . __doc__ = "Inspect .param.%s method for the full docstring" % fn . __name__ return inner | Decorator to issue warnings for API moving onto the param namespace and to add a docstring directing people to the appropriate method . |
55,848 | def print_param_defaults ( self_ ) : cls = self_ . cls for key , val in cls . __dict__ . items ( ) : if isinstance ( val , Parameter ) : print ( cls . __name__ + '.' + key + '=' + repr ( val . default ) ) | Print the default values of all cls s Parameters . |
55,849 | def set_default ( self_ , param_name , value ) : cls = self_ . cls setattr ( cls , param_name , value ) | Set the default value of param_name . |
55,850 | def _add_parameter ( self_ , param_name , param_obj ) : cls = self_ . cls type . __setattr__ ( cls , param_name , param_obj ) ParameterizedMetaclass . _initialize_parameter ( cls , param_name , param_obj ) try : delattr ( cls , '_%s__params' % cls . __name__ ) except AttributeError : pass | Add a new Parameter object into this object s class . |
55,851 | def set_param ( self_ , * args , ** kwargs ) : BATCH_WATCH = self_ . self_or_cls . param . _BATCH_WATCH self_ . self_or_cls . param . _BATCH_WATCH = True self_or_cls = self_ . self_or_cls if args : if len ( args ) == 2 and not args [ 0 ] in kwargs and not kwargs : kwargs [ args [ 0 ] ] = args [ 1 ] else : self_ . self_or_cls . param . _BATCH_WATCH = False raise ValueError ( "Invalid positional arguments for %s.set_param" % ( self_or_cls . name ) ) for ( k , v ) in kwargs . items ( ) : if k not in self_or_cls . param : self_ . self_or_cls . param . _BATCH_WATCH = False raise ValueError ( "'%s' is not a parameter of %s" % ( k , self_or_cls . name ) ) try : setattr ( self_or_cls , k , v ) except : self_ . self_or_cls . param . _BATCH_WATCH = False raise self_ . self_or_cls . param . _BATCH_WATCH = BATCH_WATCH if not BATCH_WATCH : self_ . _batch_call_watchers ( ) | For each param = value keyword argument sets the corresponding parameter of this object or class to the given value . |
55,852 | def objects ( self_ , instance = True ) : cls = self_ . cls try : pdict = getattr ( cls , '_%s__params' % cls . __name__ ) except AttributeError : paramdict = { } for class_ in classlist ( cls ) : for name , val in class_ . __dict__ . items ( ) : if isinstance ( val , Parameter ) : paramdict [ name ] = val setattr ( cls , '_%s__params' % cls . __name__ , paramdict ) pdict = paramdict if instance and self_ . self is not None : if instance == 'existing' : if self_ . self . _instance__params : return dict ( pdict , ** self_ . self . _instance__params ) return pdict else : return { k : self_ . self . param [ k ] for k in pdict } return pdict | Returns the Parameters of this instance or class |
55,853 | def trigger ( self_ , * param_names ) : events = self_ . self_or_cls . param . _events watchers = self_ . self_or_cls . param . _watchers self_ . self_or_cls . param . _events = [ ] self_ . self_or_cls . param . _watchers = [ ] param_values = dict ( self_ . get_param_values ( ) ) params = { name : param_values [ name ] for name in param_names } self_ . self_or_cls . param . _TRIGGER = True self_ . set_param ( ** params ) self_ . self_or_cls . param . _TRIGGER = False self_ . self_or_cls . param . _events = events self_ . self_or_cls . param . _watchers = watchers | Trigger watchers for the given set of parameter names . Watchers will be triggered whether or not the parameter values have actually changed . |
55,854 | def _update_event_type ( self_ , watcher , event , triggered ) : if triggered : event_type = 'triggered' else : event_type = 'changed' if watcher . onlychanged else 'set' return Event ( what = event . what , name = event . name , obj = event . obj , cls = event . cls , old = event . old , new = event . new , type = event_type ) | Returns an updated Event object with the type field set appropriately . |
55,855 | def _call_watcher ( self_ , watcher , event ) : if self_ . self_or_cls . param . _TRIGGER : pass elif watcher . onlychanged and ( not self_ . _changed ( event ) ) : return if self_ . self_or_cls . param . _BATCH_WATCH : self_ . _events . append ( event ) if watcher not in self_ . _watchers : self_ . _watchers . append ( watcher ) elif watcher . mode == 'args' : with batch_watch ( self_ . self_or_cls , run = False ) : watcher . fn ( self_ . _update_event_type ( watcher , event , self_ . self_or_cls . param . _TRIGGER ) ) else : with batch_watch ( self_ . self_or_cls , run = False ) : event = self_ . _update_event_type ( watcher , event , self_ . self_or_cls . param . _TRIGGER ) watcher . fn ( ** { event . name : event . new } ) | Invoke the given the watcher appropriately given a Event object . |
55,856 | def _batch_call_watchers ( self_ ) : while self_ . self_or_cls . param . _events : event_dict = OrderedDict ( [ ( ( event . name , event . what ) , event ) for event in self_ . self_or_cls . param . _events ] ) watchers = self_ . self_or_cls . param . _watchers [ : ] self_ . self_or_cls . param . _events = [ ] self_ . self_or_cls . param . _watchers = [ ] for watcher in watchers : events = [ self_ . _update_event_type ( watcher , event_dict [ ( name , watcher . what ) ] , self_ . self_or_cls . param . _TRIGGER ) for name in watcher . parameter_names if ( name , watcher . what ) in event_dict ] with batch_watch ( self_ . self_or_cls , run = False ) : if watcher . mode == 'args' : watcher . fn ( * events ) else : watcher . fn ( ** { c . name : c . new for c in events } ) | Batch call a set of watchers based on the parameter value settings in kwargs using the queued Event and watcher objects . |
55,857 | def set_dynamic_time_fn ( self_ , time_fn , sublistattr = None ) : self_or_cls = self_ . self_or_cls self_or_cls . _Dynamic_time_fn = time_fn if isinstance ( self_or_cls , type ) : a = ( None , self_or_cls ) else : a = ( self_or_cls , ) for n , p in self_or_cls . param . objects ( 'existing' ) . items ( ) : if hasattr ( p , '_value_is_dynamic' ) : if p . _value_is_dynamic ( * a ) : g = self_or_cls . param . get_value_generator ( n ) g . _Dynamic_time_fn = time_fn if sublistattr : try : sublist = getattr ( self_or_cls , sublistattr ) except AttributeError : sublist = [ ] for obj in sublist : obj . param . set_dynamic_time_fn ( time_fn , sublistattr ) | Set time_fn for all Dynamic Parameters of this class or instance object that are currently being dynamically generated . |
55,858 | def get_param_values ( self_ , onlychanged = False ) : self_or_cls = self_ . self_or_cls vals = [ ] for name , val in self_or_cls . param . objects ( 'existing' ) . items ( ) : value = self_or_cls . param . get_value_generator ( name ) if not onlychanged or not all_equal ( value , val . default ) : vals . append ( ( name , value ) ) vals . sort ( key = itemgetter ( 0 ) ) return vals | Return a list of name value pairs for all Parameters of this object . |
55,859 | def force_new_dynamic_value ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : return getattr ( cls_or_slf , name ) cls , slf = None , None if isinstance ( cls_or_slf , type ) : cls = cls_or_slf else : slf = cls_or_slf if not hasattr ( param_obj , '_force' ) : return param_obj . __get__ ( slf , cls ) else : return param_obj . _force ( slf , cls ) | Force a new value to be generated for the dynamic attribute name and return it . |
55,860 | def get_value_generator ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : value = getattr ( cls_or_slf , name ) elif hasattr ( param_obj , 'attribs' ) : value = [ cls_or_slf . param . get_value_generator ( a ) for a in param_obj . attribs ] elif not hasattr ( param_obj , '_value_is_dynamic' ) : value = getattr ( cls_or_slf , name ) else : internal_name = "_%s_param_value" % name if hasattr ( cls_or_slf , internal_name ) : value = getattr ( cls_or_slf , internal_name ) else : value = param_obj . default return value | Return the value or value - generating object of the named attribute . |
55,861 | def inspect_value ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : value = getattr ( cls_or_slf , name ) elif hasattr ( param_obj , 'attribs' ) : value = [ cls_or_slf . param . inspect_value ( a ) for a in param_obj . attribs ] elif not hasattr ( param_obj , '_inspect' ) : value = getattr ( cls_or_slf , name ) else : if isinstance ( cls_or_slf , type ) : value = param_obj . _inspect ( None , cls_or_slf ) else : value = param_obj . _inspect ( cls_or_slf , None ) return value | Return the current value of the named attribute without modifying it . |
55,862 | def outputs ( self_ ) : outputs = { } for cls in classlist ( self_ . cls ) : for name in dir ( cls ) : method = getattr ( self_ . self_or_cls , name ) dinfo = getattr ( method , '_dinfo' , { } ) if 'outputs' not in dinfo : continue for override , otype , idx in dinfo [ 'outputs' ] : if override is not None : name = override outputs [ name ] = ( otype , method , idx ) return outputs | Returns a mapping between any declared outputs and a tuple of the declared Parameter type the output method and the index into the output if multiple outputs are returned . |
55,863 | def unwatch ( self_ , watcher ) : try : self_ . _watch ( 'remove' , watcher ) except : self_ . warning ( 'No such watcher {watcher} to remove.' . format ( watcher = watcher ) ) | Unwatch watchers set either with watch or watch_values . |
55,864 | def print_param_values ( self_ ) : self = self_ . self for name , val in self . param . get_param_values ( ) : print ( '%s.%s = %s' % ( self . name , name , val ) ) | Print the values of all this object s Parameters . |
55,865 | def warning ( self_ , msg , * args , ** kw ) : if not warnings_as_exceptions : global warning_count warning_count += 1 self_ . __db_print ( WARNING , msg , * args , ** kw ) else : raise Exception ( "Warning: " + msg % args ) | Print msg merged with args as a warning unless module variable warnings_as_exceptions is True then raise an Exception containing the arguments . |
55,866 | def message ( self_ , msg , * args , ** kw ) : self_ . __db_print ( INFO , msg , * args , ** kw ) | Print msg merged with args as a message . |
55,867 | def verbose ( self_ , msg , * args , ** kw ) : self_ . __db_print ( VERBOSE , msg , * args , ** kw ) | Print msg merged with args as a verbose message . |
55,868 | def debug ( self_ , msg , * args , ** kw ) : self_ . __db_print ( DEBUG , msg , * args , ** kw ) | Print msg merged with args as a debugging statement . |
55,869 | def __class_docstring_signature ( mcs , max_repr_len = 15 ) : processed_kws , keyword_groups = set ( ) , [ ] for cls in reversed ( mcs . mro ( ) ) : keyword_group = [ ] for ( k , v ) in sorted ( cls . __dict__ . items ( ) ) : if isinstance ( v , Parameter ) and k not in processed_kws : param_type = v . __class__ . __name__ keyword_group . append ( "%s=%s" % ( k , param_type ) ) processed_kws . add ( k ) keyword_groups . append ( keyword_group ) keywords = [ el for grp in reversed ( keyword_groups ) for el in grp ] class_docstr = "\n" + mcs . __doc__ if mcs . __doc__ else '' signature = "params(%s)" % ( ", " . join ( keywords ) ) description = param_pager ( mcs ) if ( docstring_describe_params and param_pager ) else '' mcs . __doc__ = signature + class_docstr + '\n' + description | Autogenerate a keyword signature in the class docstring for all available parameters . This is particularly useful in the IPython Notebook as IPython will parse this signature to allow tab - completion of keywords . |
55,870 | def __param_inheritance ( mcs , param_name , param ) : slots = { } for p_class in classlist ( type ( param ) ) [ 1 : : ] : slots . update ( dict . fromkeys ( p_class . __slots__ ) ) setattr ( param , 'owner' , mcs ) del slots [ 'owner' ] if 'objtype' in slots : setattr ( param , 'objtype' , mcs ) del slots [ 'objtype' ] for superclass in classlist ( mcs ) [ : : - 1 ] : super_param = superclass . __dict__ . get ( param_name ) if isinstance ( super_param , Parameter ) and super_param . instantiate is True : param . instantiate = True del slots [ 'instantiate' ] for slot in slots . keys ( ) : superclasses = iter ( classlist ( mcs ) [ : : - 1 ] ) while getattr ( param , slot ) is None : try : param_super_class = next ( superclasses ) except StopIteration : break new_param = param_super_class . __dict__ . get ( param_name ) if new_param is not None and hasattr ( new_param , slot ) : new_value = getattr ( new_param , slot ) setattr ( param , slot , new_value ) | Look for Parameter values in superclasses of this Parameterized class . |
55,871 | def _check_params ( self , params ) : overridden_object_params = list ( self . _overridden . param ) for item in params : if item not in overridden_object_params : self . param . warning ( "'%s' will be ignored (not a Parameter)." , item ) | Print a warning if params contains something that is not a Parameter of the overridden object . |
55,872 | def _extract_extra_keywords ( self , params ) : extra_keywords = { } overridden_object_params = list ( self . _overridden . param ) for name , val in params . items ( ) : if name not in overridden_object_params : extra_keywords [ name ] = val return extra_keywords | Return any items in params that are not also parameters of the overridden object . |
55,873 | def instance ( self_or_cls , ** params ) : if isinstance ( self_or_cls , ParameterizedMetaclass ) : cls = self_or_cls else : p = params params = dict ( self_or_cls . get_param_values ( ) ) params . update ( p ) params . pop ( 'name' ) cls = self_or_cls . __class__ inst = Parameterized . __new__ ( cls ) Parameterized . __init__ ( inst , ** params ) if 'name' in params : inst . __name__ = params [ 'name' ] else : inst . __name__ = self_or_cls . name return inst | Return an instance of this class copying parameters from any existing instance provided . |
55,874 | def script_repr ( self , imports = [ ] , prefix = " " ) : return self . pprint ( imports , prefix , unknown_value = '' , qualify = True , separator = "\n" ) | Same as Parameterized . script_repr except that X . classname ( Y is replaced with X . classname . instance ( Y |
55,875 | def pprint ( self , imports = None , prefix = "\n " , unknown_value = '<?>' , qualify = False , separator = "" ) : r = Parameterized . pprint ( self , imports , prefix , unknown_value = unknown_value , qualify = qualify , separator = separator ) classname = self . __class__ . __name__ return r . replace ( ".%s(" % classname , ".%s.instance(" % classname ) | Same as Parameterized . pprint except that X . classname ( Y is replaced with X . classname . instance ( Y |
55,876 | def resolve_filename ( self , package_dir , filename ) : sass_path = os . path . join ( package_dir , self . sass_path , filename ) if self . strip_extension : filename , _ = os . path . splitext ( filename ) css_filename = filename + '.css' css_path = os . path . join ( package_dir , self . css_path , css_filename ) return sass_path , css_path | Gets a proper full relative path of Sass source and CSS source that will be generated according to package_dir and filename . |
55,877 | def unresolve_filename ( self , package_dir , filename ) : filename , _ = os . path . splitext ( filename ) if self . strip_extension : for ext in ( '.scss' , '.sass' ) : test_path = os . path . join ( package_dir , self . sass_path , filename + ext , ) if os . path . exists ( test_path ) : return filename + ext else : return filename + '.scss' else : return filename | Retrieves the probable source path from the output filename . Pass in a . css path to get out a . scss path . |
55,878 | def _validate_importers ( importers ) : if importers is None : return None def _to_importer ( priority , func ) : assert isinstance ( priority , int ) , priority assert callable ( func ) , func return ( priority , _importer_callback_wrapper ( func ) ) return tuple ( _to_importer ( priority , func ) for priority , func in importers ) | Validates the importers and decorates the callables with our output formatter . |
55,879 | def and_join ( strings ) : last = len ( strings ) - 1 if last == 0 : return strings [ 0 ] elif last < 0 : return '' iterator = enumerate ( strings ) return ', ' . join ( 'and ' + s if i == last else s for i , s in iterator ) | Join the given strings by commas with last and conjuction . |
55,880 | def allow_staff_or_superuser ( func ) : is_object_permission = "has_object" in func . __name__ @ wraps ( func ) def func_wrapper ( * args , ** kwargs ) : request = args [ 0 ] if is_object_permission : request = args [ 1 ] if request . user . is_staff or request . user . is_superuser : return True return func ( * args , ** kwargs ) return func_wrapper | This decorator is used to abstract common is_staff and is_superuser functionality out of permission checks . It determines which parameter is the request based on name . |
55,881 | def authenticated_users ( func ) : is_object_permission = "has_object" in func . __name__ @ wraps ( func ) def func_wrapper ( * args , ** kwargs ) : request = args [ 0 ] if is_object_permission : request = args [ 1 ] if not ( request . user and request . user . is_authenticated ) : return False return func ( * args , ** kwargs ) return func_wrapper | This decorator is used to abstract common authentication checking functionality out of permission checks . It determines which parameter is the request based on name . |
55,882 | def filter_queryset ( self , request , queryset , view ) : if view . lookup_field not in view . kwargs : if not self . action_routing : return self . filter_list_queryset ( request , queryset , view ) else : method_name = "filter_{action}_queryset" . format ( action = view . action ) return getattr ( self , method_name ) ( request , queryset , view ) return queryset | This method overrides the standard filter_queryset method . This method will check to see if the view calling this is from a list type action . This function will also route the filter by action type if action_routing is set to True . |
55,883 | def has_permission ( self , request , view ) : if not self . global_permissions : return True serializer_class = view . get_serializer_class ( ) assert serializer_class . Meta . model is not None , ( "global_permissions set to true without a model " "set on the serializer for '%s'" % view . __class__ . __name__ ) model_class = serializer_class . Meta . model action_method_name = None if hasattr ( view , 'action' ) : action = self . _get_action ( view . action ) action_method_name = "has_{action}_permission" . format ( action = action ) if hasattr ( model_class , action_method_name ) : return getattr ( model_class , action_method_name ) ( request ) if request . method in permissions . SAFE_METHODS : assert hasattr ( model_class , 'has_read_permission' ) , self . _get_error_message ( model_class , 'has_read_permission' , action_method_name ) return model_class . has_read_permission ( request ) else : assert hasattr ( model_class , 'has_write_permission' ) , self . _get_error_message ( model_class , 'has_write_permission' , action_method_name ) return model_class . has_write_permission ( request ) | Overrides the standard function and figures out methods to call for global permissions . |
55,884 | def has_object_permission ( self , request , view , obj ) : if not self . object_permissions : return True serializer_class = view . get_serializer_class ( ) model_class = serializer_class . Meta . model action_method_name = None if hasattr ( view , 'action' ) : action = self . _get_action ( view . action ) action_method_name = "has_object_{action}_permission" . format ( action = action ) if hasattr ( obj , action_method_name ) : return getattr ( obj , action_method_name ) ( request ) if request . method in permissions . SAFE_METHODS : assert hasattr ( obj , 'has_object_read_permission' ) , self . _get_error_message ( model_class , 'has_object_read_permission' , action_method_name ) return obj . has_object_read_permission ( request ) else : assert hasattr ( obj , 'has_object_write_permission' ) , self . _get_error_message ( model_class , 'has_object_write_permission' , action_method_name ) return obj . has_object_write_permission ( request ) | Overrides the standard function and figures out methods to call for object permissions . |
55,885 | def _get_action ( self , action ) : return_action = action if self . partial_update_is_update and action == 'partial_update' : return_action = 'update' return return_action | Utility function that consolidates actions if necessary . |
55,886 | def _get_error_message ( self , model_class , method_name , action_method_name ) : if action_method_name : return "'{}' does not have '{}' or '{}' defined." . format ( model_class , method_name , action_method_name ) else : return "'{}' does not have '{}' defined." . format ( model_class , method_name ) | Get assertion error message depending if there are actions permissions methods defined . |
55,887 | def bind ( self , field_name , parent ) : assert parent . Meta . model is not None , "DRYPermissions is used on '{}' without a model" . format ( parent . __class__ . __name__ ) for action in self . actions : if not self . object_only : global_method_name = "has_{action}_permission" . format ( action = action ) if hasattr ( parent . Meta . model , global_method_name ) : self . action_method_map [ action ] = { 'global' : global_method_name } if not self . global_only : object_method_name = "has_object_{action}_permission" . format ( action = action ) if hasattr ( parent . Meta . model , object_method_name ) : if self . action_method_map . get ( action , None ) is None : self . action_method_map [ action ] = { } self . action_method_map [ action ] [ 'object' ] = object_method_name super ( DRYPermissionsField , self ) . bind ( field_name , parent ) | Check the model attached to the serializer to see what methods are defined and save them . |
55,888 | def skip_prepare ( func ) : @ wraps ( func ) def _wrapper ( self , * args , ** kwargs ) : value = func ( self , * args , ** kwargs ) return Data ( value , should_prepare = False ) return _wrapper | A convenience decorator for indicating the raw data should not be prepared . |
55,889 | def build_error ( self , err ) : data = { 'error' : err . args [ 0 ] , } if self . is_debug ( ) : data [ 'traceback' ] = format_traceback ( sys . exc_info ( ) ) body = self . serializer . serialize ( data ) status = getattr ( err , 'status' , 500 ) return self . build_response ( body , status = status ) | When an exception is encountered this generates a JSON error message for display to the user . |
55,890 | def deserialize ( self , method , endpoint , body ) : if endpoint == 'list' : return self . deserialize_list ( body ) return self . deserialize_detail ( body ) | A convenience method for deserializing the body of a request . |
55,891 | def serialize ( self , method , endpoint , data ) : if endpoint == 'list' : if method == 'POST' : return self . serialize_detail ( data ) return self . serialize_list ( data ) return self . serialize_detail ( data ) | A convenience method for serializing data for a response . |
55,892 | def _method ( self , * args , ** kwargs ) : yield self . resource_handler . handle ( self . __resource_view_type__ , * args , ** kwargs ) | the body of those http - methods used in tornado . web . RequestHandler |
55,893 | def as_view ( cls , view_type , * init_args , ** init_kwargs ) : global _method new_cls = type ( cls . __name__ + '_' + _BridgeMixin . __name__ + '_restless' , ( _BridgeMixin , cls . _request_handler_base_ , ) , dict ( __resource_cls__ = cls , __resource_args__ = init_args , __resource_kwargs__ = init_kwargs , __resource_view_type__ = view_type ) ) bases = inspect . getmro ( cls ) bases = bases [ 0 : bases . index ( Resource ) - 1 ] for k , v in cls . http_methods [ view_type ] . items ( ) : if any ( v in base_cls . __dict__ for base_cls in bases ) : setattr ( new_cls , k . lower ( ) , _method ) return new_cls | Return a subclass of tornado . web . RequestHandler and apply required setting . |
55,894 | def handle ( self , endpoint , * args , ** kwargs ) : method = self . request_method ( ) try : if not method in self . http_methods . get ( endpoint , { } ) : raise MethodNotImplemented ( "Unsupported method '{}' for {} endpoint." . format ( method , endpoint ) ) if not self . is_authenticated ( ) : raise Unauthorized ( ) self . data = self . deserialize ( method , endpoint , self . request_body ( ) ) view_method = getattr ( self , self . http_methods [ endpoint ] [ method ] ) data = view_method ( * args , ** kwargs ) if is_future ( data ) : data = yield data serialized = self . serialize ( method , endpoint , data ) except Exception as err : raise gen . Return ( self . handle_error ( err ) ) status = self . status_map . get ( self . http_methods [ endpoint ] [ method ] , OK ) raise gen . Return ( self . build_response ( serialized , status = status ) ) | almost identical to Resource . handle except the way we handle the return value of view_method . |
55,895 | def prepare ( self , data ) : result = { } if not self . fields : return data for fieldname , lookup in self . fields . items ( ) : if isinstance ( lookup , SubPreparer ) : result [ fieldname ] = lookup . prepare ( data ) else : result [ fieldname ] = self . lookup_data ( lookup , data ) return result | Handles transforming the provided data into the fielded data that should be exposed to the end user . |
55,896 | def lookup_data ( self , lookup , data ) : value = data parts = lookup . split ( '.' ) if not parts or not parts [ 0 ] : return value part = parts [ 0 ] remaining_lookup = '.' . join ( parts [ 1 : ] ) if callable ( getattr ( data , 'keys' , None ) ) and hasattr ( data , '__getitem__' ) : value = data [ part ] elif data is not None : value = getattr ( data , part ) if callable ( value ) and not hasattr ( value , 'db_manager' ) : value = value ( ) if not remaining_lookup : return value return self . lookup_data ( remaining_lookup , value ) | Given a lookup string attempts to descend through nested data looking for the value . |
55,897 | def prepare ( self , data ) : result = [ ] for item in self . get_inner_data ( data ) : result . append ( self . preparer . prepare ( item ) ) return result | Handles passing each item in the collection data to the configured subpreparer . |
55,898 | def build_url_name ( cls , name , name_prefix = None ) : if name_prefix is None : name_prefix = 'api_{}' . format ( cls . __name__ . replace ( 'Resource' , '' ) . lower ( ) ) name_prefix = name_prefix . rstrip ( '_' ) return '_' . join ( [ name_prefix , name ] ) | Given a name & an optional name_prefix this generates a name for a URL . |
55,899 | def build_endpoint_name ( cls , name , endpoint_prefix = None ) : if endpoint_prefix is None : endpoint_prefix = 'api_{}' . format ( cls . __name__ . replace ( 'Resource' , '' ) . lower ( ) ) endpoint_prefix = endpoint_prefix . rstrip ( '_' ) return '_' . join ( [ endpoint_prefix , name ] ) | Given a name & an optional endpoint_prefix this generates a name for a URL . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.