Python flask.request.is_xhr() Examples

The following are 13 code examples of flask.request.is_xhr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source File: response.py    From py-flask-jsontools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, response, status=None, headers=None, **kwargs):
        """ Init a JSON response
        :param response: Response data
        :type response: *
        :param status: Status code
        :type status: int|None
        :param headers: Additional headers
        :type headers: dict|None
        """
        # Store response
        self._response_data = self.preprocess_response_data(response)

        # PrettyPrint?
        try:
            indent = 2 if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr else None
        except RuntimeError:  # "RuntimeError: working outside of application context"
            indent = None

        # Init super
        super(JsonResponse, self).__init__(
            json.dumps(self._response_data, indent=indent),
            headers=headers, status=status, mimetype='application/json',
            direct_passthrough=True, **kwargs) 
Example #2
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def index():
    sysinfo = current_service.get_sysinfo()

    netifs = current_service.get_network_interfaces().values()
    netifs.sort(key=lambda x: x.get('bytes_sent'), reverse=True)

    data = {
        'load_avg': sysinfo['load_avg'],
        'num_cpus': sysinfo['num_cpus'],
        'memory': current_service.get_memory(),
        'swap': current_service.get_swap_space(),
        'disks': current_service.get_disks(),
        'cpu': current_service.get_cpu(),
        'users': current_service.get_users(),
        'net_interfaces': netifs,
        'page': 'overview',
        'is_xhr': request.is_xhr
    }

    return render_template('index.html', **data) 
Example #3
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def processes(sort='pid', order='asc', filter='user'):
    procs = current_service.get_process_list()
    num_procs = len(procs)

    user_procs = [p for p in procs if p['user'] != 'root']
    num_user_procs = len(user_procs)
    if filter == 'user':
        procs = user_procs

    procs.sort(
        key=lambda x: x.get(sort),
        reverse=True if order != 'asc' else False
    )

    return render_template(
        'processes.html',
        processes=procs,
        sort=sort,
        order=order,
        filter=filter,
        num_procs=num_procs,
        num_user_procs=num_user_procs,
        page='processes',
        is_xhr=request.is_xhr
    ) 
Example #4
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def view_log():
    filename = request.args['filename']
    seek_tail = request.args.get('seek_tail', '1') != '0'
    session_key = session.get('client_id')

    try:
        content = current_service.read_log(filename, session_key=session_key, seek_tail=seek_tail)
    except KeyError:
        error_msg = 'File not found. Only files passed through args are allowed.'
        if request.is_xhr:
            return error_msg
        return render_template('error.html', error=error_msg), 404

    if request.is_xhr:
        return content

    return render_template('log.html', content=content, filename=filename) 
Example #5
Source File: public.py    From platform with GNU General Public License v3.0 5 votes vote down vote up
def _callback():
    if request.is_xhr:
        return 'Unauthorised', 401
    else:
        return redirect('/login.html') 
Example #6
Source File: __init__.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def error_handler(e):
    try:
        if isinstance(e, HTTPException):
            status_code = e.code
            message = e.description if e.description != type(e).description else None
            tb = None
        else:
            status_code = httplib.INTERNAL_SERVER_ERROR
            message = None
            tb = traceback.format_exc() if current_user.admin else None

        if request.is_xhr or request.accept_mimetypes.best in ['application/json', 'text/javascript']:
            response = {
                'message': message,
                'traceback': tb
            }
        else:
            response = render_template('errors/error.html',
                                       title=httplib.responses[status_code],
                                       status_code=status_code,
                                       message=message,
                                       traceback=tb)
    except HTTPException as e2:
        return error_handler(e2)

    return response, status_code 
Example #7
Source File: 8. Other Data - request.headers & request.uri & etc.py    From --Awesome-Python-- with GNU General Public License v3.0 5 votes vote down vote up
def index():
    # request 객체에는 수많은 속성들이 존재한다
    # werkzeug.wrappers.BaseRequest에서 @cached_property나 @property로 처리된 프로퍼티들에 접근할 수 있다
    print(request.host, request.remote_addr)
    print(request.method, request.uri, request.full_url)
    print(request.headers)
    print(request.is_xhr)

    return 'hello' 
Example #8
Source File: web.py    From renrenBackup with MIT License 5 votes vote down vote up
def render_template(template_name, **kwargs):
    if request.is_xhr:
        return jsonify(success=1, **kwargs)

    return flask_render(template_name, **kwargs) 
