How do I get the user agent with Flask?

前端 未结 5 659
轻奢々
轻奢々 2020-12-02 09:35

I\'m trying to get access to the user agent with Flask, but I either can\'t find the documentation on it, or it doesn\'t tell me.

5条回答
  •  时光取名叫无心
    2020-12-02 09:55

    The question begs for a lot more information. This library seems to fit the bill of collecting a lot of information out of flask, and has example calls to getting this information out of the application context.

    https://pythonhosted.org/Flask-Track-Usage/

    Usage gets stored in this format:

    [
        {
                'url': str,
                'user_agent': {
                    'browser': str,
                    'language': str,
                    'platform': str,
                    'version': str,
                },
                'blueprint': str,
                'view_args': dict or None
                'status': int,
                'remote_addr': str,
                'xforwardedfor': str,
                'authorization': bool
                'ip_info': str or None,
                'path': str,
                'speed': float,
                'date': datetime,
        },
        {
            ....
        }
    ]
    

    Here is one of the places in the library where the data is collected:

    https://github.com/ashcrow/flask-track-usage/blob/master/src/flask_track_usage/init.py around line 158

        data = {
            'url': ctx.request.url,
            'user_agent': ctx.request.user_agent,
            'server_name': ctx.app.name,
            'blueprint': ctx.request.blueprint,
            'view_args': ctx.request.view_args,
            'status': response.status_code,
            'remote_addr': ctx.request.remote_addr,
            'xforwardedfor': ctx.request.headers.get(
                'X-Forwarded-For', None),
            'authorization': bool(ctx.request.authorization),
            'ip_info': None,
            'path': ctx.request.path,
            'speed': float(speed),
            'date': int(time.mktime(current_time.timetuple())),
            'content_length': response.content_length,
            'request': "{} {} {}".format(
                ctx.request.method,
                ctx.request.url,
                ctx.request.environ.get('SERVER_PROTOCOL')
            ),
            'url_args': dict(
                [(k, ctx.request.args[k]) for k in ctx.request.args]
            ),
            'username': None,
            'track_var': g.track_var
        }
    

提交回复
热议问题