idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
23,700 | def aggregate ( self , other = None ) : if not self . status : return self if not other : return self if not other . status : return other return Value ( True , other . index , self . value + other . value , None ) | collect the furthest failure from self and other . |
23,701 | def combinate ( values ) : prev_v = None for v in values : if prev_v : if not v : return prev_v if not v . status : return v out_values = tuple ( [ v . value for v in values ] ) return Value ( True , values [ - 1 ] . index , out_values , None ) | aggregate multiple values into tuple |
23,702 | def parse_partial ( self , text ) : if not isinstance ( text , str ) : raise TypeError ( 'Can only parsing string but got {!r}' . format ( text ) ) res = self ( text , 0 ) if res . status : return ( res . value , text [ res . index : ] ) else : raise ParseError ( res . expected , text , res . index ) | Parse the longest possible prefix of a given string . Return a tuple of the result value and the rest of the string . If failed raise a ParseError . |
23,703 | def bind ( self , fn ) : @ Parser def bind_parser ( text , index ) : res = self ( text , index ) return res if not res . status else fn ( res . value ) ( text , res . index ) return bind_parser | This is the monadic binding operation . Returns a parser which if parser is successful passes the result to fn and continues with the parser returned from fn . |
23,704 | def parsecmap ( self , fn ) : return self . bind ( lambda res : Parser ( lambda _ , index : Value . success ( index , fn ( res ) ) ) ) | Returns a parser that transforms the produced value of parser with fn . |
23,705 | def parsecapp ( self , other ) : return self . bind ( lambda res : other . parsecmap ( lambda x : res ( x ) ) ) | Returns a parser that applies the produced value of this parser to the produced value of other . |
23,706 | def result ( self , res ) : return self >> Parser ( lambda _ , index : Value . success ( index , res ) ) | Return a value according to the parameter res when parse successfully . |
23,707 | def mark ( self ) : def pos ( text , index ) : return ParseError . loc_info ( text , index ) @ Parser def mark_parser ( text , index ) : res = self ( text , index ) if res . status : return Value . success ( res . index , ( pos ( text , index ) , res . value , pos ( text , res . index ) ) ) else : return res return mark_parser | Mark the line and column information of the result of this parser . |
23,708 | def desc ( self , description ) : return self | Parser ( lambda _ , index : Value . failure ( index , description ) ) | Describe a parser when it failed print out the description text . |
23,709 | def route ( * args ) : def _validate_route ( route ) : if not isinstance ( route , six . string_types ) : raise TypeError ( '%s must be a string' % route ) if route in ( '.' , '..' ) or not re . match ( '^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$' , route ) : raise ValueError ( '%s must be a valid path segment. Keep in mind ' 'that path segments should not contain path separators ' '(e.g., /) ' % route ) if len ( args ) == 2 : route , handler = args if ismethod ( handler ) : handler = handler . __func__ if not iscontroller ( handler ) : raise TypeError ( '%s must be a callable decorated with @pecan.expose' % handler ) obj , attr , value = handler , 'custom_route' , route if handler . __name__ in ( '_lookup' , '_default' , '_route' ) : raise ValueError ( '%s is a special method in pecan and cannot be used in ' 'combination with custom path segments.' % handler . __name__ ) elif len ( args ) == 3 : _ , route , handler = args obj , attr , value = args if hasattr ( obj , attr ) : raise RuntimeError ( ( "%(module)s.%(class)s already has an " "existing attribute named \"%(route)s\"." % { 'module' : obj . __module__ , 'class' : obj . __name__ , 'route' : attr } ) , ) else : raise TypeError ( 'pecan.route should be called in the format ' 'route(ParentController, "path-segment", SubController())' ) _validate_route ( route ) setattr ( obj , attr , value ) | This function is used to define an explicit route for a path segment . |
23,710 | def lookup_controller ( obj , remainder , request = None ) : if request is None : warnings . warn ( ( "The function signature for %s.lookup_controller is changing " "in the next version of pecan.\nPlease update to: " "`lookup_controller(self, obj, remainder, request)`." % ( __name__ , ) ) , DeprecationWarning ) notfound_handlers = [ ] while True : try : obj , remainder = find_object ( obj , remainder , notfound_handlers , request ) handle_security ( obj ) return obj , remainder except ( exc . HTTPNotFound , exc . HTTPMethodNotAllowed , PecanNotFound ) as e : if isinstance ( e , PecanNotFound ) : e = exc . HTTPNotFound ( ) while notfound_handlers : name , obj , remainder = notfound_handlers . pop ( ) if name == '_default' : return obj , remainder else : result = handle_lookup_traversal ( obj , remainder ) if result : if ( remainder == [ '' ] and len ( obj . _pecan [ 'argspec' ] . args ) > 1 ) : raise e obj_ , remainder_ = result return lookup_controller ( obj_ , remainder_ , request ) else : raise e | Traverses the requested url path and returns the appropriate controller object including default routes . |
23,711 | def find_object ( obj , remainder , notfound_handlers , request ) : prev_obj = None while True : if obj is None : raise PecanNotFound if iscontroller ( obj ) : if getattr ( obj , 'custom_route' , None ) is None : return obj , remainder _detect_custom_path_segments ( obj ) if remainder : custom_route = __custom_routes__ . get ( ( obj . __class__ , remainder [ 0 ] ) ) if custom_route : return getattr ( obj , custom_route ) , remainder [ 1 : ] cross_boundary ( prev_obj , obj ) try : next_obj , rest = remainder [ 0 ] , remainder [ 1 : ] if next_obj == '' : index = getattr ( obj , 'index' , None ) if iscontroller ( index ) : return index , rest except IndexError : index = getattr ( obj , 'index' , None ) if iscontroller ( index ) : raise NonCanonicalPath ( index , [ ] ) default = getattr ( obj , '_default' , None ) if iscontroller ( default ) : notfound_handlers . append ( ( '_default' , default , remainder ) ) lookup = getattr ( obj , '_lookup' , None ) if iscontroller ( lookup ) : notfound_handlers . append ( ( '_lookup' , lookup , remainder ) ) route = getattr ( obj , '_route' , None ) if iscontroller ( route ) : if len ( getargspec ( route ) . args ) == 2 : warnings . warn ( ( "The function signature for %s.%s._route is changing " "in the next version of pecan.\nPlease update to: " "`def _route(self, args, request)`." % ( obj . __class__ . __module__ , obj . __class__ . __name__ ) ) , DeprecationWarning ) next_obj , next_remainder = route ( remainder ) else : next_obj , next_remainder = route ( remainder , request ) cross_boundary ( route , next_obj ) return next_obj , next_remainder if not remainder : raise PecanNotFound prev_remainder = remainder prev_obj = obj remainder = rest try : obj = getattr ( obj , next_obj , None ) except UnicodeEncodeError : obj = None if not obj and not notfound_handlers and hasattr ( prev_obj , 'index' ) : if request . method in _cfg ( prev_obj . index ) . get ( 'generic_handlers' , { } ) : return prev_obj . index , prev_remainder | Walks the url path in search of an action for which a controller is implemented and returns that controller object along with what s left of the remainder . |
23,712 | def unlocked ( func_or_obj ) : if ismethod ( func_or_obj ) or isfunction ( func_or_obj ) : return _unlocked_method ( func_or_obj ) else : return _UnlockedAttribute ( func_or_obj ) | This method unlocks method or class attribute on a SecureController . Can be used to decorate or wrap an attribute |
23,713 | def secure ( func_or_obj , check_permissions_for_obj = None ) : if _allowed_check_permissions_types ( func_or_obj ) : return _secure_method ( func_or_obj ) else : if not _allowed_check_permissions_types ( check_permissions_for_obj ) : msg = "When securing an object, secure() requires the " + "second argument to be method" raise TypeError ( msg ) return _SecuredAttribute ( func_or_obj , check_permissions_for_obj ) | This method secures a method or class depending on invocation . |
23,714 | def _make_wrapper ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwargs ) : return f ( * args , ** kwargs ) wrapper . _pecan = f . _pecan . copy ( ) return wrapper | return a wrapped function with a copy of the _pecan context |
23,715 | def handle_security ( controller , im_self = None ) : if controller . _pecan . get ( 'secured' , False ) : check_permissions = controller . _pecan [ 'check_permissions' ] if isinstance ( check_permissions , six . string_types ) : check_permissions = getattr ( im_self or six . get_method_self ( controller ) , check_permissions ) if not check_permissions ( ) : raise exc . HTTPUnauthorized | Checks the security of a controller . |
23,716 | def cross_boundary ( prev_obj , obj ) : if prev_obj is None : return if isinstance ( obj , _SecuredAttribute ) : obj . parent = prev_obj if hasattr ( prev_obj , '_pecan' ) : if obj not in prev_obj . _pecan . get ( 'unlocked' , [ ] ) : handle_security ( prev_obj ) | Check permissions as we move between object instances . |
23,717 | def makedirs ( directory ) : parent = os . path . dirname ( os . path . abspath ( directory ) ) if not os . path . exists ( parent ) : makedirs ( parent ) os . mkdir ( directory ) | Resursively create a named directory . |
23,718 | def substitute_filename ( fn , variables ) : for var , value in variables . items ( ) : fn = fn . replace ( '+%s+' % var , str ( value ) ) return fn | Substitute + variables + in file directory names . |
23,719 | def make_app ( root , ** kw ) : logging = kw . get ( 'logging' , { } ) debug = kw . get ( 'debug' , False ) if logging : if debug : try : from logging import captureWarnings captureWarnings ( True ) warnings . simplefilter ( "default" , DeprecationWarning ) except ImportError : pass if isinstance ( logging , Config ) : logging = logging . to_dict ( ) if 'version' not in logging : logging [ 'version' ] = 1 load_logging_config ( logging ) app = Pecan ( root , ** kw ) wrap_app = kw . get ( 'wrap_app' , None ) if wrap_app : app = wrap_app ( app ) errors = kw . get ( 'errors' , getattr ( conf . app , 'errors' , { } ) ) if errors : app = middleware . errordocument . ErrorDocumentMiddleware ( app , errors ) app = middleware . recursive . RecursiveMiddleware ( app ) static_root = kw . get ( 'static_root' , None ) if debug : debug_kwargs = getattr ( conf , 'debug' , { } ) debug_kwargs . setdefault ( 'context_injectors' , [ ] ) . append ( lambda environ : { 'request' : environ . get ( 'pecan.locals' , { } ) . get ( 'request' ) } ) app = DebugMiddleware ( app , ** debug_kwargs ) if static_root : app = middleware . static . StaticFileMiddleware ( app , static_root ) elif static_root : warnings . warn ( "`static_root` is only used when `debug` is True, ignoring" , RuntimeWarning ) if hasattr ( conf , 'requestviewer' ) : warnings . warn ( '' . join ( [ "`pecan.conf.requestviewer` is deprecated. To apply the " , "`RequestViewerHook` to your application, add it to " , "`pecan.conf.app.hooks` or manually in your project's `app.py` " , "file." ] ) , DeprecationWarning ) return app | Utility for creating the Pecan application object . This function should generally be called from the setup_app function in your project s app . py file . |
23,720 | def conf_from_file ( filepath ) : abspath = os . path . abspath ( os . path . expanduser ( filepath ) ) conf_dict = { } if not os . path . isfile ( abspath ) : raise RuntimeError ( '`%s` is not a file.' % abspath ) with open ( abspath , 'rb' ) as f : compiled = compile ( f . read ( ) , abspath , 'exec' ) absname , _ = os . path . splitext ( abspath ) basepath , module_name = absname . rsplit ( os . sep , 1 ) if six . PY3 : SourceFileLoader ( module_name , abspath ) . load_module ( module_name ) else : imp . load_module ( module_name , * imp . find_module ( module_name , [ basepath ] ) ) exec ( compiled , globals ( ) , conf_dict ) conf_dict [ '__file__' ] = abspath return conf_from_dict ( conf_dict ) | Creates a configuration dictionary from a file . |
23,721 | def get_conf_path_from_env ( ) : config_path = os . environ . get ( 'PECAN_CONFIG' ) if not config_path : error = "PECAN_CONFIG is not set and " "no config file was passed as an argument." elif not os . path . isfile ( config_path ) : error = "PECAN_CONFIG was set to an invalid path: %s" % config_path else : return config_path raise RuntimeError ( error ) | If the PECAN_CONFIG environment variable exists and it points to a valid path it will return that otherwise it will raise a RuntimeError . |
23,722 | def conf_from_dict ( conf_dict ) : conf = Config ( filename = conf_dict . get ( '__file__' , '' ) ) for k , v in six . iteritems ( conf_dict ) : if k . startswith ( '__' ) : continue elif inspect . ismodule ( v ) : continue conf [ k ] = v return conf | Creates a configuration dictionary from a dictionary . |
23,723 | def set_config ( config , overwrite = False ) : if config is None : config = get_conf_path_from_env ( ) if overwrite is True : _runtime_conf . empty ( ) if isinstance ( config , six . string_types ) : config = conf_from_file ( config ) _runtime_conf . update ( config ) if config . __file__ : _runtime_conf . __file__ = config . __file__ elif isinstance ( config , dict ) : _runtime_conf . update ( conf_from_dict ( config ) ) else : raise TypeError ( '%s is neither a dictionary or a string.' % config ) | Updates the global configuration . |
23,724 | def update ( self , conf_dict ) : if isinstance ( conf_dict , dict ) : iterator = six . iteritems ( conf_dict ) else : iterator = iter ( conf_dict ) for k , v in iterator : if not IDENTIFIER . match ( k ) : raise ValueError ( '\'%s\' is not a valid indentifier' % k ) cur_val = self . __values__ . get ( k ) if isinstance ( cur_val , Config ) : cur_val . update ( conf_dict [ k ] ) else : self [ k ] = conf_dict [ k ] | Updates this configuration with a dictionary . |
23,725 | def to_dict ( self , prefix = None ) : conf_obj = dict ( self ) return self . __dictify__ ( conf_obj , prefix ) | Converts recursively the Config object into a valid dictionary . |
23,726 | def override_template ( template , content_type = None ) : request . pecan [ 'override_template' ] = template if content_type : request . pecan [ 'override_content_type' ] = content_type | Call within a controller to override the template that is used in your response . |
23,727 | def abort ( status_code , detail = '' , headers = None , comment = None , ** kw ) : try : _ , _ , traceback = sys . exc_info ( ) webob_exception = exc . status_map [ status_code ] ( detail = detail , headers = headers , comment = comment , ** kw ) if six . PY3 : raise webob_exception . with_traceback ( traceback ) else : exec ( 'raise webob_exception, None, traceback' ) finally : del traceback | Raise an HTTP status code as specified . Useful for returning status codes like 401 Unauthorized or 403 Forbidden . |
23,728 | def redirect ( location = None , internal = False , code = None , headers = { } , add_slash = False , request = None ) : request = request or state . request if add_slash : if location is None : split_url = list ( urlparse . urlsplit ( request . url ) ) new_proto = request . environ . get ( 'HTTP_X_FORWARDED_PROTO' , split_url [ 0 ] ) split_url [ 0 ] = new_proto else : split_url = urlparse . urlsplit ( location ) split_url [ 2 ] = split_url [ 2 ] . rstrip ( '/' ) + '/' location = urlparse . urlunsplit ( split_url ) if not headers : headers = { } if internal : if code is not None : raise ValueError ( 'Cannot specify a code for internal redirects' ) request . environ [ 'pecan.recursive.context' ] = request . context raise ForwardRequestException ( location ) if code is None : code = 302 raise exc . status_map [ code ] ( location = location , headers = headers ) | Perform a redirect either internal or external . An internal redirect performs the redirect server - side while the external redirect utilizes an HTTP 302 status code . |
23,729 | def load_app ( config , ** kwargs ) : from . configuration import _runtime_conf , set_config set_config ( config , overwrite = True ) for package_name in getattr ( _runtime_conf . app , 'modules' , [ ] ) : module = __import__ ( package_name , fromlist = [ 'app' ] ) if hasattr ( module , 'app' ) and hasattr ( module . app , 'setup_app' ) : app = module . app . setup_app ( _runtime_conf , ** kwargs ) app . config = _runtime_conf return app raise RuntimeError ( 'No app.setup_app found in any of the configured app.modules' ) | Used to load a Pecan application and its environment based on passed configuration . |
23,730 | def route ( self , req , node , path ) : path = path . split ( '/' ) [ 1 : ] try : node , remainder = lookup_controller ( node , path , req ) return node , remainder except NonCanonicalPath as e : if self . force_canonical and not _cfg ( e . controller ) . get ( 'accept_noncanonical' , False ) : if req . method == 'POST' : raise RuntimeError ( "You have POSTed to a URL '%s' which " "requires a slash. Most browsers will not maintain " "POST data when redirected. Please update your code " "to POST to '%s/' or set force_canonical to False" % ( req . pecan [ 'routing_path' ] , req . pecan [ 'routing_path' ] ) ) redirect ( code = 302 , add_slash = True , request = req ) return e . controller , e . remainder | Looks up a controller from a node based upon the specified path . |
23,731 | def determine_hooks ( self , controller = None ) : controller_hooks = [ ] if controller : controller_hooks = _cfg ( controller ) . get ( 'hooks' , [ ] ) if controller_hooks : return list ( sorted ( chain ( controller_hooks , self . hooks ) , key = operator . attrgetter ( 'priority' ) ) ) return self . hooks | Determines the hooks to be run in which order . |
23,732 | def handle_hooks ( self , hooks , hook_type , * args ) : if hook_type not in [ 'before' , 'on_route' ] : hooks = reversed ( hooks ) for hook in hooks : result = getattr ( hook , hook_type ) ( * args ) if hook_type == 'on_error' and isinstance ( result , WebObResponse ) : return result | Processes hooks of the specified type . |
23,733 | def get_args ( self , state , all_params , remainder , argspec , im_self ) : args = [ ] varargs = [ ] kwargs = dict ( ) valid_args = argspec . args [ : ] if ismethod ( state . controller ) or im_self : valid_args . pop ( 0 ) pecan_state = state . request . pecan remainder = [ x for x in remainder if x ] if im_self is not None : args . append ( im_self ) if 'routing_args' in pecan_state : remainder = pecan_state [ 'routing_args' ] + list ( remainder ) del pecan_state [ 'routing_args' ] if valid_args and remainder : args . extend ( remainder [ : len ( valid_args ) ] ) remainder = remainder [ len ( valid_args ) : ] valid_args = valid_args [ len ( args ) : ] if [ i for i in remainder if i ] : if not argspec [ 1 ] : abort ( 404 ) varargs . extend ( remainder ) if argspec [ 3 ] : defaults = dict ( izip ( argspec [ 0 ] [ - len ( argspec [ 3 ] ) : ] , argspec [ 3 ] ) ) else : defaults = dict ( ) for name in valid_args : if name in all_params : args . append ( all_params . pop ( name ) ) elif name in defaults : args . append ( defaults [ name ] ) else : break if argspec [ 2 ] : for name , value in six . iteritems ( all_params ) : if name not in argspec [ 0 ] : kwargs [ name ] = value return args , varargs , kwargs | Determines the arguments for a controller based upon parameters passed the argument specification for the controller . |
23,734 | def run ( self , args ) : super ( ShellCommand , self ) . run ( args ) app = self . load_app ( ) locs = dict ( __name__ = 'pecan-admin' ) locs [ 'wsgiapp' ] = app locs [ 'app' ] = TestApp ( app ) model = self . load_model ( app . config ) if model : locs [ 'model' ] = model from pecan import abort , conf , redirect , request , response locs [ 'abort' ] = abort locs [ 'conf' ] = conf locs [ 'redirect' ] = redirect locs [ 'request' ] = request locs [ 'response' ] = response banner = ' The following objects are available:\n' banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp' banner += ' %-10s - The current configuration\n' % 'conf' banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' if model : model_name = getattr ( model , '__module__' , getattr ( model , '__name__' , 'model' ) ) banner += ' %-10s - Models from %s\n' % ( 'model' , model_name ) self . invoke_shell ( locs , banner ) | Load the pecan app prepare the locals sets the banner and invokes the python shell . |
23,735 | def load_model ( self , config ) : for package_name in getattr ( config . app , 'modules' , [ ] ) : module = __import__ ( package_name , fromlist = [ 'model' ] ) if hasattr ( module , 'model' ) : return module . model return None | Load the model extension module |
23,736 | def _handle_bad_rest_arguments ( self , controller , remainder , request ) : argspec = self . _get_args_for_controller ( controller ) fixed_args = len ( argspec ) - len ( request . pecan . get ( 'routing_args' , [ ] ) ) if len ( remainder ) < fixed_args : abort ( 404 ) | Ensure that the argspec for a discovered controller actually matched the positional arguments in the request path . If not raise a webob . exc . HTTPBadRequest . |
23,737 | def _route ( self , args , request = None ) : if request is None : from pecan import request method = request . params . get ( '_method' , request . method ) . lower ( ) if request . method == 'GET' and method in ( 'delete' , 'put' ) : abort ( 405 ) result = self . _find_sub_controllers ( args , request ) if result : return result handler = getattr ( self , '_handle_%s' % method , self . _handle_unknown_method ) try : if len ( getargspec ( handler ) . args ) == 3 : result = handler ( method , args ) else : result = handler ( method , args , request ) argspec = self . _get_args_for_controller ( result [ 0 ] ) num_args = len ( argspec ) if num_args < len ( args ) : _lookup_result = self . _handle_lookup ( args , request ) if _lookup_result : return _lookup_result except ( exc . HTTPClientError , exc . HTTPNotFound , exc . HTTPMethodNotAllowed ) as e : _lookup_result = self . _handle_lookup ( args , request ) if _lookup_result : return _lookup_result if isinstance ( e , exc . HTTPMethodNotAllowed ) : def method_iter ( ) : for func in ( 'get' , 'get_one' , 'get_all' , 'new' , 'edit' , 'get_delete' ) : if self . _find_controller ( func ) : yield 'GET' break for method in ( 'HEAD' , 'POST' , 'PUT' , 'DELETE' , 'TRACE' , 'PATCH' ) : func = method . lower ( ) if self . _find_controller ( func ) : yield method e . allow = sorted ( method_iter ( ) ) raise return result | Routes a request to the appropriate controller and returns its result . |
23,738 | def _find_controller ( self , * args ) : for name in args : obj = self . _lookup_child ( name ) if obj and iscontroller ( obj ) : return obj return None | Returns the appropriate controller for routing a custom action . |
23,739 | def _find_sub_controllers ( self , remainder , request ) : method = None for name in ( 'get_one' , 'get' ) : if hasattr ( self , name ) : method = name break if not method : return args = self . _get_args_for_controller ( getattr ( self , method ) ) fixed_args = len ( args ) - len ( request . pecan . get ( 'routing_args' , [ ] ) ) var_args = getargspec ( getattr ( self , method ) ) . varargs if var_args : for i , item in enumerate ( remainder ) : controller = self . _lookup_child ( item ) if controller and not ismethod ( controller ) : self . _set_routing_args ( request , remainder [ : i ] ) return lookup_controller ( controller , remainder [ i + 1 : ] , request ) elif fixed_args < len ( remainder ) and hasattr ( self , remainder [ fixed_args ] ) : controller = self . _lookup_child ( remainder [ fixed_args ] ) if not ismethod ( controller ) : self . _set_routing_args ( request , remainder [ : fixed_args ] ) return lookup_controller ( controller , remainder [ fixed_args + 1 : ] , request ) | Identifies the correct controller to route to by analyzing the request URI . |
23,740 | def _handle_get ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_get ) if not remainder or remainder == [ '' ] : remainder = list ( six . moves . filter ( bool , remainder ) ) controller = self . _find_controller ( 'get_all' , 'get' ) if controller : self . _handle_bad_rest_arguments ( controller , remainder , request ) return controller , [ ] abort ( 405 ) method_name = remainder [ - 1 ] if method_name in ( 'new' , 'edit' , 'delete' ) : if method_name == 'delete' : method_name = 'get_delete' controller = self . _find_controller ( method_name ) if controller : return controller , remainder [ : - 1 ] match = self . _handle_custom_action ( method , remainder , request ) if match : return match controller = self . _lookup_child ( remainder [ 0 ] ) if controller and not ismethod ( controller ) : return lookup_controller ( controller , remainder [ 1 : ] , request ) controller = self . _find_controller ( 'get_one' , 'get' ) if controller : self . _handle_bad_rest_arguments ( controller , remainder , request ) return controller , remainder abort ( 405 ) | Routes GET actions to the appropriate controller . |
23,741 | def _handle_delete ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_delete ) if remainder : match = self . _handle_custom_action ( method , remainder , request ) if match : return match controller = self . _lookup_child ( remainder [ 0 ] ) if controller and not ismethod ( controller ) : return lookup_controller ( controller , remainder [ 1 : ] , request ) controller = self . _find_controller ( 'post_delete' , 'delete' ) if controller : return controller , remainder if remainder : if self . _find_controller ( remainder [ 0 ] ) : abort ( 405 ) sub_controller = self . _lookup_child ( remainder [ 0 ] ) if sub_controller : return lookup_controller ( sub_controller , remainder [ 1 : ] , request ) abort ( 405 ) | Routes DELETE actions to the appropriate controller . |
23,742 | def _handle_post ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_post ) if remainder : match = self . _handle_custom_action ( method , remainder , request ) if match : return match controller = self . _lookup_child ( remainder [ 0 ] ) if controller and not ismethod ( controller ) : return lookup_controller ( controller , remainder [ 1 : ] , request ) controller = self . _find_controller ( method ) if controller : return controller , remainder abort ( 405 ) | Routes POST requests . |
23,743 | def format_line_context ( filename , lineno , context = 10 ) : with open ( filename ) as f : lines = f . readlines ( ) lineno = lineno - 1 if lineno > 0 : start_lineno = max ( lineno - context , 0 ) end_lineno = lineno + context lines = [ escape ( l , True ) for l in lines [ start_lineno : end_lineno ] ] i = lineno - start_lineno lines [ i ] = '<strong>%s</strong>' % lines [ i ] else : lines = [ escape ( l , True ) for l in lines [ : context ] ] msg = '<pre style="background-color:#ccc;padding:2em;">%s</pre>' return msg % '' . join ( lines ) | Formats the the line context for error rendering . |
23,744 | def make_ns ( self , ns ) : if self . namespace : val = { } val . update ( self . namespace ) val . update ( ns ) return val else : return ns | Returns the lazily created template namespace . |
23,745 | def get ( self , name , template_path ) : if name not in self . _renderers : cls = self . _renderer_classes . get ( name ) if cls is None : return None else : self . _renderers [ name ] = cls ( template_path , self . extra_vars ) return self . _renderers [ name ] | Returns the renderer object . |
23,746 | def default ( self , obj ) : if hasattr ( obj , '__json__' ) and six . callable ( obj . __json__ ) : return obj . __json__ ( ) elif isinstance ( obj , ( date , datetime ) ) : return str ( obj ) elif isinstance ( obj , Decimal ) : return float ( obj ) elif is_saobject ( obj ) : props = { } for key in obj . __dict__ : if not key . startswith ( '_sa_' ) : props [ key ] = getattr ( obj , key ) return props elif isinstance ( obj , ResultProxy ) : props = dict ( rows = list ( obj ) , count = obj . rowcount ) if props [ 'count' ] < 0 : props [ 'count' ] = len ( props [ 'rows' ] ) return props elif isinstance ( obj , RowProxy ) : return dict ( obj ) elif isinstance ( obj , webob_dicts ) : return obj . mixed ( ) else : return JSONEncoder . default ( self , obj ) | Converts an object and returns a JSON - friendly structure . |
23,747 | def getargspec ( method ) : argspec = _getargspec ( method ) args = argspec [ 0 ] if args and args [ 0 ] == 'self' : return argspec if hasattr ( method , '__func__' ) : method = method . __func__ func_closure = six . get_function_closure ( method ) if not func_closure : return argspec closure = None func_closure = filter ( lambda c : ( six . callable ( c . cell_contents ) and hasattr ( c . cell_contents , '__code__' ) ) , func_closure ) func_closure = sorted ( func_closure , key = lambda c : 'self' in c . cell_contents . __code__ . co_varnames , reverse = True ) closure = func_closure [ 0 ] method = closure . cell_contents return getargspec ( method ) | Drill through layers of decorators attempting to locate the actual argspec for a method . |
23,748 | def gunicorn_run ( ) : try : from gunicorn . app . wsgiapp import WSGIApplication except ImportError as exc : args = exc . args arg0 = args [ 0 ] if args else '' arg0 += ' (are you sure `gunicorn` is installed?)' exc . args = ( arg0 , ) + args [ 1 : ] raise class PecanApplication ( WSGIApplication ) : def init ( self , parser , opts , args ) : if len ( args ) != 1 : parser . error ( "No configuration file was specified." ) self . cfgfname = os . path . normpath ( os . path . join ( os . getcwd ( ) , args [ 0 ] ) ) self . cfgfname = os . path . abspath ( self . cfgfname ) if not os . path . exists ( self . cfgfname ) : parser . error ( "Config file not found: %s" % self . cfgfname ) from pecan . configuration import _runtime_conf , set_config set_config ( self . cfgfname , overwrite = True ) cfg = { } if _runtime_conf . get ( 'server' ) : server = _runtime_conf [ 'server' ] if hasattr ( server , 'host' ) and hasattr ( server , 'port' ) : cfg [ 'bind' ] = '%s:%s' % ( server . host , server . port ) return cfg def load ( self ) : from pecan . deploy import deploy return deploy ( self . cfgfname ) PecanApplication ( "%(prog)s [OPTIONS] config.py" ) . run ( ) | The gunicorn_pecan command for launching pecan applications |
23,749 | def serve ( self , app , conf ) : if self . args . reload : try : self . watch_and_spawn ( conf ) except ImportError : print ( 'The `--reload` option requires `watchdog` to be ' 'installed.' ) print ( ' $ pip install watchdog' ) else : self . _serve ( app , conf ) | A very simple approach for a WSGI server . |
23,750 | def log_message ( self , format , * args ) : code = args [ 1 ] [ 0 ] levels = { '4' : 'warning' , '5' : 'error' } log_handler = getattr ( logger , levels . get ( code , 'info' ) ) log_handler ( format % args ) | overrides the log_message method from the wsgiref server so that normal logging works with whatever configuration the application has been set to . |
23,751 | def expose ( template = None , generic = False , route = None , ** kw ) : content_type = kw . get ( 'content_type' , 'text/html' ) if template == 'json' : content_type = 'application/json' def decorate ( f ) : f . exposed = True cfg = _cfg ( f ) cfg [ 'explicit_content_type' ] = 'content_type' in kw if route : from pecan import routing if cfg . get ( 'generic_handler' ) : raise ValueError ( 'Path segments cannot be overridden for generic ' 'controllers.' ) routing . route ( route , f ) cfg [ 'content_type' ] = content_type cfg . setdefault ( 'template' , [ ] ) . append ( template ) cfg . setdefault ( 'content_types' , { } ) [ content_type ] = template if generic : if f . __name__ in ( '_default' , '_lookup' , '_route' ) : raise ValueError ( 'The special method %s cannot be used as a generic ' 'controller' % f . __name__ ) cfg [ 'generic' ] = True cfg [ 'generic_handlers' ] = dict ( DEFAULT = f ) cfg [ 'allowed_methods' ] = [ ] f . when = when_for ( f ) cfg [ 'argspec' ] = getargspec ( f ) return f return decorate | Decorator used to flag controller methods as being exposed for access via HTTP and to configure that access . |
23,752 | def to_dict ( self ) : return { "timestamp" : int ( self . timestamp ) , "timezone" : self . timezone , "time_of_day" : self . time_of_day , "day_of_week" : self . day_of_week , "day_of_month" : self . day_of_month , "month_of_year" : self . month_of_year , "utc_iso" : self . utc_iso } | Returns the Time instance as a usable dictionary for craftai |
23,753 | def timestamp_from_datetime ( date_time ) : if date_time . tzinfo is None : return time . mktime ( ( date_time . year , date_time . month , date_time . day , date_time . hour , date_time . minute , date_time . second , - 1 , - 1 , - 1 ) ) + date_time . microsecond / 1e6 return ( date_time - _EPOCH ) . total_seconds ( ) | Returns POSIX timestamp as float |
23,754 | def create_agent ( self , configuration , agent_id = "" ) : ct_header = { "Content-Type" : "application/json; charset=utf-8" } payload = { "configuration" : configuration } if agent_id != "" : self . _check_agent_id ( agent_id ) payload [ "id" ] = agent_id try : json_pl = json . dumps ( payload ) except TypeError as err : raise CraftAiBadRequestError ( "Invalid configuration or agent id given. {}" . format ( err . __str__ ( ) ) ) req_url = "{}/agents" . format ( self . _base_url ) resp = self . _requests_session . post ( req_url , headers = ct_header , data = json_pl ) agent = self . _decode_response ( resp ) return agent | Create an agent . |
23,755 | def delete_agent ( self , agent_id ) : self . _check_agent_id ( agent_id ) req_url = "{}/agents/{}" . format ( self . _base_url , agent_id ) resp = self . _requests_session . delete ( req_url ) decoded_resp = self . _decode_response ( resp ) return decoded_resp | Delete an agent . |
23,756 | def delete_agents_bulk ( self , payload ) : valid_indices , invalid_indices , invalid_agents = self . _check_agent_id_bulk ( payload ) valid_agents = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/agents" . format ( self . _base_url ) , "DELETE" ) if invalid_indices == [ ] : return valid_agents return self . _recreate_list_with_indices ( valid_indices , valid_agents , invalid_indices , invalid_agents ) | Delete a group of agents |
23,757 | def add_operations ( self , agent_id , operations ) : self . _check_agent_id ( agent_id ) ct_header = { "Content-Type" : "application/json; charset=utf-8" } offset = 0 is_looping = True while is_looping : next_offset = offset + self . config [ "operationsChunksSize" ] try : json_pl = json . dumps ( operations [ offset : next_offset ] ) except TypeError as err : raise CraftAiBadRequestError ( "Invalid configuration or agent id given. {}" . format ( err . __str__ ( ) ) ) req_url = "{}/agents/{}/context" . format ( self . _base_url , agent_id ) resp = self . _requests_session . post ( req_url , headers = ct_header , data = json_pl ) self . _decode_response ( resp ) if next_offset >= len ( operations ) : is_looping = False offset = next_offset return { "message" : "Successfully added %i operation(s) to the agent \"%s/%s/%s\" context." % ( len ( operations ) , self . config [ "owner" ] , self . config [ "project" ] , agent_id ) } | Add operations to an agent . |
23,758 | def _add_operations_bulk ( self , chunked_data ) : url = "{}/bulk/context" . format ( self . _base_url ) ct_header = { "Content-Type" : "application/json; charset=utf-8" } responses = [ ] for chunk in chunked_data : if len ( chunk ) > 1 : try : json_pl = json . dumps ( chunk ) except TypeError as err : raise CraftAiBadRequestError ( "Error while dumping the payload into json" "format when converting it for the bulk request. {}" . format ( err . __str__ ( ) ) ) resp = self . _requests_session . post ( url , headers = ct_header , data = json_pl ) resp = self . _decode_response ( resp ) responses += resp elif chunk : message = self . add_operations ( chunk [ 0 ] [ "id" ] , chunk [ 0 ] [ "operations" ] ) responses . append ( { "id" : chunk [ 0 ] [ "id" ] , "status" : 201 , "message" : message } ) if responses == [ ] : raise CraftAiBadRequestError ( "Invalid or empty set of operations given" ) return responses | Tool for the function add_operations_bulk . It send the requests to add the operations to the agents . |
23,759 | def add_operations_bulk ( self , payload ) : valid_indices , _ , _ = self . _check_agent_id_bulk ( payload ) valid_payload = [ payload [ i ] for i in valid_indices ] chunked_data = [ ] current_chunk = [ ] current_chunk_size = 0 for agent in valid_payload : if ( agent [ "operations" ] and isinstance ( agent [ "operations" ] , list ) ) : if current_chunk_size + len ( agent [ "operations" ] ) > self . config [ "operationsChunksSize" ] : chunked_data . append ( current_chunk ) current_chunk_size = 0 current_chunk = [ ] if len ( agent [ "operations" ] ) > self . config [ "operationsChunksSize" ] : chunked_data . append ( [ agent ] ) current_chunk_size = 0 else : current_chunk_size += len ( agent [ "operations" ] ) current_chunk . append ( agent ) if current_chunk : chunked_data . append ( current_chunk ) return self . _add_operations_bulk ( chunked_data ) | Add operations to a group of agents . |
23,760 | def _get_decision_tree ( self , agent_id , timestamp , version ) : headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version if timestamp is None : req_url = "{}/agents/{}/decision/tree?" . format ( self . _base_url , agent_id ) else : req_url = "{}/agents/{}/decision/tree?t={}" . format ( self . _base_url , agent_id , timestamp ) resp = self . _requests_session . get ( req_url ) decision_tree = self . _decode_response ( resp ) return decision_tree | Tool for the function get_decision_tree . |
23,761 | def get_decision_tree ( self , agent_id , timestamp = None , version = DEFAULT_DECISION_TREE_VERSION ) : self . _check_agent_id ( agent_id ) if self . _config [ "decisionTreeRetrievalTimeout" ] is False : return self . _get_decision_tree ( agent_id , timestamp , version ) start = current_time_ms ( ) while True : now = current_time_ms ( ) if now - start > self . _config [ "decisionTreeRetrievalTimeout" ] : raise CraftAiLongRequestTimeOutError ( ) try : return self . _get_decision_tree ( agent_id , timestamp , version ) except CraftAiLongRequestTimeOutError : continue | Get decision tree . |
23,762 | def _get_decision_trees_bulk ( self , payload , valid_indices , invalid_indices , invalid_dts ) : valid_dts = self . _create_and_send_json_bulk ( [ payload [ i ] for i in valid_indices ] , "{}/bulk/decision_tree" . format ( self . _base_url ) , "POST" ) if invalid_indices == [ ] : return valid_dts return self . _recreate_list_with_indices ( valid_indices , valid_dts , invalid_indices , invalid_dts ) | Tool for the function get_decision_trees_bulk . |
23,763 | def get_decision_trees_bulk ( self , payload , version = DEFAULT_DECISION_TREE_VERSION ) : headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version valid_indices , invalid_indices , invalid_dts = self . _check_agent_id_bulk ( payload ) if self . _config [ "decisionTreeRetrievalTimeout" ] is False : return self . _get_decision_trees_bulk ( payload , valid_indices , invalid_indices , invalid_dts ) start = current_time_ms ( ) while True : now = current_time_ms ( ) if now - start > self . _config [ "decisionTreeRetrievalTimeout" ] : raise CraftAiLongRequestTimeOutError ( ) try : return self . _get_decision_trees_bulk ( payload , valid_indices , invalid_indices , invalid_dts ) except CraftAiLongRequestTimeOutError : continue | Get a group of decision trees . |
23,764 | def _decode_response ( response ) : status_code = response . status_code message = "Status code " + str ( status_code ) try : message = CraftAIClient . _parse_body ( response ) [ "message" ] except ( CraftAiInternalError , KeyError , TypeError ) : pass if status_code in [ 200 , 201 , 204 , 207 ] : return CraftAIClient . _parse_body ( response ) else : raise CraftAIClient . _get_error_from_status ( status_code , message ) return None | Decode the response of a request . |
23,765 | def _decode_response_bulk ( response_bulk ) : resp = [ ] for response in response_bulk : if ( "status" in response ) and ( response . get ( "status" ) == 201 ) : agent = { "id" : response [ "id" ] , "message" : response [ "message" ] } resp . append ( agent ) elif "status" in response : status_code = response [ "status" ] message = response [ "message" ] agent = { "error" : CraftAIClient . _get_error_from_status ( status_code , message ) } try : agent [ "id" ] = response [ "id" ] except KeyError : pass resp . append ( agent ) else : resp . append ( response ) return resp | Decode the response of each agent given by a bulk function . |
23,766 | def _get_error_from_status ( status_code , message ) : if status_code == 202 : err = CraftAiLongRequestTimeOutError ( message ) elif status_code == 401 or status_code == 403 : err = CraftAiCredentialsError ( message ) elif status_code == 400 : err = CraftAiBadRequestError ( message ) elif status_code == 404 : err = CraftAiNotFoundError ( message ) elif status_code == 413 : err = CraftAiBadRequestError ( "Given payload is too large" ) elif status_code == 500 : err = CraftAiInternalError ( message ) elif status_code == 503 : err = CraftAiNetworkError ( ) elif status_code == 504 : err = CraftAiBadRequestError ( "Request has timed out" ) else : err = CraftAiUnknownError ( message ) return err | Give the error corresponding to the status code . |
23,767 | def _check_agent_id ( agent_id ) : if ( not isinstance ( agent_id , six . string_types ) or AGENT_ID_PATTERN . match ( agent_id ) is None ) : raise CraftAiBadRequestError ( ERROR_ID_MESSAGE ) | Checks that the given agent_id is a valid non - empty string . |
23,768 | def _check_agent_id_bulk ( self , payload ) : invalid_agent_indices = [ ] valid_agent_indices = [ ] invalid_payload = [ ] for index , agent in enumerate ( payload ) : try : if "id" in agent : self . _check_agent_id ( agent [ "id" ] ) except CraftAiBadRequestError : invalid_agent_indices . append ( index ) invalid_payload . append ( { "id" : agent [ "id" ] , "error" : CraftAiBadRequestError ( ERROR_ID_MESSAGE ) } ) else : try : json . dumps ( [ agent ] ) except TypeError as err : invalid_agent_indices . append ( index ) invalid_payload . append ( { "id" : agent [ "id" ] , "error" : err } ) else : valid_agent_indices . append ( index ) if len ( invalid_agent_indices ) == len ( payload ) : raise CraftAiBadRequestError ( ERROR_ID_MESSAGE ) return valid_agent_indices , invalid_agent_indices , invalid_payload | Checks that all the given agent ids are valid non - empty strings and if the agents are serializable . |
23,769 | def _recreate_list_with_indices ( indices1 , values1 , indices2 , values2 ) : list_indices = sorted ( indices1 + indices2 ) for i , index in enumerate ( list_indices ) : if i != index : raise CraftAiInternalError ( "The agents's indices are not continuous" ) full_list = [ None ] * ( len ( indices1 ) + len ( indices2 ) ) for i , index in enumerate ( indices1 ) : full_list [ index ] = values1 [ i ] for i , index in enumerate ( indices2 ) : full_list [ index ] = values2 [ i ] return full_list | Create a list in the right order . |
23,770 | def _create_and_send_json_bulk ( self , payload , req_url , request_type = "POST" ) : ct_header = { "Content-Type" : "application/json; charset=utf-8" } try : json_pl = json . dumps ( payload ) except TypeError as err : raise CraftAiBadRequestError ( "Error while dumping the payload into json" "format when converting it for the bulk request. {}" . format ( err . __str__ ( ) ) ) if request_type == "POST" : resp = self . _requests_session . post ( req_url , headers = ct_header , data = json_pl ) elif request_type == "DELETE" : resp = self . _requests_session . delete ( req_url , headers = ct_header , data = json_pl ) else : raise CraftAiBadRequestError ( "Request for the bulk API should be either a POST or DELETE" "request" ) agents = self . _decode_response ( resp ) agents = self . _decode_response_bulk ( agents ) return agents | Create a json do a request to the URL and process the response . |
23,771 | def construct_ctcp ( * parts ) : message = ' ' . join ( parts ) message = message . replace ( '\0' , CTCP_ESCAPE_CHAR + '0' ) message = message . replace ( '\n' , CTCP_ESCAPE_CHAR + 'n' ) message = message . replace ( '\r' , CTCP_ESCAPE_CHAR + 'r' ) message = message . replace ( CTCP_ESCAPE_CHAR , CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR ) return CTCP_DELIMITER + message + CTCP_DELIMITER | Construct CTCP message . |
23,772 | def parse_ctcp ( query ) : query = query . strip ( CTCP_DELIMITER ) query = query . replace ( CTCP_ESCAPE_CHAR + '0' , '\0' ) query = query . replace ( CTCP_ESCAPE_CHAR + 'n' , '\n' ) query = query . replace ( CTCP_ESCAPE_CHAR + 'r' , '\r' ) query = query . replace ( CTCP_ESCAPE_CHAR + CTCP_ESCAPE_CHAR , CTCP_ESCAPE_CHAR ) if ' ' in query : return query . split ( ' ' , 1 ) return query , None | Strip and de - quote CTCP messages . |
23,773 | async def on_ctcp_version ( self , by , target , contents ) : import pydle version = '{name} v{ver}' . format ( name = pydle . __name__ , ver = pydle . __version__ ) self . ctcp_reply ( by , 'VERSION' , version ) | Built - in CTCP version as some networks seem to require it . |
23,774 | async def ctcp ( self , target , query , contents = None ) : if self . is_channel ( target ) and not self . in_channel ( target ) : raise client . NotInChannel ( target ) await self . message ( target , construct_ctcp ( query , contents ) ) | Send a CTCP request to a target . |
23,775 | async def ctcp_reply ( self , target , query , response ) : if self . is_channel ( target ) and not self . in_channel ( target ) : raise client . NotInChannel ( target ) await self . notice ( target , construct_ctcp ( query , response ) ) | Send a CTCP reply to a target . |
23,776 | async def on_raw_privmsg ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , msg = message . params if is_ctcp ( msg ) : self . _sync_user ( nick , metadata ) type , contents = parse_ctcp ( msg ) attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) if hasattr ( self , attr ) : await getattr ( self , attr ) ( nick , target , contents ) await self . on_ctcp ( nick , target , type , contents ) else : await super ( ) . on_raw_privmsg ( message ) | Modify PRIVMSG to redirect CTCP messages . |
23,777 | async def on_raw_notice ( self , message ) : nick , metadata = self . _parse_user ( message . source ) target , msg = message . params if is_ctcp ( msg ) : self . _sync_user ( nick , metadata ) type , response = parse_ctcp ( msg ) attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) + '_reply' if hasattr ( self , attr ) : await getattr ( self , attr ) ( user , target , response ) await self . on_ctcp_reply ( user , target , type , response ) else : await super ( ) . on_raw_notice ( message ) | Modify NOTICE to redirect CTCP messages . |
23,778 | async def _register ( self ) : if self . registered : self . logger . debug ( "skipping cap registration, already registered!" ) return await self . rawmsg ( 'CAP' , 'LS' , '302' ) await super ( ) . _register ( ) | Hijack registration to send a CAP LS first . |
23,779 | async def _capability_negotiated ( self , capab ) : self . _capabilities_negotiating . discard ( capab ) if not self . _capabilities_requested and not self . _capabilities_negotiating : await self . rawmsg ( 'CAP' , 'END' ) | Mark capability as negotiated and end negotiation if we re done . |
23,780 | async def on_raw_cap ( self , message ) : target , subcommand = message . params [ : 2 ] params = message . params [ 2 : ] attr = 'on_raw_cap_' + pydle . protocol . identifierify ( subcommand ) if hasattr ( self , attr ) : await getattr ( self , attr ) ( params ) else : self . logger . warning ( 'Unknown CAP subcommand sent from server: %s' , subcommand ) | Handle CAP message . |
23,781 | async def on_raw_cap_ls ( self , params ) : to_request = set ( ) for capab in params [ 0 ] . split ( ) : capab , value = self . _capability_normalize ( capab ) if capab in self . _capabilities : continue attr = 'on_capability_' + pydle . protocol . identifierify ( capab ) + '_available' supported = ( await getattr ( self , attr ) ( value ) ) if hasattr ( self , attr ) else False if supported : if isinstance ( supported , str ) : to_request . add ( capab + CAPABILITY_VALUE_DIVIDER + supported ) else : to_request . add ( capab ) else : self . _capabilities [ capab ] = False if to_request : self . _capabilities_requested . update ( x . split ( CAPABILITY_VALUE_DIVIDER , 1 ) [ 0 ] for x in to_request ) await self . rawmsg ( 'CAP' , 'REQ' , ' ' . join ( to_request ) ) else : await self . rawmsg ( 'CAP' , 'END' ) | Update capability mapping . Request capabilities . |
23,782 | async def on_raw_cap_list ( self , params ) : self . _capabilities = { capab : False for capab in self . _capabilities } for capab in params [ 0 ] . split ( ) : capab , value = self . _capability_normalize ( capab ) self . _capabilities [ capab ] = value if value else True | Update active capabilities . |
23,783 | async def on_raw_410 ( self , message ) : self . logger . error ( 'Server sent "Unknown CAP subcommand: %s". Aborting capability negotiation.' , message . params [ 0 ] ) self . _capabilities_requested = set ( ) self . _capabilities_negotiating = set ( ) await self . rawmsg ( 'CAP' , 'END' ) | Unknown CAP subcommand or CAP error . Force - end negotiations . |
23,784 | async def _sasl_start ( self , mechanism ) : await self . rawmsg ( 'AUTHENTICATE' , mechanism ) _sasl_partial = partial ( self . _sasl_abort , timeout = True ) self . _sasl_timer = self . eventloop . call_later ( self . SASL_TIMEOUT , _sasl_partial ) | Initiate SASL authentication . |
23,785 | async def _sasl_abort ( self , timeout = False ) : if timeout : self . logger . error ( 'SASL authentication timed out: aborting.' ) else : self . logger . error ( 'SASL authentication aborted.' ) if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None await self . rawmsg ( 'AUTHENTICATE' , ABORT_MESSAGE ) await self . _capability_negotiated ( 'sasl' ) | Abort SASL authentication . |
23,786 | async def _sasl_end ( self ) : if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None await self . _capability_negotiated ( 'sasl' ) | Finalize SASL authentication . |
23,787 | async def _sasl_respond ( self ) : if self . _sasl_client : try : response = self . _sasl_client . process ( self . _sasl_challenge ) except puresasl . SASLError : response = None if response is None : self . logger . warning ( 'SASL challenge processing failed: aborting SASL authentication.' ) await self . _sasl_abort ( ) else : response = b'' response = base64 . b64encode ( response ) . decode ( self . encoding ) to_send = len ( response ) self . _sasl_challenge = b'' while to_send > 0 : await self . rawmsg ( 'AUTHENTICATE' , response [ : RESPONSE_LIMIT ] ) response = response [ RESPONSE_LIMIT : ] to_send -= RESPONSE_LIMIT if to_send == 0 : await self . rawmsg ( 'AUTHENTICATE' , EMPTY_MESSAGE ) | Respond to SASL challenge with response . |
23,788 | async def on_capability_sasl_available ( self , value ) : if value : self . _sasl_mechanisms = value . upper ( ) . split ( ',' ) else : self . _sasl_mechanisms = None if self . sasl_mechanism == 'EXTERNAL' or ( self . sasl_username and self . sasl_password ) : if self . sasl_mechanism == 'EXTERNAL' or puresasl : return True self . logger . warning ( 'SASL credentials set but puresasl module not found: not initiating SASL authentication.' ) return False | Check whether or not SASL is available . |
23,789 | async def on_capability_sasl_enabled ( self ) : if self . sasl_mechanism : if self . _sasl_mechanisms and self . sasl_mechanism not in self . _sasl_mechanisms : self . logger . warning ( 'Requested SASL mechanism is not in server mechanism list: aborting SASL authentication.' ) return cap . failed mechanisms = [ self . sasl_mechanism ] else : mechanisms = self . _sasl_mechanisms or [ 'PLAIN' ] if mechanisms == [ 'EXTERNAL' ] : mechanism = 'EXTERNAL' else : self . _sasl_client = puresasl . client . SASLClient ( self . connection . hostname , 'irc' , username = self . sasl_username , password = self . sasl_password , identity = self . sasl_identity ) try : self . _sasl_client . choose_mechanism ( mechanisms , allow_anonymous = False ) except puresasl . SASLError : self . logger . exception ( 'SASL mechanism choice failed: aborting SASL authentication.' ) return cap . FAILED mechanism = self . _sasl_client . mechanism . upper ( ) await self . _sasl_start ( mechanism ) return cap . NEGOTIATING | Start SASL authentication . |
23,790 | async def on_raw_authenticate ( self , message ) : if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None response = ' ' . join ( message . params ) if response != EMPTY_MESSAGE : self . _sasl_challenge += base64 . b64decode ( response ) if len ( response ) % RESPONSE_LIMIT > 0 : await self . _sasl_respond ( ) else : self . _sasl_timer = self . eventloop . call_later ( self . SASL_TIMEOUT , self . _sasl_abort ( timeout = True ) ) | Received part of the authentication challenge . |
23,791 | def monitor ( self , target ) : if 'monitor-notify' in self . _capabilities and not self . is_monitoring ( target ) : yield from self . rawmsg ( 'MONITOR' , '+' , target ) self . _monitoring . add ( target ) return True else : return False | Start monitoring the online status of a user . Returns whether or not the server supports monitoring . |
23,792 | def unmonitor ( self , target ) : if 'monitor-notify' in self . _capabilities and self . is_monitoring ( target ) : yield from self . rawmsg ( 'MONITOR' , '-' , target ) self . _monitoring . remove ( target ) return True else : return False | Stop monitoring the online status of a user . Returns whether or not the server supports monitoring . |
23,793 | async def on_raw_730 ( self , message ) : for nick in message . params [ 1 ] . split ( ',' ) : self . _create_user ( nick ) await self . on_user_online ( nickname ) | Someone we are monitoring just came online . |
23,794 | async def on_raw_731 ( self , message ) : for nick in message . params [ 1 ] . split ( ',' ) : self . _destroy_user ( nick , monitor_override = True ) await self . on_user_offline ( nickname ) | Someone we are monitoring got offline . |
23,795 | async def on_raw_account ( self , message ) : if not self . _capabilities . get ( 'account-notify' , False ) : return nick , metadata = self . _parse_user ( message . source ) account = message . params [ 0 ] if nick not in self . users : return self . _sync_user ( nick , metadata ) if account == NO_ACCOUNT : self . _sync_user ( nick , { 'account' : None , 'identified' : False } ) else : self . _sync_user ( nick , { 'account' : account , 'identified' : True } ) | Changes in the associated account for a nickname . |
23,796 | async def on_raw_away ( self , message ) : if 'away-notify' not in self . _capabilities or not self . _capabilities [ 'away-notify' ] : return nick , metadata = self . _parse_user ( message . source ) if nick not in self . users : return self . _sync_user ( nick , metadata ) self . users [ nick ] [ 'away' ] = len ( message . params ) > 0 self . users [ nick ] [ 'away_message' ] = message . params [ 0 ] if len ( message . params ) > 0 else None | Process AWAY messages . |
23,797 | async def on_raw_join ( self , message ) : if 'extended-join' in self . _capabilities and self . _capabilities [ 'extended-join' ] : nick , metadata = self . _parse_user ( message . source ) channels , account , realname = message . params self . _sync_user ( nick , metadata ) fakemsg = self . _create_message ( 'JOIN' , channels , source = message . source ) await super ( ) . on_raw_join ( fakemsg ) if account == NO_ACCOUNT : account = None self . users [ nick ] [ 'account' ] = account self . users [ nick ] [ 'realname' ] = realname else : await super ( ) . on_raw_join ( message ) | Process extended JOIN messages . |
23,798 | async def on_raw_metadata ( self , message ) : target , targetmeta = self . _parse_user ( message . params [ 0 ] ) key , visibility , value = message . params [ 1 : 4 ] if visibility == VISIBLITY_ALL : visibility = None if target in self . users : self . _sync_user ( target , targetmeta ) await self . on_metadata ( target , key , value , visibility = visibility ) | Metadata event . |
23,799 | async def on_raw_762 ( self , message ) : if not self . _metadata_queue : return nickname = self . _metadata_queue . pop ( ) future = self . _pending [ 'metadata' ] . pop ( nickname ) future . set_result ( self . _metadata_info . pop ( nickname ) ) | End of metadata . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.