Python flask.request 模块,user_agent() 实例源码

我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用flask.request.user_agent()

项目:flask-api-skeleton    作者:ianunruh    | 项目源码 | 文件源码
def create_session(data):
    user = User.find_by_email_or_username(data['username'])
    if not (user and user.password == data['password']):
        return make_error_response('Invalid username/password combination', 401)

    session = Session(user=user)

    # TODO can this be made more accurate?
    session.ip_address = request.remote_addr

    if request.user_agent:
        session.user_agent = request.user_agent.string
        # Denormalize user agent
        session.platform = request.user_agent.platform
        session.browser = request.user_agent.browser

    db.session.add(session)
    db.session.commit()

    return session
项目:zmirror    作者:aploium    | 项目源码 | 文件源码
def ip_whitelist_add(ip_to_allow, info_record_dict=None):
    """??ip????, ?????"""
    if ip_to_allow in single_ip_allowed_set:
        return
    dbgprint('ip white added', ip_to_allow, 'info:', info_record_dict)
    single_ip_allowed_set.add(ip_to_allow)
    is_ip_not_in_allow_range.cache_clear()
    append_ip_whitelist_file(ip_to_allow)
    # dbgprint(single_ip_allowed_set)
    try:
        with open(zmirror_root(human_ip_verification_whitelist_log), 'a', encoding='utf-8') as fp:
            fp.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + " " + ip_to_allow
                     + " " + str(request.user_agent)
                     + " " + repr(info_record_dict) + "\n")
    except:  # coverage: exclude
        errprint('Unable to write log file', os.path.abspath(human_ip_verification_whitelist_log))
        traceback.print_exc()
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def _is_msie8or9():
    """Returns ``True`` if and only if the user agent of the client making the
    request indicates that it is Microsoft Internet Explorer 8 or 9.

    .. note::

       We have no way of knowing if the user agent is lying, so we just make
       our best guess based on the information provided.

    """
    # request.user_agent.version comes as a string, so we have to parse it
    version = lambda ua: tuple(int(d) for d in ua.version.split('.'))
    return (request.user_agent is not None
            and request.user_agent.version is not None
            and request.user_agent.browser == 'msie'
            and (8, 0) <= version(request.user_agent) < (10, 0))
项目:apropos_web    作者:abhinav-upadhyay    | 项目源码 | 文件源码
def dist_index(dist):
    netbsd_logo_url = url_for('static', filename='images/netbsd.png')
    if dist is None or dist == '':
        dist = 'NetBSD-current'
    if dist not in config.DB_PATHS and dist != 'favicon.ico':
        return redirect(url_for('search'))
    ip = request.remote_addr
    user_agent = request.user_agent
    platform = user_agent.platform
    browser = user_agent.browser
    version = user_agent.version
    language = user_agent.language
    referrer = request.referrer
    dblogger.log_page_visit(1, ip, platform, browser, version, language, referrer,
                            int(time.time()), user_agent.string, dist)
    return render_template('index.html',
                           netbsd_logo_url=netbsd_logo_url, distnames=distnames)
项目:zou    作者:cgwire    | 项目源码 | 文件源码
def is_from_browser(user_agent):
    return user_agent.browser in [
        "camino",
        "chrome",
        "firefox",
        "galeon",
        "kmeleon",
        "konqueror",
        "links",
        "lynx",
        "msie",
        "msn",
        "netscape",
        "opera",
        "safari",
        "seamonkey",
        "webkit"
    ]
项目:zou    作者:cgwire    | 项目源码 | 文件源码
def get(self):
        try:
            current_token = get_raw_jwt()
            jti = current_token['jti']
            auth_service.revoke_tokens(app, jti)
            identity_changed.send(
                current_app._get_current_object(),
                identity=AnonymousIdentity()
            )
        except KeyError:
            return {
                "Access token not found."
            }, 500

        logout_data = {
            "logout": True
        }

        if is_from_browser(request.user_agent):
            response = jsonify(logout_data)
            unset_jwt_cookies(response)
            return response
        else:
            return logout_data
项目:zou    作者:cgwire    | 项目源码 | 文件源码
def get(self):
        email = get_jwt_identity()
        access_token = create_access_token(identity=email)
        auth_service.register_tokens(app, access_token)
        if is_from_browser(request.user_agent):
            response = jsonify({'refresh': True})
            set_access_cookies(response, access_token)
        else:
            return {
                "access_token": access_token
            }
项目:SynDBB    作者:D2K5    | 项目源码 | 文件源码
def after_request(response):
        timestamp = strftime('%Y-%b-%d %H:%M:%S')
        useragent = request.user_agent
        logger.info('[%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s]',
            timestamp, request.remote_addr, useragent, request.method,
            request.scheme, request.full_path, response.status, request.referrer)
        return response
