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


Python session.get方法代码示例

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


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

示例1: setup_session

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def setup_session(url: str) -> None:
    discord = make_session(state=session.get('oauth2_state'))
    token = discord.fetch_token(
        TOKEN_URL,
        client_secret=OAUTH2_CLIENT_SECRET,
        authorization_response=url)
    session.permanent = True
    session['oauth2_token'] = token
    discord = make_session(token=session.get('oauth2_token'))
    user = discord.get(API_BASE_URL + '/users/@me').json()
    session['id'] = user['id']
    session['discord_id'] = user['id']
    session['discord_locale'] = user['locale']
    guilds = discord.get(API_BASE_URL + '/users/@me/guilds').json()
    wrong_guilds = False # protect against an unexpected response from discord
    session['in_guild'] = False
    session['admin'] = False
    session['demimod'] = False
    for guild in guilds:
        if isinstance(guild, dict) and 'id' in guild:
            if guild['id'] == configuration.get('guild_id'):
                session['admin'] = (guild['permissions'] & 0x10000000) != 0 # Check for the MANAGE_ROLES permissions on Discord as a proxy for "is admin".
                session['demimod'] = (guild['permissions'] & 0x20000) != 0 # Check for the "Mention @everyone" permissions on Discord as a proxy for "is demimod".
                session['in_guild'] = True
        else:
            wrong_guilds = True
    if wrong_guilds:
        logger.warning('auth.py: unexpected discord response. Guilds: {g}'.format(g=guilds)) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:30,代码来源:oauth.py

示例2: login

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def login(p: person.Person) -> None:
    session['logged_person_id'] = p.id
    session['person_id'] = p.id
    session['mtgo_username'] = p.name
    session.permanent = True
    if p.locale != session.get('discord_locale'):
        person.set_locale(p.id, session.get('discord_locale')) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:9,代码来源:auth.py

示例3: is_taking

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def is_taking(cotc: Dict) -> bool:
    """检查当前用户是否选了这门课"""
    user_is_taking = False

    if session.get(SESSION_CURRENT_USER, None):
        # 检查当前用户是否选了这门课
        student = entity_service.get_student(session[SESSION_CURRENT_USER].identifier)
        for semester in sorted(student.semesters, reverse=True):  # 新学期可能性大,学期从新到旧查找
            timetable = entity_service.get_student_timetable(session[SESSION_CURRENT_USER].identifier, semester)
            for card in timetable.cards:
                if card.course_id == cotc["course_id"] and cotc["teacher_id_str"] == teacher_list_to_tid_str(
                        card.teachers):
                    user_is_taking = True
                    break
            if user_is_taking:
                break
    return user_is_taking 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:19,代码来源:views.py

示例4: show_review

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def show_review(cotc_id: int):
    """查看某个教学班的评价"""
    cotc_id = int(cotc_id)

    review_info = CourseReview.get_review(cotc_id)
    avg_rate = review_info['avg_rate']
    reviews = review_info['reviews']

    cotc = COTeachingClass.get_doc(cotc_id)
    if not cotc:
        return render_template('common/error.html', message=MSG_404)

    if session.get(SESSION_CURRENT_USER, None) \
            and CourseReview.get_my_review(cotc_id=cotc_id, student_id=session[SESSION_CURRENT_USER].identifier):
        reviewed_by_me = True
    else:
        reviewed_by_me = False
    return render_template('course/review.html',
                           cotc=cotc,
                           count=review_info['count'],
                           avg_rate=avg_rate,
                           reviews=reviews,
                           user_is_taking=is_taking(cotc),
                           reviewed_by_me=reviewed_by_me) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:26,代码来源:views.py

示例5: init_plugins

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def init_plugins():
        """初始化日志、错误追踪、打点插件"""
        from everyclass.rpc import init as init_rpc
        from everyclass.common.flask import print_config

        # Sentry
        if plugin_available("sentry"):
            sentry.init_app(app=__app)
            sentry_handler = SentryHandler(sentry.client)
            sentry_handler.setLevel(logging.WARNING)
            logging.getLogger().addHandler(sentry_handler)

            init_rpc(sentry=sentry)
            logger.info('Sentry is inited because you are in {} mode.'.format(__app.config['CONFIG_NAME']))

        # metrics
        global statsd
        statsd = DogStatsd(namespace=f"{__app.config['SERVICE_NAME']}.{os.environ.get('MODE').lower()}",
                           use_default_route=True)

        init_rpc(logger=logger)

        print_config(__app, logger) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:25,代码来源:__init__.py

