idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
24,200
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 .
78
4
24,201
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 .
44
28
24,202
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 .
44
20
24,203
def _openapi_json ( self ) : # We don't use Flask.jsonify here as it would sort the keys # alphabetically while we want to preserve the order. 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
90
5
24,204
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
65
8
24,205
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
44
5
24,206
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 .
82
15
24,207
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
90
13
24,208
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 .
74
8
24,209
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 : # pylint:disable=invalid-name result . append ( yaml . load ( fp , type ( loader ) ) ) return result with io . open ( pathname , encoding = encoding ) as fp : # pylint:disable=invalid-name 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
233
30
24,210
def add_to_loader_class ( cls , loader_class = None , tag = None , * * kwargs ) : # type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor 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
182
17
24,211
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 # check if we can format the table horizontally 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}' ) # otherwise format it vertically 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 .
659
29
24,212
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 .
250
6
24,213
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 .
61
9
24,214
def init_app ( self , app ) : state = self . init_mail ( app . config , app . debug , app . testing ) # register extension with app app . extensions = getattr ( app , 'extensions' , { } ) app . extensions [ 'mail' ] = state return state
Initializes your mail settings from the application settings .
64
10
24,215
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 .
34
26
24,216
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 .
38
30
24,217
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 .
55
65
24,218
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 .
261
12
24,219
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 .
69
10
24,220
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 .
120
6
24,221
def before_request ( self , fn ) : self . _defer ( lambda app : app . before_request ( fn ) ) return fn
Registers a function to run before each request .
30
10
24,222
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 .
34
18
24,223
def after_request ( self , fn ) : self . _defer ( lambda app : app . after_request ( fn ) ) return fn
Register a function to be run after each request .
30
10
24,224
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 .
34
41
24,225
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 .
36
26
24,226
def context_processor ( self , fn ) : self . _defer ( lambda app : app . context_processor ( fn ) ) return fn
Registers a template context processor function .
30
8
24,227
def shell_context_processor ( self , fn ) : self . _defer ( lambda app : app . shell_context_processor ( fn ) ) return fn
Registers a shell context processor function .
34
8
24,228
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 .
32
30
24,229
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 .
53
12
24,230
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 .
150
14
24,231
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!
120
9
24,232
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 ) ) # the following if condition is modified: 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 .
267
14
24,233
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 .
243
7
24,234
def urls ( order_by : Optional [ str ] = None ) : url_rules : List [ Rule ] = current_app . url_map . _rules # sort the rules. by default they're sorted by priority, # ie in the order they were registered with the app 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 .
284
8
24,235
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 .
66
6
24,236
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 .
43
23
24,237
def singularize ( word , pos = NOUN , custom = None ) : if custom and word in custom : return custom [ word ] # Recurse compound words (e.g. mothers-in-law). 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 : ] ) # dogs' => dog's 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 .
344
8
24,238
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
146
9
24,239
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 .
62
3
24,240
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 .
82
5
24,241
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 .
81
4
24,242
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 .
170
25
24,243
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 .
108
9
24,244
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 .
135
8
24,245
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 .
89
10
24,246
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 .
85
8
24,247
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 .
78
16
24,248
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
77
7
24,249
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 .
45
8
24,250
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 .
137
9
24,251
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 .
62
9
24,252
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 .
62
9
24,253
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 .
79
10
24,254
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 .
112
6
24,255
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 .
146
6
24,256
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 .
118
7
24,257
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 .
118
7
24,258
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 .
164
13
24,259
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 .
387
35
24,260
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 # confirmation token depends on having user.id set, which requires # the user be committed to the database 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 .
370
7
24,261
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 .
148
9
24,262
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 .
77
18
24,263
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 .
97
12
24,264
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 : # prevents sphinx from blowing up 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 .
148
21
24,265
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 ) # update output marker for stdout/stderr, so that startup # messages appear after banner: self . _show_interpreter_prompt ( )
Overridden to customize the order that the banners are printed
147
11
24,266
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 ) # upstream has this here, even though it seems like a silly place for it 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
167
13
24,267
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 is a config key if what and what . isupper ( ) : what = current_app . config . get ( what ) if isinstance ( what , LocalProxy ) : what = what . _get_current_object ( ) # if we already have a url (or an invalid value, eg None) 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 ) # check if it's a class method name, and try that endpoint 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 , # url not found IndexError , # method_routes[0] is out-of-range TypeError , # method_routes is None ) : pass # what must be an endpoint return _url_for ( what , * * flask_url_for_kwargs )
An improved version of flask s url_for function
408
10
24,268
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
364
8
24,269
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
170
70
24,270
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 .
95
15
24,271
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 .
42
11
24,272
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 .
261
12
24,273
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
121
13
24,274
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 .
84
15
24,275
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 .
44
25
24,276
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 .
133
6
24,277
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 .
37
10
24,278
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 .
67
11
24,279
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 .
39
12
24,280
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 .
72
19
24,281
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 ) # build up a list of dependencies # IMPORTANT: keys here must match setup.py's `extra_requires` keys 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 ] # remaining ctx vars ctx [ 'app_bundle_module_name' ] = app_bundle # copy the project template into place 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 .
471
8
24,282
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 .
58
15
24,283
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 .
56
12
24,284
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 .
78
35
24,285
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 .
63
26
24,286
def _fill_cache ( self , namespace ) : modules = self . _findPluginModules ( namespace ) self . _cache = list ( modules )
Load all modules found in a namespace
32
7
24,287
def build_tree ( self ) : if self . built : return self . doc_root = self . root . element ( ) for key in self . sorted_fields ( ) : if key not in self . _fields : continue field = self . _fields [ key ] if field != self . root : if isinstance ( field , XmlModel ) : field . build_tree ( ) if ( self . drop_empty and field . drop_empty and len ( field . doc_root ) == 0 ) : continue self . doc_root . append ( field . doc_root ) elif isinstance ( field , list ) : # we just allow XmlFields and XmlModels # Also xml as str for memory management for item in field : if isinstance ( item , XmlField ) : ele = item . element ( ) if self . drop_empty and len ( ele ) == 0 : continue self . doc_root . append ( ele ) elif isinstance ( item , XmlModel ) : item . build_tree ( ) if self . drop_empty and len ( item . doc_root ) == 0 : continue self . doc_root . append ( item . doc_root ) elif isinstance ( item , ( six . text_type , six . string_types ) ) : ele = etree . fromstring ( clean_xml ( item ) ) self . doc_root . append ( ele ) item = None elif ( field . parent or self . root . name ) == self . root . name : ele = field . element ( ) if self . drop_empty and len ( ele ) == 0 and not ele . text : continue ele = field . element ( parent = self . doc_root ) else : nodes = [ n for n in self . doc_root . iterdescendants ( tag = field . parent ) ] if nodes : ele = field . element ( ) if ( self . drop_empty and len ( ele ) == 0 and not ele . text ) : continue ele = field . element ( parent = nodes [ 0 ] ) #else: # raise RuntimeError("No parent found!") self . built = True
Bulids the tree with all the fields converted to Elements
454
11
24,288
def _preserve_settings ( method : T . Callable ) -> T . Callable : @ functools . wraps ( method ) def _wrapper ( old : "ObservableProperty" , handler : T . Callable ) -> "ObservableProperty" : new = method ( old , handler ) # type: ObservableProperty new . event = old . event new . observable = old . observable return new return _wrapper
Decorator that ensures ObservableProperty - specific attributes are kept when using methods to change deleter getter or setter .
90
26
24,289
def _trigger_event ( self , holder : T . Any , alt_name : str , action : str , * event_args : T . Any ) -> None : if isinstance ( self . observable , Observable ) : observable = self . observable elif isinstance ( self . observable , str ) : observable = getattr ( holder , self . observable ) elif isinstance ( holder , Observable ) : observable = holder else : raise TypeError ( "This ObservableProperty is no member of an Observable " "object. Specify where to find the Observable object for " "triggering events with the observable keyword argument " "when initializing the ObservableProperty." ) name = alt_name if self . event is None else self . event event = "{}_{}" . format ( action , name ) observable . trigger ( event , * event_args )
Triggers an event on the associated Observable object . The Holder is the object this property is a member of alt_name is used as the event name when self . event is not set action is prepended to the event name and event_args are passed through to the registered event handlers .
182
60
24,290
def create_with ( cls , event : str = None , observable : T . Union [ str , Observable ] = None ) -> T . Callable [ ... , "ObservableProperty" ] : return functools . partial ( cls , event = event , observable = observable )
Creates a partial application of ObservableProperty with event and observable preset .
62
15
24,291
def get_all_handlers ( self ) -> T . Dict [ str , T . List [ T . Callable ] ] : events = { } for event , handlers in self . _events . items ( ) : events [ event ] = list ( handlers ) return events
Returns a dict with event names as keys and lists of registered handlers as values .
58
16
24,292
def get_handlers ( self , event : str ) -> T . List [ T . Callable ] : return list ( self . _events . get ( event , [ ] ) )
Returns a list of handlers registered for the given event .
39
11
24,293
def is_registered ( self , event : str , handler : T . Callable ) -> bool : return handler in self . _events . get ( event , [ ] )
Returns whether the given handler is registered for the given event .
36
12
24,294
def on ( # pylint: disable=invalid-name self , event : str , * handlers : T . Callable ) -> T . Callable : def _on_wrapper ( * handlers : T . Callable ) -> T . Callable : """wrapper for on decorator""" self . _events [ event ] . extend ( handlers ) return handlers [ 0 ] if handlers : return _on_wrapper ( * handlers ) return _on_wrapper
Registers one or more handlers to a specified event . This method may as well be used as a decorator for the handler .
95
26
24,295
def once ( self , event : str , * handlers : T . Callable ) -> T . Callable : def _once_wrapper ( * handlers : T . Callable ) -> T . Callable : """Wrapper for 'once' decorator""" def _wrapper ( * args : T . Any , * * kw : T . Any ) -> None : """Wrapper that unregisters itself before executing the handlers""" self . off ( event , _wrapper ) for handler in handlers : handler ( * args , * * kw ) return _wrapper if handlers : return self . on ( event , _once_wrapper ( * handlers ) ) return lambda x : self . on ( event , _once_wrapper ( x ) )
Registers one or more handlers to a specified event but removes them when the event is first triggered . This method may as well be used as a decorator for the handler .
153
35
24,296
def trigger ( self , event : str , * args : T . Any , * * kw : T . Any ) -> bool : callbacks = list ( self . _events . get ( event , [ ] ) ) if not callbacks : return False for callback in callbacks : callback ( * args , * * kw ) return True
Triggers all handlers which are subscribed to an event . Returns True when there were callbacks to execute False otherwise .
71
24
24,297
def connection ( profile_name = 'default' , api_key = None ) : if api_key is None : profile_fname = datapoint . profile . API_profile_fname ( profile_name ) if not os . path . exists ( profile_fname ) : raise ValueError ( 'Profile not found in {}. Please install your API \n' 'key with datapoint.profile.install_API_key(' '"<YOUR-KEY>")' . format ( profile_fname ) ) with open ( profile_fname ) as fh : api_key = fh . readlines ( ) return Manager ( api_key = api_key )
Connect to DataPoint with the given API key profile name .
147
12
24,298
def elements ( self ) : elements = [ ] for el in ct : if isinstance ( el [ 1 ] , datapoint . Element . Element ) : elements . append ( el [ 1 ] ) return elements
Return a list of the elements which are not None
45
10
24,299
def __retry_session ( self , retries = 10 , backoff_factor = 0.3 , status_forcelist = ( 500 , 502 , 504 ) , session = None ) : # requests.Session allows finer control, which is needed to use the # retrying code the_session = session or requests . Session ( ) # The Retry object manages the actual retrying retry = Retry ( total = retries , read = retries , connect = retries , backoff_factor = backoff_factor , status_forcelist = status_forcelist ) adapter = HTTPAdapter ( max_retries = retry ) the_session . mount ( 'http://' , adapter ) the_session . mount ( 'https://' , adapter ) return the_session
Retry the connection using requests if it fails . Use this as a wrapper to request from datapoint
164
21