当前位置: 首页>>代码示例>>Python>>正文


Python flask_login.current_user方法代码示例

本文整理汇总了Python中flask_login.current_user方法的典型用法代码示例。如果您正苦于以下问题:Python flask_login.current_user方法的具体用法?Python flask_login.current_user怎么用?Python flask_login.current_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask_login的用法示例。


在下文中一共展示了flask_login.current_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: init_logout_timeout

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def init_logout_timeout(app):
    """Add logout user after timeout"""

    def before_request():
        _force_log_out_after = conf.getint('webserver', 'FORCE_LOG_OUT_AFTER', fallback=0)
        if _force_log_out_after > 0:
            flask.session.permanent = True
            app.permanent_session_lifetime = datetime.timedelta(minutes=_force_log_out_after)
            flask.session.modified = True
            flask.g.user = flask_login.current_user

    app.before_request(before_request) 
开发者ID:apache,项目名称:airflow,代码行数:14,代码来源:init_session.py

示例2: __init__

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def __init__(self, *args, **kwargs):
        super().__init__(
            base_url="https://api.github.com/",
            authorization_url="https://github.com/login/oauth/authorize",
            token_url="https://github.com/login/oauth/access_token",
            session_class=GitHubSession,
            storage=SQLAlchemyStorage(
                OAuth, db.session, user=current_user, user_required=False, cache=cache
            ),
            *args,
            **kwargs,
        )
        self.from_config.update(
            {
                "client_id": "GITHUB_OAUTH_CLIENT_ID",
                "client_secret": "GITHUB_OAUTH_CLIENT_SECRET",
                "scope": "GITHUB_SCOPE",
                "members_team_id": "GITHUB_MEMBERS_TEAM_ID",
                "roadies_team_id": "GITHUB_ROADIES_TEAM_ID",
                "admin_access_token": "GITHUB_ADMIN_TOKEN",
                "org_id": "GITHUB_ORG_ID",
            }
        ) 
开发者ID:jazzband-roadies,项目名称:website,代码行数:25,代码来源:blueprint.py

示例3: _grantsetter

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def _grantsetter(self, client_id, code, request, *args, **kwargs):
        # pylint: disable=method-hidden,unused-argument
        # TODO: review expiration time
        # decide the expires time yourself
        expires = datetime.utcnow() + timedelta(seconds=100)
        try:
            with db.session.begin():
                grant_instance = self._grant_class(
                    client_id=client_id,
                    code=code['code'],
                    redirect_uri=request.redirect_uri,
                    scopes=request.scopes,
                    user=current_user,
                    expires=expires
                )
                db.session.add(grant_instance)
        except sqlalchemy.exc.IntegrityError:
            log.exception("Grant-setter has failed.")
            return None
        return grant_instance 
开发者ID:frol,项目名称:flask-restplus-server-example,代码行数:22,代码来源:oauth2.py

示例4: refresh_user

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def refresh_user():
    auth_methods = {am.name: am for am in current_app.auth_methods}
    user_auth_method = auth_methods[flask_login.current_user.authmethod]
    if user_auth_method.refresh(flask_login.current_user):
        current_app.logger.debug("Marking '{}' as fresh".format(
            flask_login.current_user))
        flask_login.confirm_login()
        # Call the original endpoint
        view = current_app.view_functions[request.endpoint]
        return view(**request.view_args)
    else:
        flash(login_manager.needs_refresh_message,
                category=login_manager.needs_refresh_message_category)
        original_url = url_for(request.endpoint, **request.view_args)
        return redirect(url_for('login.login', next=original_url,
                _anchor=user_auth_method.safe_name)) 
开发者ID:paxswill,项目名称:evesrp,代码行数:18,代码来源:login.py

