idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
23,600 | 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' : # Notfound handler is, in fact, a controller, so stop # traversal return obj , remainder else : # Notfound handler is an internal redirect, so continue # traversal result = handle_lookup_traversal ( obj , remainder ) if result : # If no arguments are passed to the _lookup, yet the # argspec requires at least one, raise a 404 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 . | 343 | 17 |
23,601 | 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 : ] # are we traversing to another controller 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 : # the URL has hit an index method without a trailing slash 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 # Last-ditch effort: if there's not a matching subcontroller, no # `_default`, no `_lookup`, and no `_route`, look to see if there's # an `index` that has a generic method defined for the current request # method. 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 . | 665 | 30 |
23,602 | 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 | 58 | 22 |
23,603 | 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 . | 123 | 12 |
23,604 | 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 | 56 | 13 |
23,605 | 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 . | 111 | 8 |
23,606 | def cross_boundary ( prev_obj , obj ) : if prev_obj is None : return if isinstance ( obj , _SecuredAttribute ) : # a secure attribute can live in unsecure class so we have to set # while we walk the route 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 . | 107 | 9 |
23,607 | 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 . | 51 | 8 |
23,608 | 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 . | 43 | 11 |
23,609 | def make_app ( root , * * kw ) : # Pass logging configuration (if it exists) on to the Python logging module logging = kw . get ( 'logging' , { } ) debug = kw . get ( 'debug' , False ) if logging : if debug : try : # # By default, Python 2.7+ silences DeprecationWarnings. # However, if conf.app.debug is True, we should probably ensure # that users see these types of warnings. # from logging import captureWarnings captureWarnings ( True ) warnings . simplefilter ( "default" , DeprecationWarning ) except ImportError : # No captureWarnings on Python 2.6, DeprecationWarnings are on pass if isinstance ( logging , Config ) : logging = logging . to_dict ( ) if 'version' not in logging : logging [ 'version' ] = 1 load_logging_config ( logging ) # Instantiate the WSGI app by passing **kw onward app = Pecan ( root , * * kw ) # Optionally wrap the app in another WSGI app wrap_app = kw . get ( 'wrap_app' , None ) if wrap_app : app = wrap_app ( app ) # Configuration for serving custom error messages errors = kw . get ( 'errors' , getattr ( conf . app , 'errors' , { } ) ) if errors : app = middleware . errordocument . ErrorDocumentMiddleware ( app , errors ) # Included for internal redirect support app = middleware . recursive . RecursiveMiddleware ( app ) # When in debug mode, load exception debugging middleware 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 ) # Support for serving static files (for development convenience) 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 . | 626 | 32 |
23,610 | 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 ) # First, make sure the code will actually compile (and has no SyntaxErrors) with open ( abspath , 'rb' ) as f : compiled = compile ( f . read ( ) , abspath , 'exec' ) # Next, attempt to actually import the file as a module. # This provides more verbose import-related error reporting than 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 ] ) ) # If we were able to import as a module, actually exec the compiled code exec ( compiled , globals ( ) , conf_dict ) conf_dict [ '__file__' ] = abspath return conf_from_dict ( conf_dict ) | Creates a configuration dictionary from a file . | 291 | 9 |
23,611 | 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 . | 113 | 30 |
23,612 | 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 . | 80 | 9 |
23,613 | def set_config ( config , overwrite = False ) : if config is None : config = get_conf_path_from_env ( ) # must be after the fallback other a bad fallback will incorrectly clear 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 . | 157 | 6 |
23,614 | 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 . | 131 | 8 |
23,615 | 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 . | 34 | 13 |
23,616 | 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 . | 51 | 15 |
23,617 | def abort ( status_code , detail = '' , headers = None , comment = None , * * kw ) : # If there is a traceback, we need to catch it for a re-raise 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 : # Using exec to avoid python 3 parsers from crashing exec ( 'raise webob_exception, None, traceback' ) finally : # Per the suggestion of the Python docs, delete the traceback object del traceback | Raise an HTTP status code as specified . Useful for returning status codes like 401 Unauthorized or 403 Forbidden . | 163 | 22 |
23,618 | 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 . | 250 | 29 |
23,619 | 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 . | 156 | 16 |
23,620 | 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 . | 205 | 13 |
23,621 | 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 . | 86 | 12 |
23,622 | 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 ) # on_error hooks can choose to return a Response, which will # be used instead of the standard error pages. if hook_type == 'on_error' and isinstance ( result , WebObResponse ) : return result | Processes hooks of the specified type . | 109 | 8 |
23,623 | 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 ) # pop off `self` pecan_state = state . request . pecan remainder = [ x for x in remainder if x ] if im_self is not None : args . append ( im_self ) # grab the routing args from nested REST controllers if 'routing_args' in pecan_state : remainder = pecan_state [ 'routing_args' ] + list ( remainder ) del pecan_state [ 'routing_args' ] # handle positional arguments if valid_args and remainder : args . extend ( remainder [ : len ( valid_args ) ] ) remainder = remainder [ len ( valid_args ) : ] valid_args = valid_args [ len ( args ) : ] # handle wildcard arguments if [ i for i in remainder if i ] : if not argspec [ 1 ] : abort ( 404 ) varargs . extend ( remainder ) # get the default positional arguments if argspec [ 3 ] : defaults = dict ( izip ( argspec [ 0 ] [ - len ( argspec [ 3 ] ) : ] , argspec [ 3 ] ) ) else : defaults = dict ( ) # handle positional GET/POST params 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 # handle wildcard GET/POST params 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 . | 418 | 19 |
23,624 | def run ( self , args ) : super ( ShellCommand , self ) . run ( args ) # load the application app = self . load_app ( ) # prepare the locals locs = dict ( __name__ = 'pecan-admin' ) locs [ 'wsgiapp' ] = app locs [ 'app' ] = TestApp ( app ) model = self . load_model ( app . config ) if model : locs [ 'model' ] = model # insert the pecan locals from pecan import abort , conf , redirect , request , response locs [ 'abort' ] = abort locs [ 'conf' ] = conf locs [ 'redirect' ] = redirect locs [ 'request' ] = request locs [ 'response' ] = response # prepare the banner 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 . | 323 | 18 |
23,625 | 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 | 66 | 5 |
23,626 | 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 : # For controllers that are missing intermediate IDs # (e.g., /authors/books vs /authors/1/books), return a 404 for an # invalid path. 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 . | 115 | 33 |
23,627 | def _route ( self , args , request = None ) : if request is None : from pecan import request # convention uses "_method" to handle browser-unsupported methods method = request . params . get ( '_method' , request . method ) . lower ( ) # make sure DELETE/PUT requests don't use GET if request . method == 'GET' and method in ( 'delete' , 'put' ) : abort ( 405 ) # check for nested controllers result = self . _find_sub_controllers ( args , request ) if result : return result # handle the request 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 ) # # If the signature of the handler does not match the number # of remaining positional arguments, attempt to handle # a _lookup method (if it exists) # 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 : # # If the matching handler results in a 400, 404, or 405, attempt to # handle a _lookup method (if it exists) # _lookup_result = self . _handle_lookup ( args , request ) if _lookup_result : return _lookup_result # Build a correct Allow: header 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 the result return result | Routes a request to the appropriate controller and returns its result . | 536 | 14 |
23,628 | 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 . | 42 | 10 |
23,629 | def _find_sub_controllers ( self , remainder , request ) : # need either a get_one or get to parse args method = None for name in ( 'get_one' , 'get' ) : if hasattr ( self , name ) : method = name break if not method : return # get the args to figure out how much to chop off 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 # attempt to locate a sub-controller 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 . | 314 | 14 |
23,630 | def _handle_get ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_get ) # route to a get_all or get if no additional parts are available 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 ] # check for new/edit/delete GET requests 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 ) # finally, check for the regular get_one/get requests 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 . | 335 | 10 |
23,631 | 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 ) # check for post_delete/delete requests first controller = self . _find_controller ( 'post_delete' , 'delete' ) if controller : return controller , remainder # if no controller exists, try routing to a sub-controller; note that # since this is a DELETE verb, any local exposes are 405'd 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 . | 239 | 12 |
23,632 | def _handle_post ( self , method , remainder , request = None ) : if request is None : self . _raise_method_deprecation_warning ( self . _handle_post ) # check for custom POST/PUT requests 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 ) # check for regular POST/PUT requests controller = self . _find_controller ( method ) if controller : return controller , remainder abort ( 405 ) | Routes POST requests . | 145 | 6 |
23,633 | def format_line_context ( filename , lineno , context = 10 ) : with open ( filename ) as f : lines = f . readlines ( ) lineno = lineno - 1 # files are indexed by 1 not 0 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 . | 186 | 10 |
23,634 | 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 . | 39 | 8 |
23,635 | 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 . | 79 | 6 |
23,636 | 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 ) : # XXX What to do about JSONEncoder crappy handling of Decimals? # SimpleJSON has better Decimal encoding than the std lib # but only in recent versions 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 . | 269 | 12 |
23,637 | 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 ) # NOTE(sileht): if the closure is None we cannot look deeper, # so return actual argspec, this occurs when the method # is static for example. if not func_closure : return argspec closure = None # In the case of deeply nested decorators (with arguments), it's possible # that there are several callables in scope; Take a best guess and go # with the one that looks most like a pecan controller function # (has a __code__ object, and 'self' is the first argument) 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 . | 292 | 18 |
23,638 | 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 ) # If available, use the host and port from the pecan config file 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 | 391 | 13 |
23,639 | 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 . | 76 | 10 |
23,640 | 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 . | 69 | 30 |
23,641 | 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 ) : # flag the method as exposed f . exposed = True cfg = _cfg ( f ) cfg [ 'explicit_content_type' ] = 'content_type' in kw if route : # This import is here to avoid a circular import issue from pecan import routing if cfg . get ( 'generic_handler' ) : raise ValueError ( 'Path segments cannot be overridden for generic ' 'controllers.' ) routing . route ( route , f ) # set a "pecan" attribute, where we will store details cfg [ 'content_type' ] = content_type cfg . setdefault ( 'template' , [ ] ) . append ( template ) cfg . setdefault ( 'content_types' , { } ) [ content_type ] = template # handle generic controllers 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 ) # store the arguments for this controller method 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 . | 368 | 21 |
23,642 | 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 | 110 | 11 |
23,643 | 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 | 105 | 6 |
23,644 | def create_agent ( self , configuration , agent_id = "" ) : # Extra header in addition to the main session's ct_header = { "Content-Type" : "application/json; charset=utf-8" } # Building payload and checking that it is valid for a JSON # serialization payload = { "configuration" : configuration } if agent_id != "" : # Raises an error when agent_id is invalid 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 . | 227 | 4 |
23,645 | def delete_agent ( self , agent_id ) : # Raises an error when agent_id is invalid 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 . | 97 | 4 |
23,646 | def delete_agents_bulk ( self , payload ) : # Check all ids, raise an error if all ids are invalid valid_indices , invalid_indices , invalid_agents = self . _check_agent_id_bulk ( payload ) # Create the json file with the agents with valid id and send it 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 # Put the valid and invalid agents in their original index return self . _recreate_list_with_indices ( valid_indices , valid_agents , invalid_indices , invalid_agents ) | Delete a group of agents | 183 | 5 |
23,647 | def add_operations ( self , agent_id , operations ) : # Raises an error when agent_id is invalid self . _check_agent_id ( agent_id ) # Extra header in addition to the main session's 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 . | 311 | 6 |
23,648 | 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 . | 276 | 24 |
23,649 | def add_operations_bulk ( self , payload ) : # Check all ids, raise an error if all ids are invalid 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 . | 291 | 8 |
23,650 | def _get_decision_tree ( self , agent_id , timestamp , version ) : headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version # If we give no timestamp the default behaviour is to give the tree from the latest timestamp 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 . | 172 | 11 |
23,651 | def get_decision_tree ( self , agent_id , timestamp = None , version = DEFAULT_DECISION_TREE_VERSION ) : # Raises an error when agent_id is invalid self . _check_agent_id ( agent_id ) if self . _config [ "decisionTreeRetrievalTimeout" ] is False : # Don't retry 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" ] : # Client side timeout raise CraftAiLongRequestTimeOutError ( ) try : return self . _get_decision_tree ( agent_id , timestamp , version ) except CraftAiLongRequestTimeOutError : # Do nothing and continue. continue | Get decision tree . | 194 | 4 |
23,652 | 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 # Put the valid and invalid decision trees in their original index return self . _recreate_list_with_indices ( valid_indices , valid_dts , invalid_indices , invalid_dts ) | Tool for the function get_decision_trees_bulk . | 152 | 15 |
23,653 | def get_decision_trees_bulk ( self , payload , version = DEFAULT_DECISION_TREE_VERSION ) : # payload = [{"id": agent_id, "timestamp": timestamp}] headers = self . _headers . copy ( ) headers [ "x-craft-ai-tree-version" ] = version # Check all ids, raise an error if all ids are invalid valid_indices , invalid_indices , invalid_dts = self . _check_agent_id_bulk ( payload ) if self . _config [ "decisionTreeRetrievalTimeout" ] is False : # Don't retry 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" ] : # Client side timeout raise CraftAiLongRequestTimeOutError ( ) try : return self . _get_decision_trees_bulk ( payload , valid_indices , invalid_indices , invalid_dts ) except CraftAiLongRequestTimeOutError : # Do nothing and continue. continue | Get a group of decision trees . | 282 | 7 |
23,654 | 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 . | 125 | 8 |
23,655 | 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 . | 172 | 13 |
23,656 | 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 ( """Service momentarily unavailable, please try""" """again in a few minutes. If the problem """ """persists please contact us at support@craft.ai""" ) elif status_code == 504 : err = CraftAiBadRequestError ( "Request has timed out" ) else : err = CraftAiUnknownError ( message ) return err | Give the error corresponding to the status code . | 231 | 9 |
23,657 | 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 . | 66 | 16 |
23,658 | def _check_agent_id_bulk ( self , payload ) : invalid_agent_indices = [ ] valid_agent_indices = [ ] invalid_payload = [ ] for index , agent in enumerate ( payload ) : # Check if the agent ID is valid 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 : # Check if the agent is serializable 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 . | 273 | 23 |
23,659 | def _recreate_list_with_indices ( indices1 , values1 , indices2 , values2 ) : # Test if indices are continuous 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 . | 153 | 8 |
23,660 | def _create_and_send_json_bulk ( self , payload , req_url , request_type = "POST" ) : # Extra header in addition to the main session's 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 . | 262 | 14 |
23,661 | 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 . | 152 | 6 |
23,662 | 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 . | 156 | 11 |
23,663 | 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 . | 73 | 15 |
23,664 | 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 . | 64 | 10 |
23,665 | 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 . | 64 | 10 |
23,666 | 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 ) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) if hasattr ( self , attr ) : await getattr ( self , attr ) ( nick , target , contents ) # Invoke global handler. await self . on_ctcp ( nick , target , type , contents ) else : await super ( ) . on_raw_privmsg ( message ) | Modify PRIVMSG to redirect CTCP messages . | 162 | 13 |
23,667 | 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 ) # Find dedicated handler if it exists. attr = 'on_ctcp_' + pydle . protocol . identifierify ( type ) + '_reply' if hasattr ( self , attr ) : await getattr ( self , attr ) ( user , target , response ) # Invoke global handler. await self . on_ctcp_reply ( user , target , type , response ) else : await super ( ) . on_raw_notice ( message ) | Modify NOTICE to redirect CTCP messages . | 167 | 10 |
23,668 | async def _register ( self ) : if self . registered : self . logger . debug ( "skipping cap registration, already registered!" ) return # Ask server to list capabilities. await self . rawmsg ( 'CAP' , 'LS' , '302' ) # Register as usual. await super ( ) . _register ( ) | Hijack registration to send a CAP LS first . | 70 | 11 |
23,669 | 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 . | 68 | 12 |
23,670 | async def on_raw_cap ( self , message ) : target , subcommand = message . params [ : 2 ] params = message . params [ 2 : ] # Call handler. 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 . | 109 | 4 |
23,671 | async def on_raw_cap_ls ( self , params ) : to_request = set ( ) for capab in params [ 0 ] . split ( ) : capab , value = self . _capability_normalize ( capab ) # Only process new capabilities. if capab in self . _capabilities : continue # Check if we support the capability. 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 : # Request some capabilities. 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 : # No capabilities requested, end negotiation. await self . rawmsg ( 'CAP' , 'END' ) | Update capability mapping . Request capabilities . | 284 | 7 |
23,672 | 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 . | 82 | 4 |
23,673 | 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 . | 84 | 13 |
23,674 | async def _sasl_start ( self , mechanism ) : # The rest will be handled in on_raw_authenticate()/_sasl_respond(). await self . rawmsg ( 'AUTHENTICATE' , mechanism ) # create a partial, required for our callback to get the kwarg _sasl_partial = partial ( self . _sasl_abort , timeout = True ) self . _sasl_timer = self . eventloop . call_later ( self . SASL_TIMEOUT , _sasl_partial ) | Initiate SASL authentication . | 123 | 7 |
23,675 | 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 # We're done here. await self . rawmsg ( 'AUTHENTICATE' , ABORT_MESSAGE ) await self . _capability_negotiated ( 'sasl' ) | Abort SASL authentication . | 132 | 6 |
23,676 | 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 . | 62 | 6 |
23,677 | async def _sasl_respond ( self ) : # Formulate a response. 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'' # Send response in chunks. while to_send > 0 : await self . rawmsg ( 'AUTHENTICATE' , response [ : RESPONSE_LIMIT ] ) response = response [ RESPONSE_LIMIT : ] to_send -= RESPONSE_LIMIT # If our message fit exactly in SASL_RESPOSE_LIMIT-byte chunks, send an empty message to indicate we're done. if to_send == 0 : await self . rawmsg ( 'AUTHENTICATE' , EMPTY_MESSAGE ) | Respond to SASL challenge with response . | 273 | 9 |
23,678 | 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 . | 147 | 9 |
23,679 | 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 ( ) # Initialize SASL. await self . _sasl_start ( mechanism ) # Tell caller we need more time, and to not end capability negotiation just yet. return cap . NEGOTIATING | Start SASL authentication . | 331 | 5 |
23,680 | async def on_raw_authenticate ( self , message ) : # Cancel timeout timer. if self . _sasl_timer : self . _sasl_timer . cancel ( ) self . _sasl_timer = None # Add response data. response = ' ' . join ( message . params ) if response != EMPTY_MESSAGE : self . _sasl_challenge += base64 . b64decode ( response ) # If the response ain't exactly SASL_RESPONSE_LIMIT bytes long, it's the end. Process. if len ( response ) % RESPONSE_LIMIT > 0 : await self . _sasl_respond ( ) else : # Response not done yet. Restart timer. self . _sasl_timer = self . eventloop . call_later ( self . SASL_TIMEOUT , self . _sasl_abort ( timeout = True ) ) | Received part of the authentication challenge . | 207 | 8 |
23,681 | 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 . | 68 | 18 |
23,682 | 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 . | 67 | 18 |
23,683 | 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 . | 50 | 8 |
23,684 | 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 . | 59 | 7 |
23,685 | 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 . | 134 | 9 |
23,686 | 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 . | 131 | 5 |
23,687 | 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 ) # Emit a fake join message. 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 . | 177 | 6 |
23,688 | 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 . | 96 | 4 |
23,689 | async def on_raw_762 ( self , message ) : # No way to figure out whose query this belongs to, so make a best guess # it was the first one. 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 . | 95 | 4 |
23,690 | async def on_raw_765 ( self , message ) : target , targetmeta = self . _parse_user ( message . params [ 0 ] ) if target not in self . _pending [ 'metadata' ] : return if target in self . users : self . _sync_user ( target , targetmeta ) self . _metadata_queue . remove ( target ) del self . _metadata_info [ target ] future = self . _pending [ 'metadata' ] . pop ( target ) future . set_result ( None ) | Invalid metadata target . | 114 | 4 |
23,691 | async def connect ( self ) : self . tls_context = None if self . tls : self . tls_context = self . create_tls_context ( ) ( self . reader , self . writer ) = await asyncio . open_connection ( host = self . hostname , port = self . port , local_addr = self . source_address , ssl = self . tls_context , loop = self . eventloop ) | Connect to target . | 97 | 4 |
23,692 | def create_tls_context ( self ) : # Create context manually, as we're going to set our own options. tls_context = ssl . SSLContext ( ssl . PROTOCOL_SSLv23 ) # Load client/server certificate. if self . tls_certificate_file : tls_context . load_cert_chain ( self . tls_certificate_file , self . tls_certificate_keyfile , password = self . tls_certificate_password ) # Set some relevant options: # - No server should use SSLv2 or SSLv3 any more, they are outdated and full of security holes. (RFC6176, RFC7568) # - Disable compression in order to counter the CRIME attack. (https://en.wikipedia.org/wiki/CRIME_%28security_exploit%29) # - Disable session resumption to maintain perfect forward secrecy. (https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/) for opt in [ 'NO_SSLv2' , 'NO_SSLv3' , 'NO_COMPRESSION' , 'NO_TICKET' ] : if hasattr ( ssl , 'OP_' + opt ) : tls_context . options |= getattr ( ssl , 'OP_' + opt ) # Set TLS verification options. if self . tls_verify : # Set our custom verification callback, if the library supports it. tls_context . set_servername_callback ( self . verify_tls ) # Load certificate verification paths. tls_context . set_default_verify_paths ( ) if sys . platform in DEFAULT_CA_PATHS and path . isdir ( DEFAULT_CA_PATHS [ sys . platform ] ) : tls_context . load_verify_locations ( capath = DEFAULT_CA_PATHS [ sys . platform ] ) # If we want to verify the TLS connection, we first need a certicate. # Check this certificate and its entire chain, if possible, against revocation lists. tls_context . verify_mode = ssl . CERT_REQUIRED tls_context . verify_flags = ssl . VERIFY_CRL_CHECK_CHAIN return tls_context | Transform our regular socket into a TLS socket . | 525 | 9 |
23,693 | async def disconnect ( self ) : if not self . connected : return self . writer . close ( ) self . reader = None self . writer = None | Disconnect from target . | 32 | 5 |
23,694 | async def send ( self , data ) : self . writer . write ( data ) await self . writer . drain ( ) | Add data to send queue . | 26 | 6 |
23,695 | def identifierify ( name ) : name = name . lower ( ) name = re . sub ( '[^a-z0-9]' , '_' , name ) return name | Clean up name so it works for a Python identifier . | 38 | 11 |
23,696 | async def _register ( self ) : if self . registered : return self . _registration_attempts += 1 # Don't throttle during registration, most ircds don't care for flooding during registration, # and it might speed it up significantly. self . connection . throttle = False # Password first. if self . password : await self . rawmsg ( 'PASS' , self . password ) # Then nickname... await self . set_nickname ( self . _attempt_nicknames . pop ( 0 ) ) # And now for the rest of the user information. await self . rawmsg ( 'USER' , self . username , '0' , '*' , self . realname ) | Perform IRC connection registration . | 148 | 6 |
23,697 | async def _registration_completed ( self , message ) : if not self . registered : # Re-enable throttling. self . registered = True self . connection . throttle = True target = message . params [ 0 ] fakemsg = self . _create_message ( 'NICK' , target , source = self . nickname ) await self . on_raw_nick ( fakemsg ) | We re connected and registered . Receive proper nickname and emit fake NICK message . | 83 | 17 |
23,698 | def _has_message ( self ) : sep = protocol . MINIMAL_LINE_SEPARATOR . encode ( self . encoding ) return sep in self . _receive_buffer | Whether or not we have messages available for processing . | 39 | 10 |
23,699 | async def join ( self , channel , password = None ) : if self . in_channel ( channel ) : raise AlreadyInChannel ( channel ) if password : await self . rawmsg ( 'JOIN' , channel , password ) else : await self . rawmsg ( 'JOIN' , channel ) | Join channel optionally with password . | 64 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.