示例6: login

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def login():
    """登录并获得token

    可能的错误码:
    4000 用户名或密码错误
    4100 用户不存在
    4101 密码错误
    """
    username = request.form.get("username")
    password = request.form.get("password")
    if not username:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请填写用户名")
    if not password:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请填写密码")

    if not user_service.check_password(username, password):
        raise exceptions.WrongPassword
    return generate_success_response({"token": user_service.issue_token(username)}) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:20,代码来源:views_api.py

示例7: email_verification_check

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def email_verification_check():
    """验证邮箱token

    错误码:
    4000 token缺失
    4102 用户已存在,token无效
    4103 token无效
    """
    # todo 这里发出去的邮箱里面的链接还是网页版的,要换一下

    email_token = request.args.get("token")
    if not email_token:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "token参数缺失")
    request_id = user_service.register_by_email_token_check(email_token)
    session[SESSION_EMAIL_VER_REQ_ID] = request_id
    return generate_success_response(None) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:18,代码来源:views_api.py

示例8: email_verification

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def email_verification():
    """邮件验证-设置密码

    错误码:
    4104 验证请求不存在(内部异常)
    4105 当前VerificationRequest的状态并非STATUS_TKN_PASSED(排除网络卡了导致客户端没收到响应其实已经注册成功的情况)
    4106 密码过弱
    """
    request_id = session.get(SESSION_EMAIL_VER_REQ_ID, None)
    if not request_id:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "无效请求,请重新点击邮件中的链接")

    password = request.form.get("password")
    if not password:
        return generate_error_response(None, api_helpers.STATUS_CODE_INVALID_REQUEST, "请输入密码")

    username = user_service.register_by_email_set_password(request_id, password)
    return generate_success_response({"token": user_service.issue_token(username)}) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:20,代码来源:views_api.py

示例9: register_by_password_status_refresh

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def register_by_password_status_refresh(request_id: str) -> Tuple[bool, str, Optional[str]]:
    """通过教务密码注册-刷新状态,返回是否成功、auth message及学号/教工号(如果成功)"""
    req = VerificationRequest.find_by_id(uuid.UUID(request_id))
    if not req:
        raise IdentityVerifyRequestNotFoundError
    if req.method != "password":
        logger.warn("Non-password verification request is trying get status from password interface")
        raise IdentityVerifyMethodNotExpectedError
    if req.method == VerificationRequest.STATUS_PWD_SUCCESS:
        raise RequestIDUsed("Request ID is used and password is set. It cannot be reused.")

    # fetch status from everyclass-auth
    with tracer.trace('get_result'):
        rpc_result = Auth.get_result(str(request_id))

    if rpc_result.success:  # 密码验证通过,设置请求状态并新增用户
        verification_req = VerificationRequest.find_by_id(uuid.UUID(request_id))
        verification_req.set_status_success()

        add_user(identifier=verification_req.identifier, password=verification_req.extra["password"], password_encrypted=True)

        return True, "SUCCESS", verification_req.identifier
    else:
        # 如果不是成功状态则返回auth服务返回的message
        return False, rpc_result.message, None 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:27,代码来源:service.py

示例10: get_visitors

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def get_visitors(identifier: str) -> List[Visitor]:
    result = visit_track.get_visitors(identifier)

    visitor_list = []
    for record in result:
        # query entity to get rich results
        # todo: entity add a multi GET interface to make this process faster when the list is long
        search_result = entity_service.search(record[0])
        if len(search_result.students) > 0:
            visitor_list.append(Visitor(name=search_result.students[0].name,
                                        user_type=USER_TYPE_STUDENT,
                                        identifier_encoded=search_result.students[0].student_id_encoded,
                                        last_semester=search_result.students[0].semesters[-1],
                                        visit_time=record[1]))
        elif len(search_result.teachers) > 0:
            visitor_list.append(Visitor(name=search_result.teachers[0].name,
                                        user_type=USER_TYPE_TEACHER,
                                        identifier_encoded=search_result.teachers[0].teacher_id_encoded,
                                        last_semester=search_result.teachers[0].semesters[-1],
                                        visit_time=record[1]))
    return visitor_list 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:23,代码来源:service.py

示例11: getlanguage

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def getlanguage():
    """Get the user language."""
    gval = g.get('language', None)
    if gval:
        return gval

    for lang in [
        request.form.get('uselang'),
        request.args.get('uselang'),
        session.get('language'),
        request.accept_languages.best,
    ]:
        if lang and _islang(lang):
            break
    else:
        lang = 'en'

    g.language = lang

    return lang 