示例5: _get_user_data

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def _get_user_data(self):
        if not hasattr(request, '_user_data'):
            try:
                resp = self.session.get(self.domain + '/oauth/verify').json()
                current_app.logger.debug(u"SSO lookup results: {}".format(resp))
            except OAuth2Error as e:
                current_app.logger.error(u"Error verifying user data for user "
                                         u"'{}': {}".format(current_user, e))
                # The session can be bugged in some situations. Kill it to be
                # sure.
                del self.session
                raise
            try:
                char_data = {
                    'name': resp[u'CharacterName'],
                    'id': resp[u'CharacterID'],
                    'owner_hash': resp[u'CharacterOwnerHash'],
                }
                request._user_data = char_data
            except (TypeError, KeyError):
                abort(500, u"Error in receiving EVE SSO response: {}".format(
                        resp))
        return request._user_data 
开发者ID:paxswill,项目名称:evesrp,代码行数:25,代码来源:evesso.py

示例6: form_postprocessing

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def form_postprocessing(form, form_data):
    data = {**form_data.to_dict(), **{"user": current_user}}
    if request.files:
        data["file"] = request.files["file"]
    for property, field in form_properties[form_data.get("form_type")].items():
        if field["type"] in ("object-list", "multiselect", "multiselect-string"):
            value = form_data.getlist(property)
            if field["type"] == "multiselect-string":
                value = str(value)
            data[property] = value
        elif field["type"] == "object":
            data[property] = form_data.get(property)
        elif field["type"] == "field-list":
            data[property] = []
            for entry in getattr(form, property).entries:
                properties = entry.data
                properties.pop("csrf_token")
                data[property].append(properties)
        elif field["type"] == "bool":
            data[property] = property in form_data
        elif field["type"] in db.field_conversion and property in data:
            data[property] = db.field_conversion[field["type"]](form_data[property])
    return data 
开发者ID:eNMS-automation,项目名称:eNMS,代码行数:25,代码来源:__init__.py

示例7: update

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def update(self, type, **kwargs):
        try:
            must_be_new = kwargs.get("id") == ""
            for arg in ("name", "scoped_name"):
                if arg in kwargs:
                    kwargs[arg] = kwargs[arg].strip()
            kwargs["last_modified"] = self.get_time()
            kwargs["creator"] = kwargs["user"] = getattr(current_user, "name", "")
            instance = db.factory(type, must_be_new=must_be_new, **kwargs)
            if kwargs.get("copy"):
                db.fetch(type, id=kwargs["copy"]).duplicate(clone=instance)
            db.session.flush()
            return instance.serialized
        except db.rbac_error:
            return {"alert": "Error 403 - Operation not allowed."}
        except Exception as exc:
            db.session.rollback()
            if isinstance(exc, IntegrityError):
                return {"alert": f"There is already a {type} with the same parameters."}
            return {"alert": str(exc)} 
开发者ID:eNMS-automation,项目名称:eNMS,代码行数:22,代码来源:base.py

