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 ...
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 s...
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 . ...
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 Non...
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 ) , ca...
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_RED...
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...
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 ...
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 ( sil...
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...
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 ...
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...
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 : messag...
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...
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_...
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 alrea...
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 ) i...
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 . _ser...
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 . i...
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' , 'Param...
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...
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...
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 . befo...
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 valu...
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 ) . str...
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_m...
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_...
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'Successful...
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 , co...
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...
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 {u...
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 ...
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 use...
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 i...
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_no...
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 . ...
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 ( c...
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 ( se...
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 ) s...
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 [...
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 ]...
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...
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 ...
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 wrapp...
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...
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 ( *...
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}' retur...
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 D...
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