开发者ID:toolforge,项目名称:video2commons,代码行数:22,代码来源:i18n.py

示例12: upload

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def upload() -> Response:
    error = validate_api_key()
    if error:
        return error
    match_id = int(request.form['match_id'])
    if match_id == 219603564:
        return return_json({'success': True}) # Prevent infinite 500 errors.
    if request.form.get('lines'):
        lines = request.form['lines']
        importing.import_log(lines.split('\n'), match_id)
    else:
        importing.import_from_pdbot(match_id)
    start_time = int(request.form['start_time_utc'])
    end_time = int(request.form['end_time_utc'])
    match.get_match(match_id).set_times(start_time, end_time)

    return return_json({'success': True}) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:19,代码来源:api.py

示例13: post_rule_update

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def post_rule_update(rule_id: int = None) -> Response:
    if rule_id is not None and request.form.get('include') is not None and request.form.get('exclude') is not None:
        inc = []
        exc = []
        for line in cast(str, request.form.get('include')).strip().splitlines():
            try:
                inc.append(parse_line(line))
            except InvalidDataException:
                return return_json({'success':False, 'msg':f"Couldn't find a card count and name on line: {line}"})
            if not cs.card_exists(inc[-1][1]):
                return return_json({'success':False, 'msg':f'Card not found in any deck: {line}'})
        for line in cast(str, request.form.get('exclude')).strip().splitlines():
            try:
                exc.append(parse_line(line))
            except InvalidDataException:
                return return_json({'success':False, 'msg':f"Couldn't find a card count and name on line: {line}"})
            if not cs.card_exists(exc[-1][1]):
                return return_json({'success':False, 'msg':f'Card not found in any deck {line}'})
        rs.update_cards(rule_id, inc, exc)
        return return_json({'success':True})
    return return_json({'success':False, 'msg':'Required keys not found'}) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:23,代码来源:api.py

示例14: person_status

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def person_status() -> Response:
    username = auth.mtgo_username()
    r = {
        'mtgo_username': username,
        'discord_id': auth.discord_id(),
        'admin': session.get('admin', False),
        'demimod': session.get('demimod', False),
        'hide_intro': request.cookies.get('hide_intro', False) or auth.hide_intro() or username or auth.discord_id(),
        'in_guild': session.get('in_guild', False),
        }
    if username:
        d = guarantee_at_most_one_or_retire(league.active_decks_by(username))
        if d is not None:
            r['deck'] = {'name': d.name, 'url': url_for('deck', deck_id=d.id), 'wins': d.get('wins', 0), 'losses': d.get('losses', 0)} # type: ignore
    if r['admin'] or r['demimod']:
        r['archetypes_to_tag'] = len(deck.load_decks('NOT d.reviewed'))
    active_league = league.active_league()
    if active_league:
        time_until_league_end = active_league.end_date - datetime.datetime.now(tz=datetime.timezone.utc)
        if time_until_league_end <= datetime.timedelta(days=2):
            r['league_end'] = dtutil.display_time(time_until_league_end/datetime.timedelta(seconds=1), granularity=2)
    return return_json(r) 
开发者ID:PennyDreadfulMTG,项目名称:Penny-Dreadful-Tools,代码行数:24,代码来源:api.py

示例15: web_console

# 需要导入模块: from flask import session [as 别名]
# 或者: from flask.session import get [as 别名]
def web_console():
    g = proc.Group()
    action=request.args.get('action')
    allow_action=['UpdateFile','UploadDir','Upload']
    if action not in allow_action:
        return make_response('error')
    if action in ['UploadDir','Upload']:
        local=urllib.unquote(request.args.get('local'))
        remote=urllib.unquote(request.args.get('remote'))
        user=urllib.unquote(request.args.get('user'))
        cmd=["python","-u",os.path.join(config_dir,'function.py'),action,local,remote,user]
    elif action=='UpdateFile':
        type_=request.args.get('type')
        cmd=["python","-u",os.path.join(config_dir,'function.py'),'UpdateFile',type_]
    else:
        cmd=["python","-u",os.path.join(config_dir,'function.py'),action]
    p = g.run(cmd)
    def read_process():
        while g.is_pending():
            lines = g.readlines()
            for proc, line in lines:
                yield "data:" + line + "\n\n"
        yield "data:end\n\n"
    resp=Response(read_process(), mimetype= 'text/event-stream')
    return resp 
开发者ID:abbeyokgo,项目名称:PyOne,代码行数:27,代码来源:base_view.py


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