示例8: get

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def get(self, sketch_id):
        """Handles GET request to the resource.

        Handler for /api/v1/sketches/<int:sketch_id>/aggregation/

        Args:
            sketch_id: Integer primary key for a sketch database model

        Returns:
            Views in JSON (instance of flask.wrappers.Response)
        """
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(
                HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')

        if not sketch.has_permission(current_user, 'read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN,
                  'User does not have read access controls on sketch.')
        aggregations = sketch.get_named_aggregations
        return self.to_json(aggregations) 
开发者ID:google,项目名称:timesketch,代码行数:23,代码来源:aggregation.py

示例9: get

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def get(self, sketch_id):
        """Handles GET request to the resource.

        Args:
            sketch_id: Integer primary key for a sketch database model

        Returns:
            Views in JSON (instance of flask.wrappers.Response)
        """
        sketch = Sketch.query.get_with_acl(sketch_id)
        if not sketch:
            abort(
                HTTP_STATUS_CODE_NOT_FOUND, 'No sketch found with this ID.')
        if not sketch.has_permission(current_user, 'read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN,
                  'User does not have read access controls on sketch.')
        return self.to_json(sketch.get_named_views) 
开发者ID:google,项目名称:timesketch,代码行数:19,代码来源:view.py

示例10: get_with_acl

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def get_with_acl(self, model_id, user=current_user):
        """Get a database object with permission check enforced.

        Args:
            model_id: The integer ID of the model to get.
            user: User (instance of timesketch.models.user.User)

        Returns:
            A BaseQuery instance.
        """
        result_obj = self.get(model_id)
        if not result_obj:
            abort(HTTP_STATUS_CODE_NOT_FOUND)
        try:
            if result_obj.get_status.status == 'deleted':
                abort(HTTP_STATUS_CODE_NOT_FOUND)
        except AttributeError:
            pass
        if result_obj.is_public:
            return result_obj
        if not result_obj.has_permission(user=user, permission='read'):
            abort(HTTP_STATUS_CODE_FORBIDDEN)
        return result_obj 
开发者ID:google,项目名称:timesketch,代码行数:25,代码来源:__init__.py

示例11: to_db

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def to_db(data=None, as_api=False):
        """
        记录日志到数据库

        :param data: dict, 键必须是 log 表字段名
        :param as_api:
        :return:
        """
        log = {
            'log_action': request.endpoint,
            'log_operator': getattr(current_user, 'realname', request.remote_addr)
        }

        isinstance(data, dict) and log.update(data)
        if not isinstance(log.get('log_content', ''), str):
            log['log_content'] = json.dumps(log['log_content'], ensure_ascii=False)

        res = TBLog().insert(log)
        if not res and as_api:
            raise APIFailure('日志入库失败')

        return res 
开发者ID:fufuok,项目名称:FF.PyAdmin,代码行数:24,代码来源:log.py

示例12: conversation_reply

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def conversation_reply(
    service_id,
    notification_id,
    from_folder=None,
):
    return render_template(
        'views/templates/choose-reply.html',
        templates_and_folders=TemplateList(
            current_service,
            template_folder_id=from_folder,
            user=current_user,
            template_type='sms'
        ),
        template_folder_path=current_service.get_template_folder_path(from_folder),
        search_form=SearchByNameForm(),
        notification_id=notification_id,
        template_type='sms'
    ) 
开发者ID:alphagov,项目名称:notifications-admin,代码行数:20,代码来源:conversation.py

示例13: confirm_email

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def confirm_email(token):
    """View function which handles a email confirmation request."""

    expired, invalid, user = confirm_email_token_status(token)

    if not user or invalid:
        invalid = True

    already_confirmed = user is not None and user.confirmed_at is not None
    expired_and_not_confirmed = expired and not already_confirmed

    if expired_and_not_confirmed:
        send_confirmation_instructions(user)

    if invalid or expired_and_not_confirmed:
        return redirect(get_url(_security.confirm_error_view))

    if confirm_user(user):
        after_this_request(_commit)

    if user != current_user:
        logout_user()
        login_user(user)

    return redirect(get_url(_security.post_confirm_view)) 
开发者ID:briancappello,项目名称:flask-react-spa,代码行数:27,代码来源:confirm_email.py

示例14: index

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def index():
    if not flask_login.current_user.is_authenticated:
        return redirect(url_for('main.login'))
    else:
        user_profile = "Could not access fitbit profile"
        fitbit_creds = get_user_fitbit_credentials(flask_login.current_user.id)
        if fitbit_creds:
            with fitbit_client(fitbit_creds) as client:
                try:
                    profile_response = client.user_profile_get()
                    user_profile = "{} has been on fitbit since {}".format(
                        profile_response['user']['fullName'],
                        profile_response['user']['memberSince']
                    )
                except BadResponse:
                    flash("Api Call Failed")
        return render_template('index.html', user_profile=user_profile, permission_url=get_permission_screen_url()) 
开发者ID:Stasonis,项目名称:fitbit-api-example-python,代码行数:19,代码来源:views.py

示例15: dashboard

# 需要导入模块: import flask_login [as 别名]
# 或者: from flask_login import current_user [as 别名]
def dashboard():
    """Logged in Dashboard screen."""
    session['redis_test'] = 'This is a session variable.'
    return render_template(
        'dashboard.jinja2',
        title='Flask-Session Tutorial.',
        template='dashboard-template',
        current_user=current_user,
        body="You are now logged in!"
    ) 
开发者ID:hackersandslackers,项目名称:flask-session-tutorial,代码行数:12,代码来源:routes.py


注:本文中的flask_login.current_user方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。