idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
24,300
def after_init_app ( self , app : FlaskUnchained ) : from flask_wtf . csrf import generate_csrf @ app . after_request def set_csrf_cookie ( response ) : if response : response . set_cookie ( 'csrf_token' , generate_csrf ( ) ) return response
Configure an after request hook to set the csrf_token in the cookie .
24,301
def shell ( ) : ctx = _get_shell_ctx ( ) try : import IPython IPython . embed ( header = _get_shell_banner ( ) , user_ns = ctx ) except ImportError : import code code . interact ( banner = _get_shell_banner ( verbose = True ) , local = ctx )
Runs a shell in the app context . If IPython is installed it will be used otherwise the default Python shell is used .
24,302
def login ( self ) : form = self . _get_form ( 'SECURITY_LOGIN_FORM' ) if form . validate_on_submit ( ) : try : self . security_service . login_user ( form . user , form . remember . data ) except AuthenticationError as e : form . _errors = { '_error' : [ str ( e ) ] } else : self . after_this_request ( self . _commit ) if request . is_json : return self . jsonify ( { 'token' : form . user . get_auth_token ( ) , 'user' : form . user } ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.login' ) , category = 'success' ) return self . redirect ( 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) else : identity_attrs = app . config . SECURITY_USER_IDENTITY_ATTRIBUTES msg = f"Invalid {', '.join(identity_attrs)} and/or password." form . _errors = { '_error' : [ msg ] } for field in form . _fields . values ( ) : field . errors = None if form . errors and request . is_json : return self . jsonify ( { 'error' : form . errors . get ( '_error' ) [ 0 ] } , code = HTTPStatus . UNAUTHORIZED ) return self . render ( 'login' , login_user_form = form , ** self . security . run_ctx_processor ( 'login' ) )
View function to log a user in . Supports html and json requests .
24,303
def logout ( self ) : if current_user . is_authenticated : self . security_service . logout_user ( ) if request . is_json : return '' , HTTPStatus . NO_CONTENT self . flash ( _ ( 'flask_unchained.bundles.security:flash.logout' ) , category = 'success' ) return self . redirect ( 'SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT' )
View function to log a user out . Supports html and json requests .
24,304
def register ( self ) : form = self . _get_form ( 'SECURITY_REGISTER_FORM' ) if form . validate_on_submit ( ) : user = self . security_service . user_manager . create ( ** form . to_dict ( ) ) self . security_service . register_user ( user ) return self . redirect ( 'SECURITY_POST_REGISTER_REDIRECT_ENDPOINT' ) return self . render ( 'register' , register_user_form = form , ** self . security . run_ctx_processor ( 'register' ) )
View function to register user . Supports html and json requests .
24,305
def send_confirmation_email ( self ) : form = self . _get_form ( 'SECURITY_SEND_CONFIRMATION_FORM' ) if form . validate_on_submit ( ) : self . security_service . send_email_confirmation_instructions ( form . user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.confirmation_request' , email = form . user . email ) , category = 'info' ) if request . is_json : return '' , HTTPStatus . NO_CONTENT elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'send_confirmation_email' , send_confirmation_form = form , ** self . security . run_ctx_processor ( 'send_confirmation_email' ) )
View function which sends confirmation token and instructions to a user .
24,306
def confirm_email ( self , token ) : expired , invalid , user = self . security_utils_service . confirm_email_token_status ( token ) if not user or invalid : invalid = True self . flash ( _ ( 'flask_unchained.bundles.security:flash.invalid_confirmation_token' ) , category = 'error' ) already_confirmed = user is not None and user . confirmed_at is not None if expired and not already_confirmed : self . security_service . send_email_confirmation_instructions ( user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.confirmation_expired' , email = user . email , within = app . config . SECURITY_CONFIRM_EMAIL_WITHIN ) , category = 'error' ) if invalid or ( expired and not already_confirmed ) : return self . redirect ( 'SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT' , 'security_controller.send_confirmation_email' ) if self . security_service . confirm_user ( user ) : self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.email_confirmed' ) , category = 'success' ) else : self . flash ( _ ( 'flask_unchained.bundles.security:flash.already_confirmed' ) , category = 'info' ) if user != current_user : self . security_service . logout_user ( ) self . security_service . login_user ( user ) return self . redirect ( 'SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' )
View function to confirm a user s token from the confirmation email send to them . Supports html and json requests .
24,307
def forgot_password ( self ) : form = self . _get_form ( 'SECURITY_FORGOT_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . send_reset_password_instructions ( form . user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset_request' , email = form . user . email ) , category = 'info' ) if request . is_json : return '' , HTTPStatus . NO_CONTENT elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'forgot_password' , forgot_password_form = form , ** self . security . run_ctx_processor ( 'forgot_password' ) )
View function to request a password recovery email with a reset token . Supports html and json requests .
24,308
def reset_password ( self , token ) : expired , invalid , user = self . security_utils_service . reset_password_token_status ( token ) if invalid : self . flash ( _ ( 'flask_unchained.bundles.security:flash.invalid_reset_password_token' ) , category = 'error' ) return self . redirect ( 'SECURITY_INVALID_RESET_TOKEN_REDIRECT' ) elif expired : self . security_service . send_reset_password_instructions ( user ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset_expired' , email = user . email , within = app . config . SECURITY_RESET_PASSWORD_WITHIN ) , category = 'error' ) return self . redirect ( 'SECURITY_EXPIRED_RESET_TOKEN_REDIRECT' ) spa_redirect = app . config . SECURITY_API_RESET_PASSWORD_HTTP_GET_REDIRECT if request . method == 'GET' and spa_redirect : return self . redirect ( spa_redirect , token = token , _external = True ) form = self . _get_form ( 'SECURITY_RESET_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . reset_password ( user , form . password . data ) self . security_service . login_user ( user ) self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_reset' ) , category = 'success' ) if request . is_json : return self . jsonify ( { 'token' : user . get_auth_token ( ) , 'user' : user } ) return self . redirect ( 'SECURITY_POST_RESET_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'reset_password' , reset_password_form = form , reset_password_token = token , ** self . security . run_ctx_processor ( 'reset_password' ) )
View function verify a users reset password token from the email we sent to them . It also handles the form for them to set a new password . Supports html and json requests .
24,309
def change_password ( self ) : form = self . _get_form ( 'SECURITY_CHANGE_PASSWORD_FORM' ) if form . validate_on_submit ( ) : self . security_service . change_password ( current_user . _get_current_object ( ) , form . new_password . data ) self . after_this_request ( self . _commit ) self . flash ( _ ( 'flask_unchained.bundles.security:flash.password_change' ) , category = 'success' ) if request . is_json : return self . jsonify ( { 'token' : current_user . get_auth_token ( ) } ) return self . redirect ( 'SECURITY_POST_CHANGE_REDIRECT_ENDPOINT' , 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' ) elif form . errors and request . is_json : return self . errors ( form . errors ) return self . render ( 'change_password' , change_password_form = form , ** self . security . run_ctx_processor ( 'change_password' ) )
View function for a user to change their password . Supports html and json requests .
24,310
def _get_pwd_context ( self , app : FlaskUnchained ) -> CryptContext : pw_hash = app . config . SECURITY_PASSWORD_HASH schemes = app . config . SECURITY_PASSWORD_SCHEMES if pw_hash not in schemes : allowed = ( ', ' . join ( schemes [ : - 1 ] ) + ' and ' + schemes [ - 1 ] ) raise ValueError ( f'Invalid password hashing scheme {pw_hash}. ' f'Allowed values are {allowed}.' ) return CryptContext ( schemes = schemes , default = pw_hash , deprecated = app . config . SECURITY_DEPRECATED_PASSWORD_SCHEMES )
Get the password hashing context .
24,311
def _get_serializer ( self , app : FlaskUnchained , name : str ) -> URLSafeTimedSerializer : salt = app . config . get ( 'SECURITY_%s_SALT' % name . upper ( ) ) return URLSafeTimedSerializer ( secret_key = app . config . SECRET_KEY , salt = salt )
Get a URLSafeTimedSerializer for the given serialization context name .
24,312
def _request_loader ( self , request : Request ) -> Union [ User , AnonymousUser ] : header_key = self . token_authentication_header args_key = self . token_authentication_key token = request . args . get ( args_key , request . headers . get ( header_key , None ) ) if request . is_json : data = request . get_json ( silent = True ) or { } token = data . get ( args_key , token ) try : data = self . remember_token_serializer . loads ( token , max_age = self . token_max_age ) user = self . user_manager . get ( data [ 0 ] ) if user and self . security_utils_service . verify_hash ( data [ 1 ] , user . password ) : return user except : pass return self . login_manager . anonymous_user ( )
Attempt to load the user from the request token .
24,313
def bundles ( ctx ) : bundles = _get_bundles ( ctx . obj . data [ 'env' ] ) print_table ( ( 'Name' , 'Location' ) , [ ( bundle . name , f'{bundle.__module__}.{bundle.__class__.__name__}' ) for bundle in bundles ] )
List discovered bundles .
24,314
def argument ( * param_decls , cls = None , ** attrs ) : return click . argument ( * param_decls , cls = cls or Argument , ** attrs )
Arguments are positional parameters to a command . They generally provide fewer features than options but can have infinite nargs and are required by default .
24,315
def option ( * param_decls , cls = None , ** attrs ) : return click . option ( * param_decls , cls = cls or Option , ** attrs )
Options are usually optional values on the command line and have some extra features that arguments don t have .
24,316
def _openapi_json ( self ) : from pprint import pprint pprint ( self . to_dict ( ) ) return current_app . response_class ( json . dumps ( self . to_dict ( ) , indent = 4 ) , mimetype = 'application/json' )
Serve JSON spec file
24,317
def _openapi_redoc ( self ) : return render_template ( 'openapi/redoc.html' , title = self . app . config . API_TITLE or self . app . name , redoc_url = self . app . config . API_REDOC_SOURCE_URL )
Expose OpenAPI spec with ReDoc
24,318
def register_converter ( self , converter , conv_type , conv_format = None ) : self . flask_plugin . register_converter ( converter , conv_type , conv_format )
Register custom path parameter converter
24,319
def list_loader ( * decorator_args , model ) : def wrapped ( fn ) : @ wraps ( fn ) def decorated ( * args , ** kwargs ) : return fn ( model . query . all ( ) ) return decorated if decorator_args and callable ( decorator_args [ 0 ] ) : return wrapped ( decorator_args [ 0 ] ) return wrapped
Decorator to automatically query the database for all records of a model .
24,320
def post_loader ( * decorator_args , serializer ) : def wrapped ( fn ) : @ wraps ( fn ) def decorated ( * args , ** kwargs ) : return fn ( * serializer . load ( request . get_json ( ) ) ) return decorated if decorator_args and callable ( decorator_args [ 0 ] ) : return wrapped ( decorator_args [ 0 ] ) return wrapped
Decorator to automatically instantiate a model from json request data
24,321
def reset_command ( force ) : if not force : exit ( 'Cancelled.' ) click . echo ( 'Dropping DB tables.' ) drop_all ( ) click . echo ( 'Running DB migrations.' ) alembic . upgrade ( migrate . get_config ( None ) , 'head' ) click . echo ( 'Done.' )
Drop database tables and run migrations .
24,322
def load ( self , loader , pathname , recursive = False , encoding = None ) : if not encoding : encoding = self . _encoding or self . DEFAULT_ENCODING if self . _base_dir : pathname = os . path . join ( self . _base_dir , pathname ) if re . match ( WILDCARDS_REGEX , pathname ) : result = [ ] if PYTHON_MAYOR_MINOR >= '3.5' : iterator = iglob ( pathname , recursive = recursive ) else : iterator = iglob ( pathname ) for path in iterator : if os . path . isfile ( path ) : with io . open ( path , encoding = encoding ) as fp : result . append ( yaml . load ( fp , type ( loader ) ) ) return result with io . open ( pathname , encoding = encoding ) as fp : return yaml . load ( fp , type ( loader ) )
Once add the constructor to PyYAML loader class Loader will use this function to include other YAML fils on parsing !include tag
24,323
def add_to_loader_class ( cls , loader_class = None , tag = None , ** kwargs ) : if tag is None : tag = '' tag = tag . strip ( ) if not tag : tag = cls . DEFAULT_TAG_NAME if not tag . startswith ( '!' ) : raise ValueError ( '`tag` argument should start with character "!"' ) instance = cls ( ** kwargs ) if loader_class is None : if FullLoader : yaml . add_constructor ( tag , instance , FullLoader ) else : yaml . add_constructor ( tag , instance ) else : yaml . add_constructor ( tag , instance , loader_class ) return instance
Create an instance of the constructor and add it to the YAML Loader class
24,324
def print_table ( column_names : IterableOfStrings , rows : IterableOfTuples , column_alignments : Optional [ IterableOfStrings ] = None , primary_column_idx : int = 0 , ) -> None : header_template = '' row_template = '' table_width = 0 type_formatters = { int : 'd' , float : 'f' , str : 's' } types = [ type_formatters . get ( type ( x ) , 'r' ) for x in rows [ 0 ] ] alignments = { int : '>' , float : '>' } column_alignments = ( column_alignments or [ alignments . get ( type ( x ) , '<' ) for x in rows [ 0 ] ] ) def get_column_width ( idx ) : header_length = len ( column_names [ idx ] ) content_length = max ( len ( str ( row [ idx ] ) ) for row in rows ) return ( content_length if content_length > header_length else header_length ) for i in range ( 0 , len ( column_names ) ) : col_width = get_column_width ( i ) header_col_template = f'{{:{col_width}}}' col_template = f'{{:{column_alignments[i]}{col_width}{types[i]}}}' if i == 0 : header_template += header_col_template row_template += col_template table_width += col_width else : header_template += ' ' + header_col_template row_template += ' ' + col_template table_width += 2 + col_width if table_width < get_terminal_width ( ) : click . echo ( header_template . format ( * column_names ) ) click . echo ( '-' * table_width ) for row in rows : try : click . echo ( row_template . format ( * row ) ) except TypeError as e : raise TypeError ( f'{e}: {row!r}' ) else : max_label_width = max ( * [ len ( label ) for label in column_names ] ) non_primary_columns = [ ( i , col ) for i , col in enumerate ( column_names ) if i != primary_column_idx ] for row in rows : type_ = types [ primary_column_idx ] row_template = f'{{:>{max_label_width}s}}: {{:{type_}}}' click . echo ( row_template . format ( column_names [ primary_column_idx ] , row [ primary_column_idx ] ) ) for i , label in non_primary_columns : row_template = f'{{:>{max_label_width}s}}: {{:{types[i]}}}' click . echo ( row_template . format ( label , row [ i ] ) ) click . echo ( )
Prints a table of information to the console . Automatically determines if the console is wide enough and if not displays the information in list form .
24,325
def send ( self , message , envelope_from = None ) : assert message . send_to , "No recipients have been added" assert message . sender , ( "The message does not specify a sender and a default sender " "has not been configured" ) if message . has_bad_headers ( ) : raise BadHeaderError if message . date is None : message . date = time . time ( ) ret = None if self . host : ret = self . host . sendmail ( sanitize_address ( envelope_from or message . sender ) , list ( sanitize_addresses ( message . send_to ) ) , message . as_bytes ( ) if PY3 else message . as_string ( ) , message . mail_options , message . rcpt_options ) email_dispatched . send ( message , app = current_app . _get_current_object ( ) ) self . num_emails += 1 if self . num_emails == self . mail . max_emails : self . num_emails = 0 if self . host : self . host . quit ( ) self . host = self . configure_host ( ) return ret
Verifies and sends message .
24,326
def connect ( self ) : app = getattr ( self , "app" , None ) or current_app try : return Connection ( app . extensions [ 'mail' ] ) except KeyError : raise RuntimeError ( "The curent application was" " not configured with Flask-Mail" )
Opens a connection to the mail host .
24,327
def init_app ( self , app ) : state = self . init_mail ( app . config , app . debug , app . testing ) app . extensions = getattr ( app , 'extensions' , { } ) app . extensions [ 'mail' ] = state return state
Initializes your mail settings from the application settings .
24,328
def url_defaults ( self , fn ) : self . _defer ( lambda bp : bp . url_defaults ( fn ) ) return fn
Callback function for URL defaults for this bundle . It s called with the endpoint and values and should update the values passed in place .
24,329
def url_value_preprocessor ( self , fn ) : self . _defer ( lambda bp : bp . url_value_preprocessor ( fn ) ) return fn
Registers a function as URL value preprocessor for this bundle . It s called before the view functions are called and can modify the url values provided .
24,330
def errorhandler ( self , code_or_exception ) : def decorator ( fn ) : self . _defer ( lambda bp : bp . register_error_handler ( code_or_exception , fn ) ) return fn return decorator
Registers an error handler that becomes active for this bundle only . Please be aware that routing does not happen local to a bundle so an error handler for 404 usually is not handled by a bundle unless it is caused inside a view function . Another special case is the 500 internal server error which is always looked up from the application .
24,331
def controller ( url_prefix_or_controller_cls : Union [ str , Type [ Controller ] ] , controller_cls : Optional [ Type [ Controller ] ] = None , * , rules : Optional [ Iterable [ Union [ Route , RouteGenerator ] ] ] = None , ) -> RouteGenerator : url_prefix , controller_cls = _normalize_args ( url_prefix_or_controller_cls , controller_cls , _is_controller_cls ) url_prefix = url_prefix or controller_cls . Meta . url_prefix routes = [ ] controller_routes = getattr ( controller_cls , CONTROLLER_ROUTES_ATTR ) if rules is None : routes = controller_routes . values ( ) else : for route in _reduce_routes ( rules ) : existing = controller_routes . get ( route . method_name ) if existing : routes . append ( _inherit_route_options ( route , existing [ 0 ] ) ) else : routes . append ( route ) yield from _normalize_controller_routes ( routes , controller_cls , url_prefix = url_prefix )
This function is used to register a controller class s routes .
24,332
def service ( self , name : str = None ) : if self . _services_initialized : from warnings import warn warn ( 'Services have already been initialized. Please register ' f'{name} sooner.' ) return lambda x : x def wrapper ( service ) : self . register_service ( name , service ) return service return wrapper
Decorator to mark something as a service .
24,333
def register_service ( self , name : str , service : Any ) : if not isinstance ( service , type ) : if hasattr ( service , '__class__' ) : _ensure_service_name ( service . __class__ , name ) self . services [ name ] = service return if self . _services_initialized : from warnings import warn warn ( 'Services have already been initialized. Please register ' f'{name} sooner.' ) return self . _services_registry [ _ensure_service_name ( service , name ) ] = service
Method to register a service .
24,334
def before_request ( self , fn ) : self . _defer ( lambda app : app . before_request ( fn ) ) return fn
Registers a function to run before each request .
24,335
def before_first_request ( self , fn ) : self . _defer ( lambda app : app . before_first_request ( fn ) ) return fn
Registers a function to be run before the first request to this instance of the application .
24,336
def after_request ( self , fn ) : self . _defer ( lambda app : app . after_request ( fn ) ) return fn
Register a function to be run after each request .
24,337
def teardown_request ( self , fn ) : self . _defer ( lambda app : app . teardown_request ( fn ) ) return fn
Register a function to be run at the end of each request regardless of whether there was an exception or not . These functions are executed when the request context is popped even if not an actual request was performed .
24,338
def teardown_appcontext ( self , fn ) : self . _defer ( lambda app : app . teardown_appcontext ( fn ) ) return fn
Registers a function to be called when the application context ends . These functions are typically also called when the request context is popped .
24,339
def context_processor ( self , fn ) : self . _defer ( lambda app : app . context_processor ( fn ) ) return fn
Registers a template context processor function .
24,340
def shell_context_processor ( self , fn ) : self . _defer ( lambda app : app . shell_context_processor ( fn ) ) return fn
Registers a shell context processor function .
24,341
def url_defaults ( self , fn ) : self . _defer ( lambda app : app . url_defaults ( fn ) ) return fn
Callback function for URL defaults for all view functions of the application . It s called with the endpoint and values and should update the values passed in place .
24,342
def errorhandler ( self , code_or_exception ) : def decorator ( fn ) : self . _defer ( lambda app : app . register_error_handler ( code_or_exception , fn ) ) return fn return decorator
Register a function to handle errors by code or exception class .
24,343
def template_filter ( self , arg : Optional [ Callable ] = None , * , name : Optional [ str ] = None , pass_context : bool = False , inject : Optional [ Union [ bool , Iterable [ str ] ] ] = None , safe : bool = False , ) -> Callable : def wrapper ( fn ) : fn = _inject ( fn , inject ) if safe : fn = _make_safe ( fn ) if pass_context : fn = jinja2 . contextfilter ( fn ) self . _defer ( lambda app : app . add_template_filter ( fn , name = name ) ) return fn if callable ( arg ) : return wrapper ( arg ) return wrapper
Decorator to mark a function as a Jinja template filter .
24,344
def _reset ( self ) : self . bundles = AttrDict ( ) self . _bundles = _DeferredBundleFunctionsStore ( ) self . babel_bundle = None self . env = None self . extensions = AttrDict ( ) self . services = AttrDict ( ) self . _deferred_functions = [ ] self . _initialized = False self . _models_initialized = False self . _services_initialized = False self . _services_registry = { } self . _shell_ctx = { }
This method is for use by tests only!
24,345
def model_fields ( model , db_session = None , only = None , exclude = None , field_args = None , converter = None , exclude_pk = False , exclude_fk = False ) : mapper = model . _sa_class_manager . mapper converter = converter or _ModelConverter ( ) field_args = field_args or { } properties = [ ] for prop in mapper . iterate_properties : if getattr ( prop , 'columns' , None ) : if exclude_fk and prop . columns [ 0 ] . foreign_keys : continue elif exclude_pk and prop . columns [ 0 ] . primary_key : continue properties . append ( ( prop . key , prop ) ) if only is not None : properties = ( x for x in properties if x [ 0 ] in only ) elif exclude : properties = ( x for x in properties if x [ 0 ] not in exclude ) field_dict = { } for name , prop in properties : field = converter . convert ( model , mapper , prop , field_args . get ( name ) , db_session ) if field is not None : field_dict [ name ] = field return field_dict
Generate a dictionary of fields for a given SQLAlchemy model .
24,346
def url ( url : str , method : str ) : try : url_rule , params = ( current_app . url_map . bind ( 'localhost' ) . match ( url , method = method , return_rule = True ) ) except ( NotFound , MethodNotAllowed ) as e : click . secho ( str ( e ) , fg = 'white' , bg = 'red' ) else : headings = ( 'Method(s)' , 'Rule' , 'Params' , 'Endpoint' , 'View' , 'Options' ) print_table ( headings , [ ( _get_http_methods ( url_rule ) , url_rule . rule if url_rule . strict_slashes else url_rule . rule + '[/]' , _format_dict ( params ) , url_rule . endpoint , _get_rule_view ( url_rule ) , _format_rule_options ( url_rule ) ) ] , [ '<' if i > 0 else '>' for i , col in enumerate ( headings ) ] , primary_column_idx = 1 )
Show details for a specific URL .
24,347
def urls ( order_by : Optional [ str ] = None ) : url_rules : List [ Rule ] = current_app . url_map . _rules if order_by == 'view' : url_rules = sorted ( url_rules , key = lambda rule : _get_rule_view ( rule ) ) elif order_by != 'priority' : url_rules = sorted ( url_rules , key = lambda rule : getattr ( rule , order_by ) ) headings = ( 'Method(s)' , 'Rule' , 'Endpoint' , 'View' , 'Options' ) print_table ( headings , [ ( _get_http_methods ( url_rule ) , url_rule . rule if url_rule . strict_slashes else url_rule . rule . rstrip ( '/' ) + '[/]' , url_rule . endpoint , _get_rule_view ( url_rule ) , _format_rule_options ( url_rule ) , ) for url_rule in url_rules ] , [ '<' if i > 0 else '>' for i , col in enumerate ( headings ) ] , primary_column_idx = 1 )
List all URLs registered with the app .
24,348
def register_converter ( self , converter , conv_type , conv_format = None , * , name = None ) : if name : self . app . url_map . converters [ name ] = converter self . spec . register_converter ( converter , conv_type , conv_format )
Register custom path parameter converter .
24,349
def run_hook ( self , app : FlaskUnchained , bundles : List [ Bundle ] ) : self . process_objects ( app , self . collect_from_bundles ( bundles ) )
Hook entry point . Override to disable standard behavior of iterating over bundles to discover objects and processing them .
24,350
def singularize ( word , pos = NOUN , custom = None ) : if custom and word in custom : return custom [ word ] if "-" in word : w = word . split ( "-" ) if len ( w ) > 1 and w [ 1 ] in plural_prepositions : return singularize ( w [ 0 ] , pos , custom ) + "-" + "-" . join ( w [ 1 : ] ) if word . endswith ( "'" ) : return singularize ( word [ : - 1 ] ) + "'s" w = word . lower ( ) for x in singular_uninflected : if x . endswith ( w ) : return word for x in singular_uncountable : if x . endswith ( w ) : return word for x in singular_ie : if w . endswith ( x + "s" ) : return w [ : - 1 ] for x in singular_irregular : if w . endswith ( x ) : return re . sub ( '(?i)' + x + '$' , singular_irregular [ x ] , word ) for suffix , inflection in singular_rules : m = suffix . search ( word ) g = m and m . groups ( ) or [ ] if m : for k in range ( len ( g ) ) : if g [ k ] is None : inflection = inflection . replace ( '\\' + str ( k + 1 ) , '' ) return suffix . sub ( inflection , word ) return word
Returns the singular of a given word .
24,351
def create_basic_app ( cls , bundles = None , _config_overrides = None ) : bundles = bundles or [ ] name = bundles [ - 1 ] . module_name if bundles else 'basic_app' app = FlaskUnchained ( name , template_folder = os . path . join ( os . path . dirname ( __file__ ) , 'templates' ) ) for bundle in bundles : bundle . before_init_app ( app ) unchained . init_app ( app , DEV , bundles , _config_overrides = _config_overrides ) for bundle in bundles : bundle . after_init_app ( app ) return app
Creates a fake app for use while developing
24,352
def list_roles ( ) : roles = role_manager . all ( ) if roles : print_table ( [ 'ID' , 'Name' ] , [ ( role . id , role . name ) for role in roles ] ) else : click . echo ( 'No roles found.' )
List roles .
24,353
def create_role ( name ) : role = role_manager . create ( name = name ) if click . confirm ( f'Are you sure you want to create {role!r}?' ) : role_manager . save ( role , commit = True ) click . echo ( f'Successfully created {role!r}' ) else : click . echo ( 'Cancelled.' )
Create a new role .
24,354
def delete_role ( query ) : role = _query_to_role ( query ) if click . confirm ( f'Are you sure you want to delete {role!r}?' ) : role_manager . delete ( role , commit = True ) click . echo ( f'Successfully deleted {role!r}' ) else : click . echo ( 'Cancelled.' )
Delete a role .
24,355
def slugify ( field_name , slug_field_name = None , mutable = False ) : slug_field_name = slug_field_name or 'slug' def _set_slug ( target , value , old_value , _ , mutable = False ) : existing_slug = getattr ( target , slug_field_name ) if existing_slug and not mutable : return if value and ( not existing_slug or value != old_value ) : setattr ( target , slug_field_name , _slugify ( value ) ) def wrapper ( cls ) : event . listen ( getattr ( cls , field_name ) , 'set' , partial ( _set_slug , mutable = mutable ) ) return cls return wrapper
Class decorator to specify a field to slugify . Slugs are immutable by default unless mutable = True is passed .
24,356
def get_message_plain_text ( msg : Message ) : if msg . body : return msg . body if BeautifulSoup is None or not msg . html : return msg . html plain_text = '\n' . join ( line . strip ( ) for line in BeautifulSoup ( msg . html , 'lxml' ) . text . splitlines ( ) ) return re . sub ( r'\n\n+' , '\n\n' , plain_text ) . strip ( )
Converts an HTML message to plain text .
24,357
def _send_mail ( subject_or_message : Optional [ Union [ str , Message ] ] = None , to : Optional [ Union [ str , List [ str ] ] ] = None , template : Optional [ str ] = None , ** kwargs ) : subject_or_message = subject_or_message or kwargs . pop ( 'subject' ) to = to or kwargs . pop ( 'recipients' , [ ] ) msg = make_message ( subject_or_message , to , template , ** kwargs ) with mail . connect ( ) as connection : connection . send ( msg )
The default function used for sending emails .
24,358
def extract ( domain ) : translations_dir = _get_translations_dir ( ) domain = _get_translations_domain ( domain ) babel_cfg = _get_babel_cfg ( ) pot = os . path . join ( translations_dir , f'{domain}.pot' ) return _run ( f'extract -F {babel_cfg} -o {pot} .' )
Extract newly added translations keys from source code .
24,359
def init ( lang , domain ) : translations_dir = _get_translations_dir ( ) domain = _get_translations_domain ( domain ) pot = os . path . join ( translations_dir , f'{domain}.pot' ) return _run ( f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain}' )
Initialize translations for a language code .
24,360
def update ( domain ) : translations_dir = _get_translations_dir ( ) domain = _get_translations_domain ( domain ) pot = os . path . join ( translations_dir , f'{domain}.pot' ) return _run ( f'update -i {pot} -d {translations_dir} --domain={domain}' )
Update language - specific translations files with new keys discovered by flask babel extract .
24,361
def get_value ( self , meta , base_model_meta , mcs_args : McsArgs ) : if mcs_args . Meta . abstract : return None value = getattr ( base_model_meta , self . name , { } ) or { } value . update ( getattr ( meta , self . name , { } ) ) return value
overridden to merge with inherited value
24,362
def flash ( self , msg : str , category : Optional [ str ] = None ) : if not request . is_json and app . config . FLASH_MESSAGES : flash ( msg , category )
Convenience method for flashing messages .
24,363
def render ( self , template_name : str , ** ctx ) : if '.' not in template_name : template_file_extension = ( self . Meta . template_file_extension or app . config . TEMPLATE_FILE_EXTENSION ) template_name = f'{template_name}{template_file_extension}' if self . Meta . template_folder_name and os . sep not in template_name : template_name = os . path . join ( self . Meta . template_folder_name , template_name ) return render_template ( template_name , ** ctx )
Convenience method for rendering a template .
24,364
def redirect ( self , where : Optional [ str ] = None , default : Optional [ str ] = None , override : Optional [ str ] = None , ** url_kwargs ) : return redirect ( where , default , override , _cls = self , ** url_kwargs )
Convenience method for returning redirect responses .
24,365
def jsonify ( self , data : Any , code : Union [ int , Tuple [ int , str , str ] ] = HTTPStatus . OK , headers : Optional [ Dict [ str , str ] ] = None , ) : return jsonify ( data ) , code , headers or { }
Convenience method to return json responses .
24,366
def errors ( self , errors : List [ str ] , code : Union [ int , Tuple [ int , str , str ] ] = HTTPStatus . BAD_REQUEST , key : str = 'errors' , headers : Optional [ Dict [ str , str ] ] = None , ) : return jsonify ( { key : errors } ) , code , headers or { }
Convenience method to return errors as json .
24,367
def set_password ( query , password , send_email ) : user = _query_to_user ( query ) if click . confirm ( f'Are you sure you want to change {user!r}\'s password?' ) : security_service . change_password ( user , password , send_email = send_email ) user_manager . save ( user , commit = True ) click . echo ( f'Successfully updated password for {user!r}' ) else : click . echo ( 'Cancelled.' )
Set a user s password .
24,368
def confirm_user ( query ) : user = _query_to_user ( query ) if click . confirm ( f'Are you sure you want to confirm {user!r}?' ) : if security_service . confirm_user ( user ) : click . echo ( f'Successfully confirmed {user!r} at ' f'{user.confirmed_at.strftime("%Y-%m-%d %H:%M:%S%z")}' ) user_manager . save ( user , commit = True ) else : click . echo ( f'{user!r} has already been confirmed.' ) else : click . echo ( 'Cancelled.' )
Confirm a user account .
24,369
def add_role_to_user ( user , role ) : user = _query_to_user ( user ) role = _query_to_role ( role ) if click . confirm ( f'Are you sure you want to add {role!r} to {user!r}?' ) : user . roles . append ( role ) user_manager . save ( user , commit = True ) click . echo ( f'Successfully added {role!r} to {user!r}' ) else : click . echo ( 'Cancelled.' )
Add a role to a user .
24,370
def remove_role_from_user ( user , role ) : user = _query_to_user ( user ) role = _query_to_role ( role ) if click . confirm ( f'Are you sure you want to remove {role!r} from {user!r}?' ) : user . roles . remove ( role ) user_manager . save ( user , commit = True ) click . echo ( f'Successfully removed {role!r} from {user!r}' ) else : click . echo ( 'Cancelled.' )
Remove a role from a user .
24,371
def anonymous_user_required ( * decorator_args , msg = None , category = None , redirect_url = None ) : def wrapper ( fn ) : @ wraps ( fn ) def decorated ( * args , ** kwargs ) : if current_user . is_authenticated : if request . is_json : abort ( HTTPStatus . FORBIDDEN ) else : if msg : flash ( msg , category ) return redirect ( 'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT' , override = redirect_url ) return fn ( * args , ** kwargs ) return decorated if decorator_args and callable ( decorator_args [ 0 ] ) : return wrapper ( decorator_args [ 0 ] ) return wrapper
Decorator requiring that there is no user currently logged in .
24,372
def login_user ( self , user : User , remember : Optional [ bool ] = None , duration : Optional [ timedelta ] = None , force : bool = False , fresh : bool = True , ) -> bool : if not force : if not user . active : raise AuthenticationError ( _ ( 'flask_unchained.bundles.security:error.disabled_account' ) ) if ( not user . confirmed_at and self . security . confirmable and not self . security . login_without_confirmation ) : raise AuthenticationError ( _ ( 'flask_unchained.bundles.security:error.confirmation_required' ) ) if not user . password : raise AuthenticationError ( _ ( 'flask_unchained.bundles.security:error.password_not_set' ) ) session [ 'user_id' ] = getattr ( user , user . Meta . pk ) session [ '_fresh' ] = fresh session [ '_id' ] = app . login_manager . _session_identifier_generator ( ) if remember is None : remember = app . config . SECURITY_DEFAULT_REMEMBER_ME if remember : session [ 'remember' ] = 'set' if duration is not None : try : session [ 'remember_seconds' ] = duration . total_seconds ( ) except AttributeError : raise Exception ( 'duration must be a datetime.timedelta, ' 'instead got: {0}' . format ( duration ) ) _request_ctx_stack . top . user = user user_logged_in . send ( app . _get_current_object ( ) , user = user ) identity_changed . send ( app . _get_current_object ( ) , identity = Identity ( user . id ) ) return True
Logs a user in . You should pass the actual user object to this . If the user s active property is False they will not be logged in unless force is True .
24,373
def register_user ( self , user , allow_login = None , send_email = None , _force_login_without_confirmation = False ) : should_login_user = ( not self . security . confirmable or self . security . login_without_confirmation or _force_login_without_confirmation ) should_login_user = ( should_login_user if allow_login is None else allow_login and should_login_user ) if should_login_user : user . active = True self . user_manager . save ( user , commit = True ) confirmation_link , token = None , None if self . security . confirmable and not _force_login_without_confirmation : token = self . security_utils_service . generate_confirmation_token ( user ) confirmation_link = url_for ( 'security_controller.confirm_email' , token = token , _external = True ) user_registered . send ( app . _get_current_object ( ) , user = user , confirm_token = token ) if ( send_email or ( send_email is None and app . config . SECURITY_SEND_REGISTER_EMAIL ) ) : self . send_mail ( _ ( 'flask_unchained.bundles.security:email_subject.register' ) , to = user . email , template = 'security/email/welcome.html' , user = user , confirmation_link = confirmation_link ) if should_login_user : return self . login_user ( user , force = _force_login_without_confirmation ) return False
Service method to register a user .
24,374
def change_password ( self , user , password , send_email = None ) : user . password = password self . user_manager . save ( user ) if send_email or ( app . config . SECURITY_SEND_PASSWORD_CHANGED_EMAIL and send_email is None ) : self . send_mail ( _ ( 'flask_unchained.bundles.security:email_subject.password_changed_notice' ) , to = user . email , template = 'security/email/password_changed_notice.html' , user = user ) password_changed . send ( app . _get_current_object ( ) , user = user )
Service method to change a user s password .
24,375
def confirm_user ( self , user ) : if user . confirmed_at is not None : return False user . confirmed_at = self . security . datetime_factory ( ) user . active = True self . user_manager . save ( user ) user_confirmed . send ( app . _get_current_object ( ) , user = user ) return True
Confirms the specified user . Returns False if the user has already been confirmed True otherwise .
24,376
def send_mail ( self , subject , to , template , ** template_ctx ) : if not self . mail : from warnings import warn warn ( 'Attempting to send mail without the mail bundle installed! ' 'Please install it, or fix your configuration.' ) return self . mail . send ( subject , to , template , ** dict ( ** self . security . run_ctx_processor ( 'mail' ) , ** template_ctx ) )
Utility method to send mail with the mail template context .
24,377
def get_declared_fields ( mcs , klass , cls_fields , inherited_fields , dict_cls ) : opts = klass . opts converter = opts . model_converter ( schema_cls = klass ) base_fields = _BaseModelSerializerMetaclass . get_declared_fields ( klass , cls_fields , inherited_fields , dict_cls ) declared_fields = mcs . get_fields ( converter , opts , base_fields , dict_cls ) if declared_fields is not None : declared_fields . update ( base_fields ) return declared_fields
Updates declared fields with fields converted from the SQLAlchemy model passed as the model class Meta option .
24,378
def reset ( self , clear = False ) : if self . _executing : self . _executing = False self . _request_info [ 'execute' ] = { } self . _reading = False self . _highlighter . highlighting_on = False if clear : self . _control . clear ( ) if self . _display_banner : if self . kernel_banner : self . _append_plain_text ( self . kernel_banner ) self . _append_plain_text ( self . banner ) self . _show_interpreter_prompt ( )
Overridden to customize the order that the banners are printed
24,379
def log_connection_info ( self ) : _ctrl_c_lines = [ 'NOTE: Ctrl-C does not work to exit from the command line.' , 'To exit, just close the window, type "exit" or "quit" at the ' 'qtconsole prompt, or use Ctrl-\\ in UNIX-like environments ' '(at the command prompt).' ] for line in _ctrl_c_lines : io . rprint ( line ) self . ports = dict ( shell = self . shell_port , iopub = self . iopub_port , stdin = self . stdin_port , hb = self . hb_port , control = self . control_port )
Overridden to customize the start - up message printed to the terminal
24,380
def url_for ( endpoint_or_url_or_config_key : str , _anchor : Optional [ str ] = None , _cls : Optional [ Union [ object , type ] ] = None , _external : Optional [ bool ] = False , _external_host : Optional [ str ] = None , _method : Optional [ str ] = None , _scheme : Optional [ str ] = None , ** values , ) -> Union [ str , None ] : what = endpoint_or_url_or_config_key if what and what . isupper ( ) : what = current_app . config . get ( what ) if isinstance ( what , LocalProxy ) : what = what . _get_current_object ( ) if not what or '/' in what : return what flask_url_for_kwargs = dict ( _anchor = _anchor , _external = _external , _external_host = _external_host , _method = _method , _scheme = _scheme , ** values ) if _cls and '.' not in what : controller_routes = getattr ( _cls , CONTROLLER_ROUTES_ATTR ) method_routes = controller_routes . get ( what ) try : return _url_for ( method_routes [ 0 ] . endpoint , ** flask_url_for_kwargs ) except ( BuildError , IndexError , TypeError , ) : pass return _url_for ( what , ** flask_url_for_kwargs )
An improved version of flask s url_for function
24,381
def redirect ( where : Optional [ str ] = None , default : Optional [ str ] = None , override : Optional [ str ] = None , _anchor : Optional [ str ] = None , _cls : Optional [ Union [ object , type ] ] = None , _external : Optional [ bool ] = False , _external_host : Optional [ str ] = None , _method : Optional [ str ] = None , _scheme : Optional [ str ] = None , ** values , ) -> Response : flask_url_for_kwargs = dict ( _anchor = _anchor , _external = _external , _external_host = _external_host , _method = _method , _scheme = _scheme , ** values ) urls = [ url_for ( request . args . get ( 'next' ) , ** flask_url_for_kwargs ) , url_for ( request . form . get ( 'next' ) , ** flask_url_for_kwargs ) ] if where : urls . append ( url_for ( where , _cls = _cls , ** flask_url_for_kwargs ) ) if default : urls . append ( url_for ( default , _cls = _cls , ** flask_url_for_kwargs ) ) if override : urls . insert ( 0 , url_for ( override , _cls = _cls , ** flask_url_for_kwargs ) ) for url in urls : if _validate_redirect_url ( url , _external_host ) : return flask_redirect ( url ) return flask_redirect ( '/' )
An improved version of flask s redirect function
24,382
def _url_for ( endpoint : str , ** values ) -> Union [ str , None ] : _external_host = values . pop ( '_external_host' , None ) is_external = bool ( _external_host or values . get ( '_external' ) ) external_host = _external_host or current_app . config . get ( 'EXTERNAL_SERVER_NAME' ) if not is_external or not external_host : return flask_url_for ( endpoint , ** values ) if '://' not in external_host : external_host = f'http://{external_host}' values . pop ( '_external' ) return external_host . rstrip ( '/' ) + flask_url_for ( endpoint , ** values )
The same as flask s url_for except this also supports building external urls for hosts that are different from app . config . SERVER_NAME . One case where this is especially useful is for single page apps where the frontend is not hosted by the same server as the backend but the backend still needs to generate urls to frontend routes
24,383
def roles_required ( * roles ) : def wrapper ( fn ) : @ wraps ( fn ) def decorated_view ( * args , ** kwargs ) : perms = [ Permission ( RoleNeed ( role ) ) for role in roles ] for perm in perms : if not perm . can ( ) : abort ( HTTPStatus . FORBIDDEN ) return fn ( * args , ** kwargs ) return decorated_view return wrapper
Decorator which specifies that a user must have all the specified roles .
24,384
def verify_hash ( self , hashed_data , compare_data ) : return self . security . hashing_context . verify ( encode_string ( compare_data ) , hashed_data )
Verify a hash in the security token hashing context .
24,385
def auth_required ( decorated_fn = None , ** role_rules ) : required_roles = [ ] one_of_roles = [ ] if not ( decorated_fn and callable ( decorated_fn ) ) : if 'role' in role_rules and 'roles' in role_rules : raise RuntimeError ( 'specify only one of `role` or `roles` kwargs' ) elif 'role' in role_rules : required_roles = [ role_rules [ 'role' ] ] elif 'roles' in role_rules : required_roles = role_rules [ 'roles' ] if 'one_of' in role_rules : one_of_roles = role_rules [ 'one_of' ] def wrapper ( fn ) : @ wraps ( fn ) @ _auth_required ( ) @ roles_required ( * required_roles ) @ roles_accepted ( * one_of_roles ) def decorated ( * args , ** kwargs ) : return fn ( * args , ** kwargs ) return decorated if decorated_fn and callable ( decorated_fn ) : return wrapper ( decorated_fn ) return wrapper
Decorator for requiring an authenticated user optionally with roles .
24,386
def _auth_required ( ) : login_mechanisms = ( ( 'token' , lambda : _check_token ( ) ) , ( 'session' , lambda : current_user . is_authenticated ) , ) def wrapper ( fn ) : @ wraps ( fn ) def decorated_view ( * args , ** kwargs ) : for method , mechanism in login_mechanisms : if mechanism and mechanism ( ) : return fn ( * args , ** kwargs ) return security . _unauthorized_callback ( ) return decorated_view return wrapper
Decorator that protects endpoints through token and session auth mechanisms
24,387
def async_mail_task ( subject_or_message , to = None , template = None , ** kwargs ) : to = to or kwargs . pop ( 'recipients' , [ ] ) msg = make_message ( subject_or_message , to , template , ** kwargs ) with mail . connect ( ) as connection : connection . send ( msg )
Celery task to send emails asynchronously using the mail bundle .
24,388
def after_init_app ( self , app : FlaskUnchained ) : self . set_json_encoder ( app ) app . before_first_request ( self . register_model_resources )
Configure the JSON encoder for Flask to be able to serialize Enums LocalProxy objects and SQLAlchemy models .
24,389
def endpoint ( self ) : if self . _endpoint : return self . _endpoint elif self . _controller_cls : endpoint = f'{snake_case(self._controller_cls.__name__)}.{self.method_name}' return endpoint if not self . bp_name else f'{self.bp_name}.{endpoint}' elif self . bp_name : return f'{self.bp_name}.{self.method_name}' return f'{self.view_func.__module__}.{self.method_name}'
The endpoint for this route .
24,390
def method_name ( self ) : if isinstance ( self . view_func , str ) : return self . view_func return self . view_func . __name__
The string name of this route s view function .
24,391
def module_name ( self ) : if not self . view_func : return None elif self . _controller_cls : rv = inspect . getmodule ( self . _controller_cls ) . __name__ return rv return inspect . getmodule ( self . view_func ) . __name__
The module where this route s view function was defined .
24,392
def full_rule ( self ) : return join ( self . bp_prefix , self . rule , trailing_slash = self . rule . endswith ( '/' ) )
The full url rule for this route including any blueprint prefix .
24,393
def full_name ( self ) : if not self . view_func : return None prefix = self . view_func . __module__ if self . _controller_cls : prefix = f'{prefix}.{self._controller_cls.__name__}' return f'{prefix}.{self.method_name}'
The full name of this route s view function including the module path and controller name if any .
24,394
def project ( dest , app_bundle , force , dev , admin , api , celery , graphene , mail , oauth , security , session , sqlalchemy , webpack ) : if os . path . exists ( dest ) and os . listdir ( dest ) and not force : if not click . confirm ( f'WARNING: Project directory {dest!r} exists and is ' f'not empty. It will be DELETED!!! Continue?' ) : click . echo ( f'Exiting.' ) sys . exit ( 1 ) ctx = dict ( dev = dev , admin = admin , api = api , celery = celery , graphene = graphene , mail = mail , oauth = oauth , security = security or oauth , session = security or session , sqlalchemy = security or sqlalchemy , webpack = webpack ) ctx [ 'requirements' ] = [ k for k , v in ctx . items ( ) if v ] ctx [ 'app_bundle_module_name' ] = app_bundle copy_file_tree ( PROJECT_TEMPLATE , dest , ctx , [ ( option , files ) for option , files in [ ( 'api' , [ 'app/serializers' ] ) , ( 'celery' , [ 'app/tasks' , 'celery_app.py' ] ) , ( 'graphene' , [ 'app/graphql' ] ) , ( 'mail' , [ 'templates/email' ] ) , ( 'security' , [ 'app/models/role.py' , 'app/models/user.py' , 'db/fixtures/Role.yaml' , 'db/fixtures/User.yaml' ] ) , ( 'webpack' , [ 'assets' , 'package.json' , 'webpack' ] ) , ] if not ctx [ option ] ] ) click . echo ( f'Successfully created a new project at: {dest}' )
Create a new Flask Unchained project .
24,395
def produce ( self , * args , ** kwargs ) : new_plugins = [ ] for p in self . _plugins : r = p ( * args , ** kwargs ) new_plugins . append ( r ) return PluginManager ( new_plugins )
Produce a new set of plugins treating the current set as plugin factories .
24,396
def call ( self , methodname , * args , ** kwargs ) : for plugin in self . _plugins : method = getattr ( plugin , methodname , None ) if method is None : continue yield method ( * args , ** kwargs )
Call a common method on all the plugins if it exists .
24,397
def pipe ( self , methodname , first_arg , * args , ** kwargs ) : for plugin in self . _plugins : method = getattr ( plugin , methodname , None ) if method is None : continue r = method ( first_arg , * args , ** kwargs ) if r is not None : first_arg = r return r
Call a common method on all the plugins if it exists . The return value of each call becomes the replaces the first argument in the given argument list to pass to the next .
24,398
def unified_load ( namespace , subclasses = None , recurse = False ) : if subclasses is not None : return ClassLoader ( recurse = recurse ) . load ( namespace , subclasses = subclasses ) else : return ModuleLoader ( recurse = recurse ) . load ( namespace )
Provides a unified interface to both the module and class loaders finding modules by default or classes if given a subclasses parameter .
24,399
def _fill_cache ( self , namespace ) : modules = self . _findPluginModules ( namespace ) self . _cache = list ( modules )
Load all modules found in a namespace