Example #9
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def view_disks():
    disks = current_service.get_disks(all_partitions=True)
    io_counters = current_service.get_disks_counters().items()
    io_counters.sort(key=lambda x: x[1]['read_count'], reverse=True)
    return render_template(
        'disks.html',
        page='disks',
        disks=disks,
        io_counters=io_counters,
        is_xhr=request.is_xhr
    ) 
Example #10
Source File: application.py    From acmicpc.cc with MIT License 5 votes vote down vote up
def update_user():
    if request.is_xhr:
        user_id = request.args.get('id')
        update_profile(user_id)
        return "OK" 
    else:
        abort(404) 
Example #11
Source File: patch.py    From white with GNU General Public License v2.0 4 votes vote down vote up
def jsonify(value):
    """Creates a :class:`~flask.Response` with the JSON representation of
    the given arguments with an `application/json` mimetype.  The arguments
    to this function are the same as to the :class:`dict` constructor.

    Example usage::

        from flask import jsonify

        class User(object):
            def __json__(self):
                return dict(username=g.user.username,
                           email=g.user.email,
                           id=g.user.id)

        @app.route('/_get_current_user')
        def get_current_user():
            return jsonify(user)

    This will send a JSON response like this to the browser::

        {
            "username": "admin",
            "email": "admin@localhost",
            "id": 42
        }

    For security reasons only objects are supported toplevel.  For more
    information about this, have a look at :ref:`json-security`.

    This function's response will be pretty printed if it was not requested
    with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless
    the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.

    """
    indent = None
    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
            and not request.is_xhr:
        indent = 2
    return current_app.response_class(dumps(value,
                                            indent=indent),
                                      mimetype='application/json') 
Example #12
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def process(pid, section):
    valid_sections = [
        'overview',
        'threads',
        'files',
        'connections',
        'memory',
        'environment',
        'children',
        'limits'
    ]

    if section not in valid_sections:
        errmsg = 'Invalid subsection when trying to view process %d' % pid
        return render_template('error.html', error=errmsg), 404

    context = {
        'process': current_service.get_process(pid),
        'section': section,
        'page': 'processes',
        'is_xhr': request.is_xhr
    }

    if section == 'environment':
        penviron = current_service.get_process_environment(pid)

        whitelist = current_app.config.get('PSDASH_ENVIRON_WHITELIST')
        if whitelist:
            penviron = dict((k, v if k in whitelist else '*hidden by whitelist*') 
                             for k, v in penviron.iteritems())

        context['process_environ'] = penviron
    elif section == 'threads':
        context['threads'] = current_service.get_process_threads(pid)
    elif section == 'files':
        context['files'] = current_service.get_process_open_files(pid)
    elif section == 'connections':
        context['connections'] = current_service.get_process_connections(pid)
    elif section == 'memory':
        context['memory_maps'] = current_service.get_process_memory_maps(pid)
    elif section == 'children':
        context['children'] = current_service.get_process_children(pid)
    elif section == 'limits':
        context['limits'] = current_service.get_process_limits(pid)

    return render_template(
        'process/%s.html' % section,
        **context
    ) 
Example #13
Source File: web.py    From psdash with Creative Commons Zero v1.0 Universal 4 votes vote down vote up
def view_networks():
    netifs = current_service.get_network_interfaces().values()
    netifs.sort(key=lambda x: x.get('bytes_sent'), reverse=True)

    # {'key', 'default_value'}
    # An empty string means that no filtering will take place on that key
    form_keys = {
        'pid': '', 
        'family': socket_families[socket.AF_INET],
        'type': socket_types[socket.SOCK_STREAM],
        'state': 'LISTEN'
    }

    form_values = dict((k, request.args.get(k, default_val)) for k, default_val in form_keys.iteritems())

    for k in ('local_addr', 'remote_addr'):
        val = request.args.get(k, '')
        if ':' in val:
            host, port = val.rsplit(':', 1)
            form_values[k + '_host'] = host
            form_values[k + '_port'] = int(port)
        elif val:
            form_values[k + '_host'] = val

    conns = current_service.get_connections(form_values)
    conns.sort(key=lambda x: x['state'])

    states = [
        'ESTABLISHED', 'SYN_SENT', 'SYN_RECV',
        'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT',
        'CLOSE', 'CLOSE_WAIT', 'LAST_ACK',
        'LISTEN', 'CLOSING', 'NONE'
    ]

    return render_template(
        'network.html',
        page='network',
        network_interfaces=netifs,
        connections=conns,
        socket_families=socket_families,
        socket_types=socket_types,
        states=states,
        is_xhr=request.is_xhr,
        num_conns=len(conns),
        **form_values
    )