repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
briancappello/flask-unchained
flask_unchained/bundles/controller/__init__.py
ControllerBundle.after_init_app
def after_init_app(self, app: FlaskUnchained): """ Configure an after request hook to set the ``csrf_token`` in the cookie. """ from flask_wtf.csrf import generate_csrf # send CSRF token in the cookie @app.after_request def set_csrf_cookie(response): if response: response.set_cookie('csrf_token', generate_csrf()) return response
python
def after_init_app(self, app: FlaskUnchained): """ Configure an after request hook to set the ``csrf_token`` in the cookie. """ from flask_wtf.csrf import generate_csrf # send CSRF token in the cookie @app.after_request def set_csrf_cookie(response): if response: response.set_cookie('csrf_token', generate_csrf()) return response
[ "def", "after_init_app", "(", "self", ",", "app", ":", "FlaskUnchained", ")", ":", "from", "flask_wtf", ".", "csrf", "import", "generate_csrf", "# send CSRF token in the cookie", "@", "app", ".", "after_request", "def", "set_csrf_cookie", "(", "response", ")", ":"...
Configure an after request hook to set the ``csrf_token`` in the cookie.
[ "Configure", "an", "after", "request", "hook", "to", "set", "the", "csrf_token", "in", "the", "cookie", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/__init__.py#L57-L69
train
24,300
briancappello/flask-unchained
flask_unchained/commands/shell.py
shell
def shell(): """ Runs a shell in the app context. If ``IPython`` is installed, it will be used, otherwise the default Python shell is used. """ 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)
python
def shell(): """ Runs a shell in the app context. If ``IPython`` is installed, it will be used, otherwise the default Python shell is used. """ 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)
[ "def", "shell", "(", ")", ":", "ctx", "=", "_get_shell_ctx", "(", ")", "try", ":", "import", "IPython", "IPython", ".", "embed", "(", "header", "=", "_get_shell_banner", "(", ")", ",", "user_ns", "=", "ctx", ")", "except", "ImportError", ":", "import", ...
Runs a shell in the app context. If ``IPython`` is installed, it will be used, otherwise the default Python shell is used.
[ "Runs", "a", "shell", "in", "the", "app", "context", ".", "If", "IPython", "is", "installed", "it", "will", "be", "used", "otherwise", "the", "default", "Python", "shell", "is", "used", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/shell.py#L10-L21
train
24,301
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.login
def login(self): """ View function to log a user in. Supports html and json requests. """ 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: # FIXME-identity identity_attrs = app.config.SECURITY_USER_IDENTITY_ATTRIBUTES msg = f"Invalid {', '.join(identity_attrs)} and/or password." # we just want a single top-level form error 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'))
python
def login(self): """ View function to log a user in. Supports html and json requests. """ 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: # FIXME-identity identity_attrs = app.config.SECURITY_USER_IDENTITY_ATTRIBUTES msg = f"Invalid {', '.join(identity_attrs)} and/or password." # we just want a single top-level form error 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'))
[ "def", "login", "(", "self", ")", ":", "form", "=", "self", ".", "_get_form", "(", "'SECURITY_LOGIN_FORM'", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "try", ":", "self", ".", "security_service", ".", "login_user", "(", "form", ".", "us...
View function to log a user in. Supports html and json requests.
[ "View", "function", "to", "log", "a", "user", "in", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L39-L73
train
24,302
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.logout
def logout(self): """ View function to log a user out. Supports html and json requests. """ 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')
python
def logout(self): """ View function to log a user out. Supports html and json requests. """ 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')
[ "def", "logout", "(", "self", ")", ":", "if", "current_user", ".", "is_authenticated", ":", "self", ".", "security_service", ".", "logout_user", "(", ")", "if", "request", ".", "is_json", ":", "return", "''", ",", "HTTPStatus", ".", "NO_CONTENT", "self", "...
View function to log a user out. Supports html and json requests.
[ "View", "function", "to", "log", "a", "user", "out", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L76-L88
train
24,303
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.register
def register(self): """ View function to register user. Supports html and json requests. """ 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'))
python
def register(self): """ View function to register user. Supports html and json requests. """ 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'))
[ "def", "register", "(", "self", ")", ":", "form", "=", "self", ".", "_get_form", "(", "'SECURITY_REGISTER_FORM'", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "user", "=", "self", ".", "security_service", ".", "user_manager", ".", "create", ...
View function to register user. Supports html and json requests.
[ "View", "function", "to", "register", "user", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L93-L105
train
24,304
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.send_confirmation_email
def send_confirmation_email(self): """ View function which sends confirmation token and instructions to a user. """ 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'))
python
def send_confirmation_email(self): """ View function which sends confirmation token and instructions to a user. """ 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'))
[ "def", "send_confirmation_email", "(", "self", ")", ":", "form", "=", "self", ".", "_get_form", "(", "'SECURITY_SEND_CONFIRMATION_FORM'", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "self", ".", "security_service", ".", "send_email_confirmation_inst...
View function which sends confirmation token and instructions to a user.
[ "View", "function", "which", "sends", "confirmation", "token", "and", "instructions", "to", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L109-L126
train
24,305
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.confirm_email
def confirm_email(self, token): """ View function to confirm a user's token from the confirmation email send to them. Supports html and json requests. """ 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')
python
def confirm_email(self, token): """ View function to confirm a user's token from the confirmation email send to them. Supports html and json requests. """ 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')
[ "def", "confirm_email", "(", "self", ",", "token", ")", ":", "expired", ",", "invalid", ",", "user", "=", "self", ".", "security_utils_service", ".", "confirm_email_token_status", "(", "token", ")", "if", "not", "user", "or", "invalid", ":", "invalid", "=", ...
View function to confirm a user's token from the confirmation email send to them. Supports html and json requests.
[ "View", "function", "to", "confirm", "a", "user", "s", "token", "from", "the", "confirmation", "email", "send", "to", "them", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L130-L168
train
24,306
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.forgot_password
def forgot_password(self): """ View function to request a password recovery email with a reset token. Supports html and json requests. """ 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'))
python
def forgot_password(self): """ View function to request a password recovery email with a reset token. Supports html and json requests. """ 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'))
[ "def", "forgot_password", "(", "self", ")", ":", "form", "=", "self", ".", "_get_form", "(", "'SECURITY_FORGOT_PASSWORD_FORM'", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "self", ".", "security_service", ".", "send_reset_password_instructions", "...
View function to request a password recovery email with a reset token. Supports html and json requests.
[ "View", "function", "to", "request", "a", "password", "recovery", "email", "with", "a", "reset", "token", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L174-L193
train
24,307
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.reset_password
def reset_password(self, token): """ 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. """ 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'))
python
def reset_password(self, token): """ 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. """ 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'))
[ "def", "reset_password", "(", "self", ",", "token", ")", ":", "expired", ",", "invalid", ",", "user", "=", "self", ".", "security_utils_service", ".", "reset_password_token_status", "(", "token", ")", "if", "invalid", ":", "self", ".", "flash", "(", "_", "...
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.
[ "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",...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L198-L242
train
24,308
briancappello/flask-unchained
flask_unchained/bundles/security/views/security_controller.py
SecurityController.change_password
def change_password(self): """ View function for a user to change their password. Supports html and json requests. """ 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'))
python
def change_password(self): """ View function for a user to change their password. Supports html and json requests. """ 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'))
[ "def", "change_password", "(", "self", ")", ":", "form", "=", "self", ".", "_get_form", "(", "'SECURITY_CHANGE_PASSWORD_FORM'", ")", "if", "form", ".", "validate_on_submit", "(", ")", ":", "self", ".", "security_service", ".", "change_password", "(", "current_us...
View function for a user to change their password. Supports html and json requests.
[ "View", "function", "for", "a", "user", "to", "change", "their", "password", ".", "Supports", "html", "and", "json", "requests", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L247-L270
train
24,309
briancappello/flask-unchained
flask_unchained/bundles/security/extensions/security.py
Security._get_pwd_context
def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext: """ Get the password hashing context. """ 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)
python
def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext: """ Get the password hashing context. """ 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)
[ "def", "_get_pwd_context", "(", "self", ",", "app", ":", "FlaskUnchained", ")", "->", "CryptContext", ":", "pw_hash", "=", "app", ".", "config", ".", "SECURITY_PASSWORD_HASH", "schemes", "=", "app", ".", "config", ".", "SECURITY_PASSWORD_SCHEMES", "if", "pw_hash...
Get the password hashing context.
[ "Get", "the", "password", "hashing", "context", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L215-L226
train
24,310
briancappello/flask-unchained
flask_unchained/bundles/security/extensions/security.py
Security._get_serializer
def _get_serializer(self, app: FlaskUnchained, name: str) -> URLSafeTimedSerializer: """ Get a URLSafeTimedSerializer for the given serialization context name. :param app: the :class:`FlaskUnchained` instance :param name: Serialization context. One of ``confirm``, ``login``, ``remember``, or ``reset`` :return: URLSafeTimedSerializer """ salt = app.config.get('SECURITY_%s_SALT' % name.upper()) return URLSafeTimedSerializer(secret_key=app.config.SECRET_KEY, salt=salt)
python
def _get_serializer(self, app: FlaskUnchained, name: str) -> URLSafeTimedSerializer: """ Get a URLSafeTimedSerializer for the given serialization context name. :param app: the :class:`FlaskUnchained` instance :param name: Serialization context. One of ``confirm``, ``login``, ``remember``, or ``reset`` :return: URLSafeTimedSerializer """ salt = app.config.get('SECURITY_%s_SALT' % name.upper()) return URLSafeTimedSerializer(secret_key=app.config.SECRET_KEY, salt=salt)
[ "def", "_get_serializer", "(", "self", ",", "app", ":", "FlaskUnchained", ",", "name", ":", "str", ")", "->", "URLSafeTimedSerializer", ":", "salt", "=", "app", ".", "config", ".", "get", "(", "'SECURITY_%s_SALT'", "%", "name", ".", "upper", "(", ")", ")...
Get a URLSafeTimedSerializer for the given serialization context name. :param app: the :class:`FlaskUnchained` instance :param name: Serialization context. One of ``confirm``, ``login``, ``remember``, or ``reset`` :return: URLSafeTimedSerializer
[ "Get", "a", "URLSafeTimedSerializer", "for", "the", "given", "serialization", "context", "name", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L228-L238
train
24,311
briancappello/flask-unchained
flask_unchained/bundles/security/extensions/security.py
Security._request_loader
def _request_loader(self, request: Request) -> Union[User, AnonymousUser]: """ Attempt to load the user from the request token. """ 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()
python
def _request_loader(self, request: Request) -> Union[User, AnonymousUser]: """ Attempt to load the user from the request token. """ 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()
[ "def", "_request_loader", "(", "self", ",", "request", ":", "Request", ")", "->", "Union", "[", "User", ",", "AnonymousUser", "]", ":", "header_key", "=", "self", ".", "token_authentication_header", "args_key", "=", "self", ".", "token_authentication_key", "toke...
Attempt to load the user from the request token.
[ "Attempt", "to", "load", "the", "user", "from", "the", "request", "token", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L260-L279
train
24,312
briancappello/flask-unchained
flask_unchained/commands/unchained.py
bundles
def bundles(ctx): """ List discovered bundles. """ bundles = _get_bundles(ctx.obj.data['env']) print_table(('Name', 'Location'), [(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}') for bundle in bundles])
python
def bundles(ctx): """ List discovered bundles. """ bundles = _get_bundles(ctx.obj.data['env']) print_table(('Name', 'Location'), [(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}') for bundle in bundles])
[ "def", "bundles", "(", "ctx", ")", ":", "bundles", "=", "_get_bundles", "(", "ctx", ".", "obj", ".", "data", "[", "'env'", "]", ")", "print_table", "(", "(", "'Name'", ",", "'Location'", ")", ",", "[", "(", "bundle", ".", "name", ",", "f'{bundle.__mo...
List discovered bundles.
[ "List", "discovered", "bundles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/unchained.py#L16-L23
train
24,313
briancappello/flask-unchained
flask_unchained/click.py
argument
def argument(*param_decls, cls=None, **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. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The later is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. :param help: the help string. :param hidden: hide this option from help outputs. Default is True, unless help is given. """ return click.argument(*param_decls, cls=cls or Argument, **attrs)
python
def argument(*param_decls, cls=None, **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. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The later is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. :param help: the help string. :param hidden: hide this option from help outputs. Default is True, unless help is given. """ return click.argument(*param_decls, cls=cls or Argument, **attrs)
[ "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. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param type: the type that should be used. Either a :class:`ParamType` or a Python type. The later is converted into the former automatically if supported. :param required: controls if this is optional or not. :param default: the default value if omitted. This can also be a callable, in which case it's invoked when the default is needed without any arguments. :param callback: a callback that should be executed after the parameter was matched. This is called as ``fn(ctx, param, value)`` and needs to return the value. Before Click 2.0, the signature was ``(ctx, value)``. :param nargs: the number of arguments to match. If not ``1`` the return value is a tuple instead of single value. The default for nargs is ``1`` (except if the type is a tuple, then it's the arity of the tuple). :param metavar: how the value is represented in the help page. :param expose_value: if this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it's skipped. :param is_eager: eager values are processed before non eager ones. This should not be set for arguments or it will inverse the order of processing. :param envvar: a string or list of strings that are environment variables that should be checked. :param help: the help string. :param hidden: hide this option from help outputs. Default is True, unless help is given.
[ "Arguments", "are", "positional", "parameters", "to", "a", "command", ".", "They", "generally", "provide", "fewer", "features", "than", "options", "but", "can", "have", "infinite", "nargs", "and", "are", "required", "by", "default", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/click.py#L390-L427
train
24,314
briancappello/flask-unchained
flask_unchained/click.py
option
def option(*param_decls, cls=None, **attrs): """ Options are usually optional values on the command line and have some extra features that arguments don't have. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param show_default: controls if the default value should be shown on the help page. Normally, defaults are not shown. :param prompt: if set to `True` or a non empty string then the user will be prompted for input if not set. If set to `True` the prompt will be the option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. """ return click.option(*param_decls, cls=cls or Option, **attrs)
python
def option(*param_decls, cls=None, **attrs): """ Options are usually optional values on the command line and have some extra features that arguments don't have. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param show_default: controls if the default value should be shown on the help page. Normally, defaults are not shown. :param prompt: if set to `True` or a non empty string then the user will be prompted for input if not set. If set to `True` the prompt will be the option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string. """ return click.option(*param_decls, cls=cls or Option, **attrs)
[ "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. :param param_decls: the parameter declarations for this option or argument. This is a list of flags or argument names. :param show_default: controls if the default value should be shown on the help page. Normally, defaults are not shown. :param prompt: if set to `True` or a non empty string then the user will be prompted for input if not set. If set to `True` the prompt will be the option name capitalized. :param confirmation_prompt: if set then the value will need to be confirmed if it was prompted for. :param hide_input: if this is `True` then the input on the prompt will be hidden from the user. This is useful for password input. :param is_flag: forces this option to act as a flag. The default is auto detection. :param flag_value: which value should be used for this flag if it's enabled. This is set to a boolean automatically if the option string contains a slash to mark two options. :param multiple: if this is set to `True` then the argument is accepted multiple times and recorded. This is similar to ``nargs`` in how it works but supports arbitrary number of arguments. :param count: this flag makes an option increment an integer. :param allow_from_autoenv: if this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context. :param help: the help string.
[ "Options", "are", "usually", "optional", "values", "on", "the", "command", "line", "and", "have", "some", "extra", "features", "that", "arguments", "don", "t", "have", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/click.py#L430-L464
train
24,315
briancappello/flask-unchained
flask_unchained/bundles/api/apispec.py
APISpec._openapi_json
def _openapi_json(self): """Serve JSON spec file""" # 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')
python
def _openapi_json(self): """Serve JSON spec file""" # 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')
[ "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", "curr...
Serve JSON spec file
[ "Serve", "JSON", "spec", "file" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L59-L66
train
24,316
briancappello/flask-unchained
flask_unchained/bundles/api/apispec.py
APISpec._openapi_redoc
def _openapi_redoc(self): """ Expose OpenAPI spec with ReDoc The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL`` """ 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)
python
def _openapi_redoc(self): """ Expose OpenAPI spec with ReDoc The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL`` """ 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)
[ "def", "_openapi_redoc", "(", "self", ")", ":", "return", "render_template", "(", "'openapi/redoc.html'", ",", "title", "=", "self", ".", "app", ".", "config", ".", "API_TITLE", "or", "self", ".", "app", ".", "name", ",", "redoc_url", "=", "self", ".", "...
Expose OpenAPI spec with ReDoc The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL``
[ "Expose", "OpenAPI", "spec", "with", "ReDoc" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L68-L76
train
24,317
briancappello/flask-unchained
flask_unchained/bundles/api/apispec.py
APISpec.register_converter
def register_converter(self, converter, conv_type, conv_format=None): """ Register custom path parameter converter :param BaseConverter converter: Converter. Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) """ self.flask_plugin.register_converter(converter, conv_type, conv_format)
python
def register_converter(self, converter, conv_type, conv_format=None): """ Register custom path parameter converter :param BaseConverter converter: Converter. Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) """ self.flask_plugin.register_converter(converter, conv_type, conv_format)
[ "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 :param BaseConverter converter: Converter. Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional)
[ "Register", "custom", "path", "parameter", "converter" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L78-L87
train
24,318
briancappello/flask-unchained
flask_unchained/bundles/api/decorators.py
list_loader
def list_loader(*decorator_args, model): """ Decorator to automatically query the database for all records of a model. :param model: The model class to query """ 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
python
def list_loader(*decorator_args, model): """ Decorator to automatically query the database for all records of a model. :param model: The model class to query """ 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
[ "def", "list_loader", "(", "*", "decorator_args", ",", "model", ")", ":", "def", "wrapped", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "fn", "(", "model", ...
Decorator to automatically query the database for all records of a model. :param model: The model class to query
[ "Decorator", "to", "automatically", "query", "the", "database", "for", "all", "records", "of", "a", "model", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/decorators.py#L7-L21
train
24,319
briancappello/flask-unchained
flask_unchained/bundles/api/decorators.py
post_loader
def post_loader(*decorator_args, serializer): """ Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request """ 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
python
def post_loader(*decorator_args, serializer): """ Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request """ 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
[ "def", "post_loader", "(", "*", "decorator_args", ",", "serializer", ")", ":", "def", "wrapped", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "fn", "(", "*", ...
Decorator to automatically instantiate a model from json request data :param serializer: The ModelSerializer to use to load data from the request
[ "Decorator", "to", "automatically", "instantiate", "a", "model", "from", "json", "request", "data" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/decorators.py#L68-L82
train
24,320
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/commands.py
reset_command
def reset_command(force): """Drop database tables and run migrations.""" 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.')
python
def reset_command(force): """Drop database tables and run migrations.""" 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.')
[ "def", "reset_command", "(", "force", ")", ":", "if", "not", "force", ":", "exit", "(", "'Cancelled.'", ")", "click", ".", "echo", "(", "'Dropping DB tables.'", ")", "drop_all", "(", ")", "click", ".", "echo", "(", "'Running DB migrations.'", ")", "alembic",...
Drop database tables and run migrations.
[ "Drop", "database", "tables", "and", "run", "migrations", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/commands.py#L43-L54
train
24,321
tanbro/pyyaml-include
src/yamlinclude/constructor.py
YamlIncludeConstructor.load
def load(self, loader, pathname, recursive=False, encoding=None): """Once add the constructor to PyYAML loader class, Loader will use this function to include other YAML fils on parsing ``"!include"`` tag :param loader: Instance of PyYAML's loader class :param str pathname: pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards :param bool recursive: If recursive is true, the pattern ``"**"`` will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match. Note: Using the ``"**"`` pattern in large directory trees may consume an inordinate amount of time. :param str encoding: YAML file encoding :default: ``None``: Attribute :attr:`encoding` or constant :attr:`DEFAULT_ENCODING` will be used to open it :return: included YAML file, in Python data type .. warning:: It's called by :mod:`yaml`. Do NOT call it yourself. """ 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))
python
def load(self, loader, pathname, recursive=False, encoding=None): """Once add the constructor to PyYAML loader class, Loader will use this function to include other YAML fils on parsing ``"!include"`` tag :param loader: Instance of PyYAML's loader class :param str pathname: pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards :param bool recursive: If recursive is true, the pattern ``"**"`` will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match. Note: Using the ``"**"`` pattern in large directory trees may consume an inordinate amount of time. :param str encoding: YAML file encoding :default: ``None``: Attribute :attr:`encoding` or constant :attr:`DEFAULT_ENCODING` will be used to open it :return: included YAML file, in Python data type .. warning:: It's called by :mod:`yaml`. Do NOT call it yourself. """ 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))
[ "def", "load", "(", "self", ",", "loader", ",", "pathname", ",", "recursive", "=", "False", ",", "encoding", "=", "None", ")", ":", "if", "not", "encoding", ":", "encoding", "=", "self", ".", "_encoding", "or", "self", ".", "DEFAULT_ENCODING", "if", "s...
Once add the constructor to PyYAML loader class, Loader will use this function to include other YAML fils on parsing ``"!include"`` tag :param loader: Instance of PyYAML's loader class :param str pathname: pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards :param bool recursive: If recursive is true, the pattern ``"**"`` will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match. Note: Using the ``"**"`` pattern in large directory trees may consume an inordinate amount of time. :param str encoding: YAML file encoding :default: ``None``: Attribute :attr:`encoding` or constant :attr:`DEFAULT_ENCODING` will be used to open it :return: included YAML file, in Python data type .. warning:: It's called by :mod:`yaml`. Do NOT call it yourself.
[ "Once", "add", "the", "constructor", "to", "PyYAML", "loader", "class", "Loader", "will", "use", "this", "function", "to", "include", "other", "YAML", "fils", "on", "parsing", "!include", "tag" ]
f0e6490399aaf7c02321000fe5cdccfa8f63cf66
https://github.com/tanbro/pyyaml-include/blob/f0e6490399aaf7c02321000fe5cdccfa8f63cf66/src/yamlinclude/constructor.py#L96-L133
train
24,322
tanbro/pyyaml-include
src/yamlinclude/constructor.py
YamlIncludeConstructor.add_to_loader_class
def add_to_loader_class(cls, loader_class=None, tag=None, **kwargs): # type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor """ Create an instance of the constructor, and add it to the YAML `Loader` class :param loader_class: The `Loader` class add constructor to. .. attention:: This parameter **SHOULD** be a **class type**, **NOT** object. It's one of following: - :class:`yaml.BaseLoader` - :class:`yaml.UnSafeLoader` - :class:`yaml.SafeLoader` - :class:`yaml.Loader` - :class:`yaml.FullLoader` - :class:`yaml.CBaseLoader` - :class:`yaml.CUnSafeLoader` - :class:`yaml.CSafeLoader` - :class:`yaml.CLoader` - :class:`yaml.CFullLoader` :default: ``None``: - When :mod:`pyyaml` 3.*: Add to PyYAML's default `Loader` - When :mod:`pyyaml` 5.*: Add to `FullLoader` :type loader_class: type :param str tag: Tag's name of the include constructor. :default: ``""``: Use :attr:`DEFAULT_TAG_NAME` as tag name. :param kwargs: Arguments passed to construct function :return: New created object :rtype: 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
python
def add_to_loader_class(cls, loader_class=None, tag=None, **kwargs): # type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor """ Create an instance of the constructor, and add it to the YAML `Loader` class :param loader_class: The `Loader` class add constructor to. .. attention:: This parameter **SHOULD** be a **class type**, **NOT** object. It's one of following: - :class:`yaml.BaseLoader` - :class:`yaml.UnSafeLoader` - :class:`yaml.SafeLoader` - :class:`yaml.Loader` - :class:`yaml.FullLoader` - :class:`yaml.CBaseLoader` - :class:`yaml.CUnSafeLoader` - :class:`yaml.CSafeLoader` - :class:`yaml.CLoader` - :class:`yaml.CFullLoader` :default: ``None``: - When :mod:`pyyaml` 3.*: Add to PyYAML's default `Loader` - When :mod:`pyyaml` 5.*: Add to `FullLoader` :type loader_class: type :param str tag: Tag's name of the include constructor. :default: ``""``: Use :attr:`DEFAULT_TAG_NAME` as tag name. :param kwargs: Arguments passed to construct function :return: New created object :rtype: 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
[ "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", ...
Create an instance of the constructor, and add it to the YAML `Loader` class :param loader_class: The `Loader` class add constructor to. .. attention:: This parameter **SHOULD** be a **class type**, **NOT** object. It's one of following: - :class:`yaml.BaseLoader` - :class:`yaml.UnSafeLoader` - :class:`yaml.SafeLoader` - :class:`yaml.Loader` - :class:`yaml.FullLoader` - :class:`yaml.CBaseLoader` - :class:`yaml.CUnSafeLoader` - :class:`yaml.CSafeLoader` - :class:`yaml.CLoader` - :class:`yaml.CFullLoader` :default: ``None``: - When :mod:`pyyaml` 3.*: Add to PyYAML's default `Loader` - When :mod:`pyyaml` 5.*: Add to `FullLoader` :type loader_class: type :param str tag: Tag's name of the include constructor. :default: ``""``: Use :attr:`DEFAULT_TAG_NAME` as tag name. :param kwargs: Arguments passed to construct function :return: New created object :rtype: YamlIncludeConstructor
[ "Create", "an", "instance", "of", "the", "constructor", "and", "add", "it", "to", "the", "YAML", "Loader", "class" ]
f0e6490399aaf7c02321000fe5cdccfa8f63cf66
https://github.com/tanbro/pyyaml-include/blob/f0e6490399aaf7c02321000fe5cdccfa8f63cf66/src/yamlinclude/constructor.py#L136-L189
train
24,323
briancappello/flask-unchained
flask_unchained/commands/utils.py
print_table
def print_table(column_names: IterableOfStrings, rows: IterableOfTuples, column_alignments: Optional[IterableOfStrings] = None, primary_column_idx: int = 0, ) -> None: """ 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. :param column_names: The heading labels :param rows: A list of lists :param column_alignments: An optional list of strings, using either '<' or '>' to specify left or right alignment respectively :param primary_column_idx: Used when displaying information in list form, to determine which label should be the top-most one. Defaults to the first label in ``column_names``. """ 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()
python
def print_table(column_names: IterableOfStrings, rows: IterableOfTuples, column_alignments: Optional[IterableOfStrings] = None, primary_column_idx: int = 0, ) -> None: """ 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. :param column_names: The heading labels :param rows: A list of lists :param column_alignments: An optional list of strings, using either '<' or '>' to specify left or right alignment respectively :param primary_column_idx: Used when displaying information in list form, to determine which label should be the top-most one. Defaults to the first label in ``column_names``. """ 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()
[ "def", "print_table", "(", "column_names", ":", "IterableOfStrings", ",", "rows", ":", "IterableOfTuples", ",", "column_alignments", ":", "Optional", "[", "IterableOfStrings", "]", "=", "None", ",", "primary_column_idx", ":", "int", "=", "0", ",", ")", "->", "...
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. :param column_names: The heading labels :param rows: A list of lists :param column_alignments: An optional list of strings, using either '<' or '>' to specify left or right alignment respectively :param primary_column_idx: Used when displaying information in list form, to determine which label should be the top-most one. Defaults to the first label in ``column_names``.
[ "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", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/utils.py#L10-L80
train
24,324
briancappello/flask-unchained
flask_mail.py
Connection.send
def send(self, message, envelope_from=None): """Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command. """ 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
python
def send(self, message, envelope_from=None): """Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command. """ 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
[ "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...
Verifies and sends message. :param message: Message instance. :param envelope_from: Email address to be used in MAIL FROM command.
[ "Verifies", "and", "sends", "message", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L228-L266
train
24,325
briancappello/flask-unchained
flask_mail.py
_MailMixin.connect
def connect(self): """ Opens a connection to the mail host. """ 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")
python
def connect(self): """ Opens a connection to the mail host. """ 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")
[ "def", "connect", "(", "self", ")", ":", "app", "=", "getattr", "(", "self", ",", "\"app\"", ",", "None", ")", "or", "current_app", "try", ":", "return", "Connection", "(", "app", ".", "extensions", "[", "'mail'", "]", ")", "except", "KeyError", ":", ...
Opens a connection to the mail host.
[ "Opens", "a", "connection", "to", "the", "mail", "host", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L633-L642
train
24,326
briancappello/flask-unchained
flask_mail.py
Mail.init_app
def init_app(self, app): """Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance """ 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
python
def init_app(self, app): """Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance """ 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
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "state", "=", "self", ".", "init_mail", "(", "app", ".", "config", ",", "app", ".", "debug", ",", "app", ".", "testing", ")", "# register extension with app", "app", ".", "extensions", "=", "getattr",...
Initializes your mail settings from the application settings. You can use this if you want to set up your Mail instance at configuration time. :param app: Flask application instance
[ "Initializes", "your", "mail", "settings", "from", "the", "application", "settings", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L691-L704
train
24,327
briancappello/flask-unchained
flask_unchained/bundle.py
_DeferredBundleFunctions.url_defaults
def url_defaults(self, 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. """ self._defer(lambda bp: bp.url_defaults(fn)) return fn
python
def url_defaults(self, 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. """ self._defer(lambda bp: bp.url_defaults(fn)) return fn
[ "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.
[ "Callback", "function", "for", "URL", "defaults", "for", "this", "bundle", ".", "It", "s", "called", "with", "the", "endpoint", "and", "values", "and", "should", "update", "the", "values", "passed", "in", "place", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L113-L120
train
24,328
briancappello/flask-unchained
flask_unchained/bundle.py
_DeferredBundleFunctions.url_value_preprocessor
def url_value_preprocessor(self, 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. """ self._defer(lambda bp: bp.url_value_preprocessor(fn)) return fn
python
def url_value_preprocessor(self, 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. """ self._defer(lambda bp: bp.url_value_preprocessor(fn)) return fn
[ "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.
[ "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", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L122-L129
train
24,329
briancappello/flask-unchained
flask_unchained/bundle.py
_DeferredBundleFunctions.errorhandler
def errorhandler(self, code_or_exception): """ 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. Otherwise works as the :meth:`flask.Blueprint.errorhandler` decorator. """ def decorator(fn): self._defer(lambda bp: bp.register_error_handler(code_or_exception, fn)) return fn return decorator
python
def errorhandler(self, code_or_exception): """ 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. Otherwise works as the :meth:`flask.Blueprint.errorhandler` decorator. """ def decorator(fn): self._defer(lambda bp: bp.register_error_handler(code_or_exception, fn)) return fn return decorator
[ "def", "errorhandler", "(", "self", ",", "code_or_exception", ")", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "bp", ":", "bp", ".", "register_error_handler", "(", "code_or_exception", ",", "fn", ")", ")", "return", ...
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. Otherwise works as the :meth:`flask.Blueprint.errorhandler` 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", "usua...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L131-L145
train
24,330
briancappello/flask-unchained
flask_unchained/bundles/controller/routes.py
controller
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: """ This function is used to register a controller class's routes. Example usage:: routes = lambda: [ controller(SiteController), ] Or with the optional prefix argument:: routes = lambda: [ controller('/products', ProductController), ] Specify ``rules`` to only include those routes from the controller:: routes = lambda: [ controller(SecurityController, rules=[ rule('/login', SecurityController.login), rule('/logout', SecurityController.logout), rule('/sign-up', SecurityController.register), ]), ] :param url_prefix_or_controller_cls: The controller class, or a url prefix for all of the rules from the controller class passed as the second argument :param controller_cls: If a url prefix was given as the first argument, then the controller class must be passed as the second argument :param rules: An optional list of rules to limit/customize the routes included from the controller """ 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)
python
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: """ This function is used to register a controller class's routes. Example usage:: routes = lambda: [ controller(SiteController), ] Or with the optional prefix argument:: routes = lambda: [ controller('/products', ProductController), ] Specify ``rules`` to only include those routes from the controller:: routes = lambda: [ controller(SecurityController, rules=[ rule('/login', SecurityController.login), rule('/logout', SecurityController.logout), rule('/sign-up', SecurityController.register), ]), ] :param url_prefix_or_controller_cls: The controller class, or a url prefix for all of the rules from the controller class passed as the second argument :param controller_cls: If a url prefix was given as the first argument, then the controller class must be passed as the second argument :param rules: An optional list of rules to limit/customize the routes included from the controller """ 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)
[ "def", "controller", "(", "url_prefix_or_controller_cls", ":", "Union", "[", "str", ",", "Type", "[", "Controller", "]", "]", ",", "controller_cls", ":", "Optional", "[", "Type", "[", "Controller", "]", "]", "=", "None", ",", "*", ",", "rules", ":", "Opt...
This function is used to register a controller class's routes. Example usage:: routes = lambda: [ controller(SiteController), ] Or with the optional prefix argument:: routes = lambda: [ controller('/products', ProductController), ] Specify ``rules`` to only include those routes from the controller:: routes = lambda: [ controller(SecurityController, rules=[ rule('/login', SecurityController.login), rule('/logout', SecurityController.logout), rule('/sign-up', SecurityController.register), ]), ] :param url_prefix_or_controller_cls: The controller class, or a url prefix for all of the rules from the controller class passed as the second argument :param controller_cls: If a url prefix was given as the first argument, then the controller class must be passed as the second argument :param rules: An optional list of rules to limit/customize the routes included from the controller
[ "This", "function", "is", "used", "to", "register", "a", "controller", "class", "s", "routes", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/routes.py#L20-L75
train
24,331
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.service
def service(self, name: str = None): """ Decorator to mark something as a service. """ 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
python
def service(self, name: str = None): """ Decorator to mark something as a service. """ 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
[ "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.'", ")",...
Decorator to mark something as a service.
[ "Decorator", "to", "mark", "something", "as", "a", "service", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L127-L140
train
24,332
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.register_service
def register_service(self, name: str, service: Any): """ Method to register a service. """ 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
python
def register_service(self, name: str, service: Any): """ Method to register a service. """ 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
[ "def", "register_service", "(", "self", ",", "name", ":", "str", ",", "service", ":", "Any", ")", ":", "if", "not", "isinstance", "(", "service", ",", "type", ")", ":", "if", "hasattr", "(", "service", ",", "'__class__'", ")", ":", "_ensure_service_name"...
Method to register a service.
[ "Method", "to", "register", "a", "service", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L142-L158
train
24,333
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.before_request
def before_request(self, fn): """ Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ self._defer(lambda app: app.before_request(fn)) return fn
python
def before_request(self, fn): """ Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped. """ self._defer(lambda app: app.before_request(fn)) return fn
[ "def", "before_request", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "before_request", "(", "fn", ")", ")", "return", "fn" ]
Registers a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session. The function will be called without any arguments. If it returns a non-None value, the value is handled as if it was the return value from the view, and further request handling is stopped.
[ "Registers", "a", "function", "to", "run", "before", "each", "request", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L346-L358
train
24,334
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.before_first_request
def before_first_request(self, fn): """ Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. """ self._defer(lambda app: app.before_first_request(fn)) return fn
python
def before_first_request(self, fn): """ Registers a function to be run before the first request to this instance of the application. The function will be called without any arguments and its return value is ignored. """ self._defer(lambda app: app.before_first_request(fn)) return fn
[ "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. The function will be called without any arguments and its return value is ignored.
[ "Registers", "a", "function", "to", "be", "run", "before", "the", "first", "request", "to", "this", "instance", "of", "the", "application", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L360-L369
train
24,335
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.after_request
def after_request(self, fn): """ Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred. """ self._defer(lambda app: app.after_request(fn)) return fn
python
def after_request(self, fn): """ Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred. """ self._defer(lambda app: app.after_request(fn)) return fn
[ "def", "after_request", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "after_request", "(", "fn", ")", ")", "return", "fn" ]
Register a function to be run after each request. Your function must take one parameter, an instance of :attr:`response_class` and return a new response object or the same (see :meth:`process_response`). As of Flask 0.7 this function might not be executed at the end of the request in case an unhandled exception occurred.
[ "Register", "a", "function", "to", "be", "run", "after", "each", "request", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L371-L383
train
24,336
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.teardown_request
def teardown_request(self, 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. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. """ self._defer(lambda app: app.teardown_request(fn)) return fn
python
def teardown_request(self, 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. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. """ self._defer(lambda app: app.teardown_request(fn)) return fn
[ "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. Example:: ctx = app.test_request_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the request context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Generally teardown functions must take every necessary step to avoid that they will fail. If they do execute code that might fail they will have to surround the execution of these code by try/except statements and log occurring errors. When a teardown function was called because of an exception it will be passed an error object. The return values of teardown functions are ignored. .. admonition:: Debug Note In debug mode Flask will not tear down a request on an exception immediately. Instead it will keep it alive so that the interactive debugger can still access it. This behavior can be controlled by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
[ "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", "...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L385-L422
train
24,337
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.teardown_appcontext
def teardown_appcontext(self, fn): """ Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. The return values of teardown functions are ignored. """ self._defer(lambda app: app.teardown_appcontext(fn)) return fn
python
def teardown_appcontext(self, fn): """ Registers a function to be called when the application context ends. These functions are typically also called when the request context is popped. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. The return values of teardown functions are ignored. """ self._defer(lambda app: app.teardown_appcontext(fn)) return fn
[ "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. Example:: ctx = app.app_context() ctx.push() ... ctx.pop() When ``ctx.pop()`` is executed in the above example, the teardown functions are called just before the app context moves from the stack of active contexts. This becomes relevant if you are using such constructs in tests. Since a request context typically also manages an application context it would also be called when you pop a request context. When a teardown function was called because of an unhandled exception it will be passed an error object. If an :meth:`errorhandler` is registered, it will handle the exception and the teardown will not receive it. The return values of teardown functions are ignored.
[ "Registers", "a", "function", "to", "be", "called", "when", "the", "application", "context", "ends", ".", "These", "functions", "are", "typically", "also", "called", "when", "the", "request", "context", "is", "popped", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L424-L453
train
24,338
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.context_processor
def context_processor(self, fn): """ Registers a template context processor function. """ self._defer(lambda app: app.context_processor(fn)) return fn
python
def context_processor(self, fn): """ Registers a template context processor function. """ self._defer(lambda app: app.context_processor(fn)) return fn
[ "def", "context_processor", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "context_processor", "(", "fn", ")", ")", "return", "fn" ]
Registers a template context processor function.
[ "Registers", "a", "template", "context", "processor", "function", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L455-L460
train
24,339
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.shell_context_processor
def shell_context_processor(self, fn): """ Registers a shell context processor function. """ self._defer(lambda app: app.shell_context_processor(fn)) return fn
python
def shell_context_processor(self, fn): """ Registers a shell context processor function. """ self._defer(lambda app: app.shell_context_processor(fn)) return fn
[ "def", "shell_context_processor", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "shell_context_processor", "(", "fn", ")", ")", "return", "fn" ]
Registers a shell context processor function.
[ "Registers", "a", "shell", "context", "processor", "function", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L462-L467
train
24,340
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.url_defaults
def url_defaults(self, 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. """ self._defer(lambda app: app.url_defaults(fn)) return fn
python
def url_defaults(self, 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. """ self._defer(lambda app: app.url_defaults(fn)) return fn
[ "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.
[ "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", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L486-L493
train
24,341
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.errorhandler
def errorhandler(self, code_or_exception): """ Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 :param code_or_exception: the code as integer for the handler, or an arbitrary exception """ def decorator(fn): self._defer(lambda app: app.register_error_handler(code_or_exception, fn)) return fn return decorator
python
def errorhandler(self, code_or_exception): """ Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 :param code_or_exception: the code as integer for the handler, or an arbitrary exception """ def decorator(fn): self._defer(lambda app: app.register_error_handler(code_or_exception, fn)) return fn return decorator
[ "def", "errorhandler", "(", "self", ",", "code_or_exception", ")", ":", "def", "decorator", "(", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "app", ":", "app", ".", "register_error_handler", "(", "code_or_exception", ",", "fn", ")", ")", "return"...
Register a function to handle errors by code or exception class. A decorator that is used to register a function given an error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register handlers for arbitrary exceptions:: @app.errorhandler(DatabaseError) def special_exception_handler(error): return 'Database connection failed', 500 :param code_or_exception: the code as integer for the handler, or an arbitrary exception
[ "Register", "a", "function", "to", "handle", "errors", "by", "code", "or", "exception", "class", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L495-L518
train
24,342
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained.template_filter
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: """ Decorator to mark a function as a Jinja template filter. :param name: The name of the filter, if different from the function name. :param pass_context: Whether or not to pass the template context into the filter. If ``True``, the first argument must be the context. :param inject: Whether or not this filter needs any dependencies injected. :param safe: Whether or not to mark the output of this filter as html-safe. """ 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
python
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: """ Decorator to mark a function as a Jinja template filter. :param name: The name of the filter, if different from the function name. :param pass_context: Whether or not to pass the template context into the filter. If ``True``, the first argument must be the context. :param inject: Whether or not this filter needs any dependencies injected. :param safe: Whether or not to mark the output of this filter as html-safe. """ 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
[ "def", "template_filter", "(", "self", ",", "arg", ":", "Optional", "[", "Callable", "]", "=", "None", ",", "*", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ",", "pass_context", ":", "bool", "=", "False", ",", "inject", ":", "Optional...
Decorator to mark a function as a Jinja template filter. :param name: The name of the filter, if different from the function name. :param pass_context: Whether or not to pass the template context into the filter. If ``True``, the first argument must be the context. :param inject: Whether or not this filter needs any dependencies injected. :param safe: Whether or not to mark the output of this filter as html-safe.
[ "Decorator", "to", "mark", "a", "function", "as", "a", "Jinja", "template", "filter", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L520-L548
train
24,343
briancappello/flask-unchained
flask_unchained/unchained.py
Unchained._reset
def _reset(self): """ This method is for use by tests only! """ 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 = {}
python
def _reset(self): """ This method is for use by tests only! """ 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 = {}
[ "def", "_reset", "(", "self", ")", ":", "self", ".", "bundles", "=", "AttrDict", "(", ")", "self", ".", "_bundles", "=", "_DeferredBundleFunctionsStore", "(", ")", "self", ".", "babel_bundle", "=", "None", "self", ".", "env", "=", "None", "self", ".", ...
This method is for use by tests only!
[ "This", "method", "is", "for", "use", "by", "tests", "only!" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L625-L641
train
24,344
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/forms.py
model_fields
def model_fields(model, db_session=None, only=None, exclude=None, field_args=None, converter=None, exclude_pk=False, exclude_fk=False): """ Generate a dictionary of fields for a given SQLAlchemy model. See `model_form` docstring for description of parameters. """ 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
python
def model_fields(model, db_session=None, only=None, exclude=None, field_args=None, converter=None, exclude_pk=False, exclude_fk=False): """ Generate a dictionary of fields for a given SQLAlchemy model. See `model_form` docstring for description of parameters. """ 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
[ "def", "model_fields", "(", "model", ",", "db_session", "=", "None", ",", "only", "=", "None", ",", "exclude", "=", "None", ",", "field_args", "=", "None", ",", "converter", "=", "None", ",", "exclude_pk", "=", "False", ",", "exclude_fk", "=", "False", ...
Generate a dictionary of fields for a given SQLAlchemy model. See `model_form` docstring for description of parameters.
[ "Generate", "a", "dictionary", "of", "fields", "for", "a", "given", "SQLAlchemy", "model", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/forms.py#L121-L158
train
24,345
briancappello/flask-unchained
flask_unchained/commands/urls.py
url
def url(url: str, method: str): """Show details for a specific URL.""" 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)
python
def url(url: str, method: str): """Show details for a specific URL.""" 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)
[ "def", "url", "(", "url", ":", "str", ",", "method", ":", "str", ")", ":", "try", ":", "url_rule", ",", "params", "=", "(", "current_app", ".", "url_map", ".", "bind", "(", "'localhost'", ")", ".", "match", "(", "url", ",", "method", "=", "method",...
Show details for a specific URL.
[ "Show", "details", "for", "a", "specific", "URL", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/urls.py#L18-L37
train
24,346
briancappello/flask-unchained
flask_unchained/commands/urls.py
urls
def urls(order_by: Optional[str] = None): """List all URLs registered with the app.""" 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)
python
def urls(order_by: Optional[str] = None): """List all URLs registered with the app.""" 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)
[ "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 t...
List all URLs registered with the app.
[ "List", "all", "URLs", "registered", "with", "the", "app", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/urls.py#L45-L66
train
24,347
briancappello/flask-unchained
flask_unchained/bundles/api/extensions/api.py
Api.register_converter
def register_converter(self, converter, conv_type, conv_format=None, *, name=None): """ Register custom path parameter converter. :param BaseConverter converter: Converter Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) :param str name: Name of the converter. If not None, this name is used to register the converter in the Flask app. Example:: api.register_converter( UUIDConverter, 'string', 'UUID', name='uuid') @blp.route('/pets/{uuid:pet_id}') # ... api.register_blueprint(blp) This registers the converter in the Flask app and in the internal APISpec instance. Once the converter is registered, all paths using it will have corresponding path parameter documented with the right type and format. The `name` parameter need not be passed if the converter is already registered in the app, for instance if it belongs to a Flask extension that already registers it in the app. """ if name: self.app.url_map.converters[name] = converter self.spec.register_converter(converter, conv_type, conv_format)
python
def register_converter(self, converter, conv_type, conv_format=None, *, name=None): """ Register custom path parameter converter. :param BaseConverter converter: Converter Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) :param str name: Name of the converter. If not None, this name is used to register the converter in the Flask app. Example:: api.register_converter( UUIDConverter, 'string', 'UUID', name='uuid') @blp.route('/pets/{uuid:pet_id}') # ... api.register_blueprint(blp) This registers the converter in the Flask app and in the internal APISpec instance. Once the converter is registered, all paths using it will have corresponding path parameter documented with the right type and format. The `name` parameter need not be passed if the converter is already registered in the app, for instance if it belongs to a Flask extension that already registers it in the app. """ if name: self.app.url_map.converters[name] = converter self.spec.register_converter(converter, conv_type, conv_format)
[ "def", "register_converter", "(", "self", ",", "converter", ",", "conv_type", ",", "conv_format", "=", "None", ",", "*", ",", "name", "=", "None", ")", ":", "if", "name", ":", "self", ".", "app", ".", "url_map", ".", "converters", "[", "name", "]", "...
Register custom path parameter converter. :param BaseConverter converter: Converter Subclass of werkzeug's BaseConverter :param str conv_type: Parameter type :param str conv_format: Parameter format (optional) :param str name: Name of the converter. If not None, this name is used to register the converter in the Flask app. Example:: api.register_converter( UUIDConverter, 'string', 'UUID', name='uuid') @blp.route('/pets/{uuid:pet_id}') # ... api.register_blueprint(blp) This registers the converter in the Flask app and in the internal APISpec instance. Once the converter is registered, all paths using it will have corresponding path parameter documented with the right type and format. The `name` parameter need not be passed if the converter is already registered in the app, for instance if it belongs to a Flask extension that already registers it in the app.
[ "Register", "custom", "path", "parameter", "converter", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/extensions/api.py#L138-L167
train
24,348
briancappello/flask-unchained
flask_unchained/app_factory_hook.py
AppFactoryHook.run_hook
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle]): """ Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them. """ self.process_objects(app, self.collect_from_bundles(bundles))
python
def run_hook(self, app: FlaskUnchained, bundles: List[Bundle]): """ Hook entry point. Override to disable standard behavior of iterating over bundles to discover objects and processing them. """ self.process_objects(app, self.collect_from_bundles(bundles))
[ "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.
[ "Hook", "entry", "point", ".", "Override", "to", "disable", "standard", "behavior", "of", "iterating", "over", "bundles", "to", "discover", "objects", "and", "processing", "them", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/app_factory_hook.py#L93-L98
train
24,349
briancappello/flask-unchained
flask_unchained/clips_pattern.py
singularize
def singularize(word, pos=NOUN, custom=None): """ Returns the singular of a given word. """ 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
python
def singularize(word, pos=NOUN, custom=None): """ Returns the singular of a given word. """ 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
[ "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"...
Returns the singular of a given word.
[ "Returns", "the", "singular", "of", "a", "given", "word", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/clips_pattern.py#L539-L573
train
24,350
briancappello/flask-unchained
flask_unchained/app_factory.py
AppFactory.create_basic_app
def create_basic_app(cls, bundles=None, _config_overrides=None): """ Creates a "fake" app for use while developing """ 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
python
def create_basic_app(cls, bundles=None, _config_overrides=None): """ Creates a "fake" app for use while developing """ 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
[ "def", "create_basic_app", "(", "cls", ",", "bundles", "=", "None", ",", "_config_overrides", "=", "None", ")", ":", "bundles", "=", "bundles", "or", "[", "]", "name", "=", "bundles", "[", "-", "1", "]", ".", "module_name", "if", "bundles", "else", "'b...
Creates a "fake" app for use while developing
[ "Creates", "a", "fake", "app", "for", "use", "while", "developing" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/app_factory.py#L83-L100
train
24,351
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
list_roles
def list_roles(): """ 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.')
python
def list_roles(): """ 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.')
[ "def", "list_roles", "(", ")", ":", "roles", "=", "role_manager", ".", "all", "(", ")", "if", "roles", ":", "print_table", "(", "[", "'ID'", ",", "'Name'", "]", ",", "[", "(", "role", ".", "id", ",", "role", ".", "name", ")", "for", "role", "in",...
List roles.
[ "List", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L19-L27
train
24,352
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
create_role
def create_role(name): """ Create a new role. """ 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.')
python
def create_role(name): """ Create a new role. """ 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.')
[ "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", ",...
Create a new role.
[ "Create", "a", "new", "role", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L33-L42
train
24,353
briancappello/flask-unchained
flask_unchained/bundles/security/commands/roles.py
delete_role
def delete_role(query): """ Delete a role. """ 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.')
python
def delete_role(query): """ Delete a role. """ 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.')
[ "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"...
Delete a role.
[ "Delete", "a", "role", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/roles.py#L48-L57
train
24,354
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/sqla/events.py
slugify
def slugify(field_name, slug_field_name=None, mutable=False): """Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed. Usage:: @slugify('title') def Post(Model): title = Column(String(100)) slug = Column(String(100)) # pass a second argument to specify the slug attribute field: @slugify('title', 'title_slug') def Post(Model) title = Column(String(100)) title_slug = Column(String(100)) # optionally set mutable to True for a slug that changes every time # the slugified field changes: @slugify('title', mutable=True) def Post(Model): title = Column(String(100)) slug = Column(String(100)) """ 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
python
def slugify(field_name, slug_field_name=None, mutable=False): """Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed. Usage:: @slugify('title') def Post(Model): title = Column(String(100)) slug = Column(String(100)) # pass a second argument to specify the slug attribute field: @slugify('title', 'title_slug') def Post(Model) title = Column(String(100)) title_slug = Column(String(100)) # optionally set mutable to True for a slug that changes every time # the slugified field changes: @slugify('title', mutable=True) def Post(Model): title = Column(String(100)) slug = Column(String(100)) """ 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
[ "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", ",", "_", ",", "...
Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed. Usage:: @slugify('title') def Post(Model): title = Column(String(100)) slug = Column(String(100)) # pass a second argument to specify the slug attribute field: @slugify('title', 'title_slug') def Post(Model) title = Column(String(100)) title_slug = Column(String(100)) # optionally set mutable to True for a slug that changes every time # the slugified field changes: @slugify('title', mutable=True) def Post(Model): title = Column(String(100)) slug = Column(String(100))
[ "Class", "decorator", "to", "specify", "a", "field", "to", "slugify", ".", "Slugs", "are", "immutable", "by", "default", "unless", "mutable", "=", "True", "is", "passed", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/sqla/events.py#L87-L124
train
24,355
briancappello/flask-unchained
flask_unchained/bundles/mail/utils.py
get_message_plain_text
def get_message_plain_text(msg: Message): """ Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text 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()
python
def get_message_plain_text(msg: Message): """ Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text 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()
[ "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", "...
Converts an HTML message to plain text. :param msg: A :class:`~flask_mail.Message` :return: The plain text message.
[ "Converts", "an", "HTML", "message", "to", "plain", "text", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/mail/utils.py#L31-L46
train
24,356
briancappello/flask-unchained
flask_unchained/bundles/mail/utils.py
_send_mail
def _send_mail(subject_or_message: Optional[Union[str, Message]] = None, to: Optional[Union[str, List[str]]] = None, template: Optional[str] = None, **kwargs): """ The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message` """ 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)
python
def _send_mail(subject_or_message: Optional[Union[str, Message]] = None, to: Optional[Union[str, List[str]]] = None, template: Optional[str] = None, **kwargs): """ The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message` """ 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)
[ "def", "_send_mail", "(", "subject_or_message", ":", "Optional", "[", "Union", "[", "str", ",", "Message", "]", "]", "=", "None", ",", "to", ":", "Optional", "[", "Union", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "templ...
The default function used for sending emails. :param subject_or_message: A subject string, or for backwards compatibility with stock Flask-Mail, a :class:`~flask_mail.Message` instance :param to: An email address, or a list of email addresses :param template: Which template to render. :param kwargs: Extra kwargs to pass on to :class:`~flask_mail.Message`
[ "The", "default", "function", "used", "for", "sending", "emails", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/mail/utils.py#L80-L97
train
24,357
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
extract
def extract(domain): """ Extract newly added translations keys from source code. """ 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} .')
python
def extract(domain): """ Extract newly added translations keys from source code. """ 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} .')
[ "def", "extract", "(", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "babel_cfg", "=", "_get_babel_cfg", "(", ")", "pot", "=", "os", ".", "path", ".", "join", "(...
Extract newly added translations keys from source code.
[ "Extract", "newly", "added", "translations", "keys", "from", "source", "code", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L22-L30
train
24,358
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
init
def init(lang, domain): """ Initialize translations for a language code. """ 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}')
python
def init(lang, domain): """ Initialize translations for a language code. """ 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}')
[ "def", "init", "(", "lang", ",", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "pot", "=", "os", ".", "path", ".", "join", "(", "translations_dir", ",", "f'{doma...
Initialize translations for a language code.
[ "Initialize", "translations", "for", "a", "language", "code", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L36-L43
train
24,359
briancappello/flask-unchained
flask_unchained/bundles/babel/commands.py
update
def update(domain): """ Update language-specific translations files with new keys discovered by ``flask babel extract``. """ 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}')
python
def update(domain): """ Update language-specific translations files with new keys discovered by ``flask babel extract``. """ 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}')
[ "def", "update", "(", "domain", ")", ":", "translations_dir", "=", "_get_translations_dir", "(", ")", "domain", "=", "_get_translations_domain", "(", "domain", ")", "pot", "=", "os", ".", "path", ".", "join", "(", "translations_dir", ",", "f'{domain}.pot'", ")...
Update language-specific translations files with new keys discovered by ``flask babel extract``.
[ "Update", "language", "-", "specific", "translations", "files", "with", "new", "keys", "discovered", "by", "flask", "babel", "extract", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/babel/commands.py#L59-L67
train
24,360
briancappello/flask-unchained
flask_unchained/bundles/sqlalchemy/meta_options.py
RelationshipsMetaOption.get_value
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): """overridden to merge with inherited value""" if mcs_args.Meta.abstract: return None value = getattr(base_model_meta, self.name, {}) or {} value.update(getattr(meta, self.name, {})) return value
python
def get_value(self, meta, base_model_meta, mcs_args: McsArgs): """overridden to merge with inherited value""" if mcs_args.Meta.abstract: return None value = getattr(base_model_meta, self.name, {}) or {} value.update(getattr(meta, self.name, {})) return value
[ "def", "get_value", "(", "self", ",", "meta", ",", "base_model_meta", ",", "mcs_args", ":", "McsArgs", ")", ":", "if", "mcs_args", ".", "Meta", ".", "abstract", ":", "return", "None", "value", "=", "getattr", "(", "base_model_meta", ",", "self", ".", "na...
overridden to merge with inherited value
[ "overridden", "to", "merge", "with", "inherited", "value" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/meta_options.py#L34-L40
train
24,361
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.flash
def flash(self, msg: str, category: Optional[str] = None): """ Convenience method for flashing messages. :param msg: The message to flash. :param category: The category of the message. """ if not request.is_json and app.config.FLASH_MESSAGES: flash(msg, category)
python
def flash(self, msg: str, category: Optional[str] = None): """ Convenience method for flashing messages. :param msg: The message to flash. :param category: The category of the message. """ if not request.is_json and app.config.FLASH_MESSAGES: flash(msg, category)
[ "def", "flash", "(", "self", ",", "msg", ":", "str", ",", "category", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "not", "request", ".", "is_json", "and", "app", ".", "config", ".", "FLASH_MESSAGES", ":", "flash", "(", "msg", ","...
Convenience method for flashing messages. :param msg: The message to flash. :param category: The category of the message.
[ "Convenience", "method", "for", "flashing", "messages", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L190-L198
train
24,362
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.render
def render(self, template_name: str, **ctx): """ Convenience method for rendering a template. :param template_name: The template's name. Can either be a full path, or a filename in the controller's template folder. :param ctx: Context variables to pass into the template. """ 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)
python
def render(self, template_name: str, **ctx): """ Convenience method for rendering a template. :param template_name: The template's name. Can either be a full path, or a filename in the controller's template folder. :param ctx: Context variables to pass into the template. """ 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)
[ "def", "render", "(", "self", ",", "template_name", ":", "str", ",", "*", "*", "ctx", ")", ":", "if", "'.'", "not", "in", "template_name", ":", "template_file_extension", "=", "(", "self", ".", "Meta", ".", "template_file_extension", "or", "app", ".", "c...
Convenience method for rendering a template. :param template_name: The template's name. Can either be a full path, or a filename in the controller's template folder. :param ctx: Context variables to pass into the template.
[ "Convenience", "method", "for", "rendering", "a", "template", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L200-L215
train
24,363
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.redirect
def redirect(self, where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, **url_kwargs): """ Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key name to redirect to. :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid. :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param url_kwargs: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ return redirect(where, default, override, _cls=self, **url_kwargs)
python
def redirect(self, where: Optional[str] = None, default: Optional[str] = None, override: Optional[str] = None, **url_kwargs): """ Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key name to redirect to. :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid. :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param url_kwargs: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ return redirect(where, default, override, _cls=self, **url_kwargs)
[ "def", "redirect", "(", "self", ",", "where", ":", "Optional", "[", "str", "]", "=", "None", ",", "default", ":", "Optional", "[", "str", "]", "=", "None", ",", "override", ":", "Optional", "[", "str", "]", "=", "None", ",", "*", "*", "url_kwargs",...
Convenience method for returning redirect responses. :param where: A URL, endpoint, or config key name to redirect to. :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid. :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param url_kwargs: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "Convenience", "method", "for", "returning", "redirect", "responses", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L217-L248
train
24,364
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.jsonify
def jsonify(self, data: Any, code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK, headers: Optional[Dict[str, str]] = None, ): """ Convenience method to return json responses. :param data: The python data to jsonify. :param code: The HTTP status code to return. :param headers: Any optional headers. """ return jsonify(data), code, headers or {}
python
def jsonify(self, data: Any, code: Union[int, Tuple[int, str, str]] = HTTPStatus.OK, headers: Optional[Dict[str, str]] = None, ): """ Convenience method to return json responses. :param data: The python data to jsonify. :param code: The HTTP status code to return. :param headers: Any optional headers. """ return jsonify(data), code, headers or {}
[ "def", "jsonify", "(", "self", ",", "data", ":", "Any", ",", "code", ":", "Union", "[", "int", ",", "Tuple", "[", "int", ",", "str", ",", "str", "]", "]", "=", "HTTPStatus", ".", "OK", ",", "headers", ":", "Optional", "[", "Dict", "[", "str", "...
Convenience method to return json responses. :param data: The python data to jsonify. :param code: The HTTP status code to return. :param headers: Any optional headers.
[ "Convenience", "method", "to", "return", "json", "responses", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L250-L262
train
24,365
briancappello/flask-unchained
flask_unchained/bundles/controller/controller.py
Controller.errors
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, ): """ Convenience method to return errors as json. :param errors: The list of errors. :param code: The HTTP status code. :param key: The key to return the errors under. :param headers: Any optional headers. """ return jsonify({key: errors}), code, headers or {}
python
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, ): """ Convenience method to return errors as json. :param errors: The list of errors. :param code: The HTTP status code. :param key: The key to return the errors under. :param headers: Any optional headers. """ return jsonify({key: errors}), code, headers or {}
[ "def", "errors", "(", "self", ",", "errors", ":", "List", "[", "str", "]", ",", "code", ":", "Union", "[", "int", ",", "Tuple", "[", "int", ",", "str", ",", "str", "]", "]", "=", "HTTPStatus", ".", "BAD_REQUEST", ",", "key", ":", "str", "=", "'...
Convenience method to return errors as json. :param errors: The list of errors. :param code: The HTTP status code. :param key: The key to return the errors under. :param headers: Any optional headers.
[ "Convenience", "method", "to", "return", "errors", "as", "json", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/controller.py#L264-L278
train
24,366
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
set_password
def set_password(query, password, send_email): """ Set a user's password. """ 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.')
python
def set_password(query, password, send_email): """ Set a user's password. """ 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.')
[ "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", ".", ...
Set a user's password.
[ "Set", "a", "user", "s", "password", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L95-L105
train
24,367
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
confirm_user
def confirm_user(query): """ Confirm a user account. """ 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.')
python
def confirm_user(query): """ Confirm a user account. """ 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.')
[ "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", ")", ":", ...
Confirm a user account.
[ "Confirm", "a", "user", "account", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L112-L125
train
24,368
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
add_role_to_user
def add_role_to_user(user, role): """ Add a role to a user. """ 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.')
python
def add_role_to_user(user, role): """ Add a role to a user. """ 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.')
[ "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}?'", ")", ":"...
Add a role to a user.
[ "Add", "a", "role", "to", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L168-L179
train
24,369
briancappello/flask-unchained
flask_unchained/bundles/security/commands/users.py
remove_role_from_user
def remove_role_from_user(user, role): """ Remove a role from a user. """ 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.')
python
def remove_role_from_user(user, role): """ Remove a role from a user. """ 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.')
[ "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}?'", ...
Remove a role from a user.
[ "Remove", "a", "role", "from", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/commands/users.py#L188-L199
train
24,370
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/anonymous_user_required.py
anonymous_user_required
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None): """ Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user. """ 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
python
def anonymous_user_required(*decorator_args, msg=None, category=None, redirect_url=None): """ Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user. """ 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
[ "def", "anonymous_user_required", "(", "*", "decorator_args", ",", "msg", "=", "None", ",", "category", "=", "None", ",", "redirect_url", "=", "None", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(...
Decorator requiring that there is no user currently logged in. Aborts with ``HTTP 403: Forbidden`` if there is an authenticated user.
[ "Decorator", "requiring", "that", "there", "is", "no", "user", "currently", "logged", "in", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/anonymous_user_required.py#L9-L31
train
24,371
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.login_user
def login_user(self, user: User, remember: Optional[bool] = None, duration: Optional[timedelta] = None, force: bool = False, fresh: bool = True, ) -> bool: """ 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``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: 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
python
def login_user(self, user: User, remember: Optional[bool] = None, duration: Optional[timedelta] = None, force: bool = False, fresh: bool = True, ) -> bool: """ 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``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: 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
[ "def", "login_user", "(", "self", ",", "user", ":", "User", ",", "remember", ":", "Optional", "[", "bool", "]", "=", "None", ",", "duration", ":", "Optional", "[", "timedelta", "]", "=", "None", ",", "force", ":", "bool", "=", "False", ",", "fresh", ...
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``. This will return ``True`` if the log in attempt succeeds, and ``False`` if it fails (i.e. because the user is inactive). :param user: The user object to log in. :type user: object :param remember: Whether to remember the user after their session expires. Defaults to ``False``. :type remember: bool :param duration: The amount of time before the remember cookie expires. If ``None`` the value set in the settings is used. Defaults to ``None``. :type duration: :class:`datetime.timedelta` :param force: If the user is inactive, setting this to ``True`` will log them in regardless. Defaults to ``False``. :type force: bool :param fresh: setting this to ``False`` will log in the user with a session marked as not "fresh". Defaults to ``True``. :type fresh: bool
[ "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", ...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L42-L106
train
24,372
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.register_user
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): """ Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. """ 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
python
def register_user(self, user, allow_login=None, send_email=None, _force_login_without_confirmation=False): """ Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise. """ 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
[ "def", "register_user", "(", "self", ",", "user", ",", "allow_login", "=", "None", ",", "send_email", "=", "None", ",", "_force_login_without_confirmation", "=", "False", ")", ":", "should_login_user", "=", "(", "not", "self", ".", "security", ".", "confirmabl...
Service method to register a user. Sends signal `user_registered`. Returns True if the user has been logged in, False otherwise.
[ "Service", "method", "to", "register", "a", "user", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L122-L163
train
24,373
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.change_password
def change_password(self, user, password, send_email=None): """ Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force either sending or not sending an email. """ 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)
python
def change_password(self, user, password, send_email=None): """ Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force either sending or not sending an email. """ 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)
[ "def", "change_password", "(", "self", ",", "user", ",", "password", ",", "send_email", "=", "None", ")", ":", "user", ".", "password", "=", "password", "self", ".", "user_manager", ".", "save", "(", "user", ")", "if", "send_email", "or", "(", "app", "...
Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to override the config option ``SECURITY_SEND_PASSWORD_CHANGED_EMAIL`` and force either sending or not sending an email.
[ "Service", "method", "to", "change", "a", "user", "s", "password", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L165-L186
train
24,374
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.confirm_user
def confirm_user(self, user): """ Confirms the specified user. Returns False if the user has already been confirmed, True otherwise. :param user: The user to confirm. """ 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
python
def confirm_user(self, user): """ Confirms the specified user. Returns False if the user has already been confirmed, True otherwise. :param user: The user to confirm. """ 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
[ "def", "confirm_user", "(", "self", ",", "user", ")", ":", "if", "user", ".", "confirmed_at", "is", "not", "None", ":", "return", "False", "user", ".", "confirmed_at", "=", "self", ".", "security", ".", "datetime_factory", "(", ")", "user", ".", "active"...
Confirms the specified user. Returns False if the user has already been confirmed, True otherwise. :param user: The user to confirm.
[ "Confirms", "the", "specified", "user", ".", "Returns", "False", "if", "the", "user", "has", "already", "been", "confirmed", "True", "otherwise", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L249-L263
train
24,375
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_service.py
SecurityService.send_mail
def send_mail(self, subject, to, template, **template_ctx): """ Utility method to send mail with the `mail` template context. """ 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))
python
def send_mail(self, subject, to, template, **template_ctx): """ Utility method to send mail with the `mail` template context. """ 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))
[ "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 in...
Utility method to send mail with the `mail` template context.
[ "Utility", "method", "to", "send", "mail", "with", "the", "mail", "template", "context", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_service.py#L265-L277
train
24,376
briancappello/flask-unchained
flask_unchained/bundles/api/model_serializer.py
_ModelSerializerMetaclass.get_declared_fields
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls): """ Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option. """ 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
python
def get_declared_fields(mcs, klass, cls_fields, inherited_fields, dict_cls): """ Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option. """ 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
[ "def", "get_declared_fields", "(", "mcs", ",", "klass", ",", "cls_fields", ",", "inherited_fields", ",", "dict_cls", ")", ":", "opts", "=", "klass", ".", "opts", "converter", "=", "opts", ".", "model_converter", "(", "schema_cls", "=", "klass", ")", "base_fi...
Updates declared fields with fields converted from the SQLAlchemy model passed as the `model` class Meta option.
[ "Updates", "declared", "fields", "with", "fields", "converted", "from", "the", "SQLAlchemy", "model", "passed", "as", "the", "model", "class", "Meta", "option", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_serializer.py#L161-L173
train
24,377
briancappello/flask-unchained
flask_unchained/commands/qtconsole.py
JupyterWidget.reset
def reset(self, clear=False): """ Overridden to customize the order that the banners are printed """ 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()
python
def reset(self, clear=False): """ Overridden to customize the order that the banners are printed """ 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()
[ "def", "reset", "(", "self", ",", "clear", "=", "False", ")", ":", "if", "self", ".", "_executing", ":", "self", ".", "_executing", "=", "False", "self", ".", "_request_info", "[", "'execute'", "]", "=", "{", "}", "self", ".", "_reading", "=", "False...
Overridden to customize the order that the banners are printed
[ "Overridden", "to", "customize", "the", "order", "that", "the", "banners", "are", "printed" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/qtconsole.py#L100-L119
train
24,378
briancappello/flask-unchained
flask_unchained/commands/qtconsole.py
IPythonKernelApp.log_connection_info
def log_connection_info(self): """ Overridden to customize the start-up message printed to the terminal """ _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)
python
def log_connection_info(self): """ Overridden to customize the start-up message printed to the terminal """ _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)
[ "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 '", "'(a...
Overridden to customize the start-up message printed to the terminal
[ "Overridden", "to", "customize", "the", "start", "-", "up", "message", "printed", "to", "the", "terminal" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/qtconsole.py#L135-L151
train
24,379
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
url_for
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]: """ An improved version of flask's url_for function :param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint name, an app config key, or an already-formed url. if _cls is specified, it also accepts a method name. :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, can also pass a method name as the first argument :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ 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)
python
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]: """ An improved version of flask's url_for function :param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint name, an app config key, or an already-formed url. if _cls is specified, it also accepts a method name. :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, can also pass a method name as the first argument :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ 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)
[ "def", "url_for", "(", "endpoint_or_url_or_config_key", ":", "str", ",", "_anchor", ":", "Optional", "[", "str", "]", "=", "None", ",", "_cls", ":", "Optional", "[", "Union", "[", "object", ",", "type", "]", "]", "=", "None", ",", "_external", ":", "Op...
An improved version of flask's url_for function :param endpoint_or_url_or_config_key: what to lookup. it can be an endpoint name, an app config key, or an already-formed url. if _cls is specified, it also accepts a method name. :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, can also pass a method name as the first argument :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "An", "improved", "version", "of", "flask", "s", "url_for", "function" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L99-L161
train
24,380
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
redirect
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: """ An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ 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('/')
python
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: """ An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs. """ 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('/')
[ "def", "redirect", "(", "where", ":", "Optional", "[", "str", "]", "=", "None", ",", "default", ":", "Optional", "[", "str", "]", "=", "None", ",", "override", ":", "Optional", "[", "str", "]", "=", "None", ",", "_anchor", ":", "Optional", "[", "st...
An improved version of flask's redirect function :param where: A URL, endpoint, or config key name to redirect to :param default: A URL, endpoint, or config key name to redirect to if ``where`` is invalid :param override: explicitly redirect to a URL, endpoint, or config key name (takes precedence over the ``next`` value in query strings or forms) :param values: the variable arguments of the URL rule :param _anchor: if provided this is added as anchor to the URL. :param _cls: if specified, allows a method name to be passed to where, default, and/or override :param _external: if set to ``True``, an absolute URL is generated. Server address can be changed via ``SERVER_NAME`` configuration variable which defaults to `localhost`. :param _external_host: if specified, the host of an external server to generate urls for (eg https://example.com or localhost:8888) :param _method: if provided this explicitly specifies an HTTP method. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default behavior uses the same scheme as the current request, or ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no request context is available. As of Werkzeug 0.10, this also can be set to an empty string to build protocol-relative URLs.
[ "An", "improved", "version", "of", "flask", "s", "redirect", "function" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L193-L245
train
24,381
briancappello/flask-unchained
flask_unchained/bundles/controller/utils.py
_url_for
def _url_for(endpoint: str, **values) -> Union[str, None]: """ 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 :param endpoint: the name of the endpoint :param values: the variable arguments of the URL rule :return: a url path, or 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)
python
def _url_for(endpoint: str, **values) -> Union[str, None]: """ 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 :param endpoint: the name of the endpoint :param values: the variable arguments of the URL rule :return: a url path, or 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)
[ "def", "_url_for", "(", "endpoint", ":", "str", ",", "*", "*", "values", ")", "->", "Union", "[", "str", ",", "None", "]", ":", "_external_host", "=", "values", ".", "pop", "(", "'_external_host'", ",", "None", ")", "is_external", "=", "bool", "(", "...
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 :param endpoint: the name of the endpoint :param values: the variable arguments of the URL rule :return: a url path, or None
[ "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", "es...
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/utils.py#L263-L284
train
24,382
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/roles_required.py
roles_required
def roles_required(*roles): """ Decorator which specifies that a user must have all the specified roles. Aborts with HTTP 403: Forbidden if the user doesn't have the required roles. Example:: @app.route('/dashboard') @roles_required('ROLE_ADMIN', 'ROLE_EDITOR') def dashboard(): return 'Dashboard' The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles in order to view the page. :param roles: The 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
python
def roles_required(*roles): """ Decorator which specifies that a user must have all the specified roles. Aborts with HTTP 403: Forbidden if the user doesn't have the required roles. Example:: @app.route('/dashboard') @roles_required('ROLE_ADMIN', 'ROLE_EDITOR') def dashboard(): return 'Dashboard' The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles in order to view the page. :param roles: The 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
[ "def", "roles_required", "(", "*", "roles", ")", ":", "def", "wrapper", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "perms", "=", "[", "Permission", "(", "RoleNeed...
Decorator which specifies that a user must have all the specified roles. Aborts with HTTP 403: Forbidden if the user doesn't have the required roles. Example:: @app.route('/dashboard') @roles_required('ROLE_ADMIN', 'ROLE_EDITOR') def dashboard(): return 'Dashboard' The current user must have both the `ROLE_ADMIN` and `ROLE_EDITOR` roles in order to view the page. :param roles: The required roles.
[ "Decorator", "which", "specifies", "that", "a", "user", "must", "have", "all", "the", "specified", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/roles_required.py#L7-L34
train
24,383
briancappello/flask-unchained
flask_unchained/bundles/security/services/security_utils_service.py
SecurityUtilsService.verify_hash
def verify_hash(self, hashed_data, compare_data): """ Verify a hash in the security token hashing context. """ return self.security.hashing_context.verify( encode_string(compare_data), hashed_data)
python
def verify_hash(self, hashed_data, compare_data): """ Verify a hash in the security token hashing context. """ return self.security.hashing_context.verify( encode_string(compare_data), hashed_data)
[ "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.
[ "Verify", "a", "hash", "in", "the", "security", "token", "hashing", "context", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/services/security_utils_service.py#L89-L94
train
24,384
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/auth_required.py
auth_required
def auth_required(decorated_fn=None, **role_rules): """ Decorator for requiring an authenticated user, optionally with roles. Roles are passed as keyword arguments, like so:: @auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE']) One of role or roles kwargs can also be combined with one_of:: @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS']) Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or ``HTTP 403: Forbidden`` if any of the specified role checks fail. """ 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
python
def auth_required(decorated_fn=None, **role_rules): """ Decorator for requiring an authenticated user, optionally with roles. Roles are passed as keyword arguments, like so:: @auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE']) One of role or roles kwargs can also be combined with one_of:: @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS']) Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or ``HTTP 403: Forbidden`` if any of the specified role checks fail. """ 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
[ "def", "auth_required", "(", "decorated_fn", "=", "None", ",", "*", "*", "role_rules", ")", ":", "required_roles", "=", "[", "]", "one_of_roles", "=", "[", "]", "if", "not", "(", "decorated_fn", "and", "callable", "(", "decorated_fn", ")", ")", ":", "if"...
Decorator for requiring an authenticated user, optionally with roles. Roles are passed as keyword arguments, like so:: @auth_required(role='REQUIRE_THIS_ONE_ROLE') @auth_required(roles=['REQUIRE', 'ALL', 'OF', 'THESE', 'ROLES']) @auth_required(one_of=['EITHER_THIS_ROLE', 'OR_THIS_ONE']) One of role or roles kwargs can also be combined with one_of:: @auth_required(role='REQUIRED', one_of=['THIS', 'OR_THIS']) Aborts with ``HTTP 401: Unauthorized`` if no user is logged in, or ``HTTP 403: Forbidden`` if any of the specified role checks fail.
[ "Decorator", "for", "requiring", "an", "authenticated", "user", "optionally", "with", "roles", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required.py#L13-L54
train
24,385
briancappello/flask-unchained
flask_unchained/bundles/security/decorators/auth_required.py
_auth_required
def _auth_required(): """ Decorator that protects endpoints through token and session auth mechanisms """ 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
python
def _auth_required(): """ Decorator that protects endpoints through token and session auth mechanisms """ 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
[ "def", "_auth_required", "(", ")", ":", "login_mechanisms", "=", "(", "(", "'token'", ",", "lambda", ":", "_check_token", "(", ")", ")", ",", "(", "'session'", ",", "lambda", ":", "current_user", ".", "is_authenticated", ")", ",", ")", "def", "wrapper", ...
Decorator that protects endpoints through token and session auth mechanisms
[ "Decorator", "that", "protects", "endpoints", "through", "token", "and", "session", "auth", "mechanisms" ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/decorators/auth_required.py#L57-L75
train
24,386
briancappello/flask-unchained
flask_unchained/bundles/celery/tasks.py
async_mail_task
def async_mail_task(subject_or_message, to=None, template=None, **kwargs): """ Celery task to send emails asynchronously using the mail bundle. """ to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
python
def async_mail_task(subject_or_message, to=None, template=None, **kwargs): """ Celery task to send emails asynchronously using the mail bundle. """ to = to or kwargs.pop('recipients', []) msg = make_message(subject_or_message, to, template, **kwargs) with mail.connect() as connection: connection.send(msg)
[ "def", "async_mail_task", "(", "subject_or_message", ",", "to", "=", "None", ",", "template", "=", "None", ",", "*", "*", "kwargs", ")", ":", "to", "=", "to", "or", "kwargs", ".", "pop", "(", "'recipients'", ",", "[", "]", ")", "msg", "=", "make_mess...
Celery task to send emails asynchronously using the mail bundle.
[ "Celery", "task", "to", "send", "emails", "asynchronously", "using", "the", "mail", "bundle", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/celery/tasks.py#L16-L23
train
24,387
briancappello/flask-unchained
flask_unchained/bundles/api/__init__.py
ApiBundle.after_init_app
def after_init_app(self, app: FlaskUnchained): """ Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models. """ self.set_json_encoder(app) app.before_first_request(self.register_model_resources)
python
def after_init_app(self, app: FlaskUnchained): """ Configure the JSON encoder for Flask to be able to serialize Enums, LocalProxy objects, and SQLAlchemy models. """ self.set_json_encoder(app) app.before_first_request(self.register_model_resources)
[ "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.
[ "Configure", "the", "JSON", "encoder", "for", "Flask", "to", "be", "able", "to", "serialize", "Enums", "LocalProxy", "objects", "and", "SQLAlchemy", "models", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/__init__.py#L52-L58
train
24,388
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.endpoint
def endpoint(self): """ The endpoint for this route. """ 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}'
python
def endpoint(self): """ The endpoint for this route. """ 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}'
[ "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", ...
The endpoint for this route.
[ "The", "endpoint", "for", "this", "route", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L102-L113
train
24,389
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.method_name
def method_name(self): """ The string name of this route's view function. """ if isinstance(self.view_func, str): return self.view_func return self.view_func.__name__
python
def method_name(self): """ The string name of this route's view function. """ if isinstance(self.view_func, str): return self.view_func return self.view_func.__name__
[ "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.
[ "The", "string", "name", "of", "this", "route", "s", "view", "function", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L133-L139
train
24,390
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.module_name
def module_name(self): """ The module where this route's view function was defined. """ 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__
python
def module_name(self): """ The module where this route's view function was defined. """ 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__
[ "def", "module_name", "(", "self", ")", ":", "if", "not", "self", ".", "view_func", ":", "return", "None", "elif", "self", ".", "_controller_cls", ":", "rv", "=", "inspect", ".", "getmodule", "(", "self", ".", "_controller_cls", ")", ".", "__name__", "re...
The module where this route's view function was defined.
[ "The", "module", "where", "this", "route", "s", "view", "function", "was", "defined", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L153-L162
train
24,391
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.full_rule
def full_rule(self): """ The full url rule for this route, including any blueprint prefix. """ return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))
python
def full_rule(self): """ The full url rule for this route, including any blueprint prefix. """ return join(self.bp_prefix, self.rule, trailing_slash=self.rule.endswith('/'))
[ "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.
[ "The", "full", "url", "rule", "for", "this", "route", "including", "any", "blueprint", "prefix", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L195-L199
train
24,392
briancappello/flask-unchained
flask_unchained/bundles/controller/route.py
Route.full_name
def full_name(self): """ The full name of this route's view function, including the module path and controller name, if any. """ 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}'
python
def full_name(self): """ The full name of this route's view function, including the module path and controller name, if any. """ 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}'
[ "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.__n...
The full name of this route's view function, including the module path and controller name, if any.
[ "The", "full", "name", "of", "this", "route", "s", "view", "function", "including", "the", "module", "path", "and", "controller", "name", "if", "any", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/route.py#L235-L246
train
24,393
briancappello/flask-unchained
flask_unchained/commands/new.py
project
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ 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}')
python
def project(dest, app_bundle, force, dev, admin, api, celery, graphene, mail, oauth, security, session, sqlalchemy, webpack): """ Create a new Flask Unchained project. """ 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}')
[ "def", "project", "(", "dest", ",", "app_bundle", ",", "force", ",", "dev", ",", "admin", ",", "api", ",", "celery", ",", "graphene", ",", "mail", ",", "oauth", ",", "security", ",", "session", ",", "sqlalchemy", ",", "webpack", ")", ":", "if", "os",...
Create a new Flask Unchained project.
[ "Create", "a", "new", "Flask", "Unchained", "project", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/new.py#L182-L224
train
24,394
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.produce
def produce(self, *args, **kwargs): """Produce a new set of plugins, treating the current set as plugin factories. """ new_plugins = [] for p in self._plugins: r = p(*args, **kwargs) new_plugins.append(r) return PluginManager(new_plugins)
python
def produce(self, *args, **kwargs): """Produce a new set of plugins, treating the current set as plugin factories. """ new_plugins = [] for p in self._plugins: r = p(*args, **kwargs) new_plugins.append(r) return PluginManager(new_plugins)
[ "def", "produce", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new_plugins", "=", "[", "]", "for", "p", "in", "self", ".", "_plugins", ":", "r", "=", "p", "(", "*", "args", ",", "*", "*", "kwargs", ")", "new_plugins", ".",...
Produce a new set of plugins, treating the current set as plugin factories.
[ "Produce", "a", "new", "set", "of", "plugins", "treating", "the", "current", "set", "as", "plugin", "factories", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L15-L24
train
24,395
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.call
def call(self, methodname, *args, **kwargs): """Call a common method on all the plugins, if it exists.""" for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue yield method(*args, **kwargs)
python
def call(self, methodname, *args, **kwargs): """Call a common method on all the plugins, if it exists.""" for plugin in self._plugins: method = getattr(plugin, methodname, None) if method is None: continue yield method(*args, **kwargs)
[ "def", "call", "(", "self", ",", "methodname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "plugin", "in", "self", ".", "_plugins", ":", "method", "=", "getattr", "(", "plugin", ",", "methodname", ",", "None", ")", "if", "method", "...
Call a common method on all the plugins, if it exists.
[ "Call", "a", "common", "method", "on", "all", "the", "plugins", "if", "it", "exists", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L26-L33
train
24,396
ironfroggy/straight.plugin
straight/plugin/manager.py
PluginManager.pipe
def pipe(self, methodname, first_arg, *args, **kwargs): """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. Useful to utilize plugins as sets of filters. """ 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
python
def pipe(self, methodname, first_arg, *args, **kwargs): """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. Useful to utilize plugins as sets of filters. """ 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
[ "def", "pipe", "(", "self", ",", "methodname", ",", "first_arg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "plugin", "in", "self", ".", "_plugins", ":", "method", "=", "getattr", "(", "plugin", ",", "methodname", ",", "None", ")", ...
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. Useful to utilize plugins as sets of filters.
[ "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", "...
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/manager.py#L46-L61
train
24,397
ironfroggy/straight.plugin
straight/plugin/loaders.py
unified_load
def unified_load(namespace, subclasses=None, recurse=False): """Provides a unified interface to both the module and class loaders, finding modules by default or classes if given a ``subclasses`` parameter. """ if subclasses is not None: return ClassLoader(recurse=recurse).load(namespace, subclasses=subclasses) else: return ModuleLoader(recurse=recurse).load(namespace)
python
def unified_load(namespace, subclasses=None, recurse=False): """Provides a unified interface to both the module and class loaders, finding modules by default or classes if given a ``subclasses`` parameter. """ if subclasses is not None: return ClassLoader(recurse=recurse).load(namespace, subclasses=subclasses) else: return ModuleLoader(recurse=recurse).load(namespace)
[ "def", "unified_load", "(", "namespace", ",", "subclasses", "=", "None", ",", "recurse", "=", "False", ")", ":", "if", "subclasses", "is", "not", "None", ":", "return", "ClassLoader", "(", "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.
[ "Provides", "a", "unified", "interface", "to", "both", "the", "module", "and", "class", "loaders", "finding", "modules", "by", "default", "or", "classes", "if", "given", "a", "subclasses", "parameter", "." ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/loaders.py#L161-L169
train
24,398
ironfroggy/straight.plugin
straight/plugin/loaders.py
ModuleLoader._fill_cache
def _fill_cache(self, namespace): """Load all modules found in a namespace""" modules = self._findPluginModules(namespace) self._cache = list(modules)
python
def _fill_cache(self, namespace): """Load all modules found in a namespace""" modules = self._findPluginModules(namespace) self._cache = list(modules)
[ "def", "_fill_cache", "(", "self", ",", "namespace", ")", ":", "modules", "=", "self", ".", "_findPluginModules", "(", "namespace", ")", "self", ".", "_cache", "=", "list", "(", "modules", ")" ]
Load all modules found in a namespace
[ "Load", "all", "modules", "found", "in", "a", "namespace" ]
aaaf68db51b823d164cf714b1be2262a75ee2a79
https://github.com/ironfroggy/straight.plugin/blob/aaaf68db51b823d164cf714b1be2262a75ee2a79/straight/plugin/loaders.py#L111-L116
train
24,399