项目:zmirror    作者:aploium    | 项目源码 | 文件源码
def filter_client_request():
    """??????, ??????????
    :rtype: Union[Response, None]
    """
    dbgprint('Client Request Url: ', request.url)

    # crossdomain.xml
    if os.path.basename(request.path) == 'crossdomain.xml':
        dbgprint('crossdomain.xml hit from', request.url)
        return crossdomain_xml()

    # Global whitelist ua
    if check_global_ua_pass(str(request.user_agent)):
        return None

    if is_deny_spiders_by_403 and is_denied_because_of_spider(str(request.user_agent)):
        return generate_simple_resp_page(b'Spiders Are Not Allowed To This Site', 403)

    if human_ip_verification_enabled and (
                ((human_ip_verification_whitelist_from_cookies or enable_custom_access_cookie_generate_and_verify)
                 and must_verify_cookies)
            or is_ip_not_in_allow_range(request.remote_addr)
    ):
        dbgprint('ip', request.remote_addr, 'is verifying cookies')
        if 'zmirror_verify' in request.cookies and \
                ((human_ip_verification_whitelist_from_cookies and verify_ip_hash_cookie(request.cookies.get('zmirror_verify')))
                 or (enable_custom_access_cookie_generate_and_verify and custom_verify_access_cookie(
                        request.cookies.get('zmirror_verify'), request))):
            ip_whitelist_add(request.remote_addr, info_record_dict=request.cookies.get('zmirror_verify'))
            dbgprint('add to ip_whitelist because cookies:', request.remote_addr)
        else:
            return redirect(
                "/ip_ban_verify_page?origin=" + base64.urlsafe_b64encode(str(request.url).encode(encoding='utf-8')).decode(
                    encoding='utf-8'),
                code=302)

    return None
项目:InfoSub    作者:CoderHito    | 项目源码 | 文件源码
def create_app(config_name):
    if config_name not in app_config:
        raise ConfigError("{} is a wrong config name.".format(config_name))
    app = Flask(__name__)
    app.config.from_object(app_config[config_name])

    from app.user import user_blueprint
    from app.information import info_blueprint
    from app.view import view_blueprint
    app.register_blueprint(user_blueprint)
    app.register_blueprint(info_blueprint)
    app.register_blueprint(view_blueprint)

    from app.extensions import display_plan_type, display_play, display_user, tracer_config
    jinja_env = app.jinja_env
    jinja_env.filters['plan_type'] = display_plan_type
    jinja_env.filters['plan_name'] = display_play
    jinja_env.filters['user_type'] = display_user

    db.init_app(app)
    tool_bar.init_app(app)
    login_manager.init_app(app)
    admin.init_app(app)
    if app.config.get("TRACER"):
        tracer_config.initialize_tracer()

    @app.before_request
    def init_tracer():
        import opentracing
        from app.extensions import tracer_config
        span = opentracing.tracer.start_span(str(request.url))
        span.set_tag('user_agent', request.user_agent)
        span.log_event("request args", payload=dict(args=request.args, form=request.form))
        g.tracer_span = span

    @app.after_request
    def close_tracer(response):
        if g.tracer_span:
            g.tracer_span.finish()
        return response

    return app
项目:zou    作者:cgwire    | 项目源码 | 文件源码
def post(self):
        (email, password) = self.get_arguments()
        try:
            user = auth_service.check_auth(app, email, password)
            access_token = create_access_token(identity=user["email"])
            refresh_token = create_refresh_token(identity=user["email"])
            auth_service.register_tokens(app, access_token, refresh_token)
            identity_changed.send(
                current_app._get_current_object(),
                identity=Identity(user["id"])
            )

            if is_from_browser(request.user_agent):
                response = jsonify({
                    "user": user,
                    "login": True
                })
                set_access_cookies(response, access_token)
                set_refresh_cookies(response, refresh_token)

            else:
                response = {
                    "login": True,
                    "user": user,
                    "access_token": access_token,
                    "refresh_token": refresh_token
                }

            return response
        except PersonNotFoundException:
            current_app.logger.info("User is not registered.")
            return {"login": False}, 400
        except WrongUserException:
            current_app.logger.info("User is not registered.")
            return {"login": False}, 400
        except WrongPasswordException:
            current_app.logger.info("User gave a wrong password.")
            return {"login": False}, 400
        except NoAuthStrategyConfigured:
            current_app.logger.info(
                "Authentication strategy is not properly configured."
            )
            return {"login": False}, 400
        except UnactiveUserException:
            return {
                "error": True,
                "message": "User is unactive, he cannot log in."
            }, 400