Python flask.json() Examples

The following are 30 code examples of flask.json(). 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 , or try the search function .
Example #1
Source File: testing.py    From py-flask-jsontools with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def open(self, path, json=None, **kwargs):
        """ Open an URL, optionally posting JSON data
        :param path: URI to request
        :type path: str
        :param json: JSON data to post
        :param method: HTTP Method to use. 'POST' by default if data is provided
        :param data: Custom data to post, if required
        """
        # Prepare request
        if json:
            kwargs['data'] = flask.json.dumps(json)
            kwargs['content_type'] = 'application/json'
            kwargs.setdefault('method', 'POST')

        # Request
        rv = super(FlaskJsonClient, self).open(path, **kwargs)
        ':type rv: flask.Response'

        # Response: JSON?
        if rv.mimetype == 'application/json':
            response = flask.json.loads(rv.get_data())
            return JsonResponse(response, rv.status_code, rv.headers)
        return rv 
Example #2
Source File: result.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def dump_result(project, _format):
    resultdb = app.config['resultdb']
    # force update project list
    resultdb.get(project, 'any')
    if project not in resultdb.projects:
        return "no such project.", 404

    offset = int(request.args.get('offset', 0)) or None
    limit = int(request.args.get('limit', 0)) or None
    results = resultdb.select(project, offset=offset, limit=limit)

    if _format == 'json':
        valid = request.args.get('style', 'rows') == 'full'
        return Response(result_dump.dump_as_json(results, valid),
                        mimetype='application/json')
    elif _format == 'txt':
        return Response(result_dump.dump_as_txt(results),
                        mimetype='text/plain')
    elif _format == 'csv':
        return Response(result_dump.dump_as_csv(results),
                        mimetype='text/csv') 
Example #3
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def create_developer():
    if not request.json or not 'platform_id' in request.json:
        abort(400)
    developer = Developer.query.filter_by(platform_id=request.json['platform_id'],
                                          platform=request.json['platform']).first()
    if 'desc' in request.json:
        desc = request.json['desc']
    else:
        desc = ''
    if developer is None:
        dev_key = generate_dev_key()
        developer = Developer(dev_key=dev_key,
                              platform=request.json['platform'],
                              platform_id=request.json['platform_id'],
                              username=request.json['dev_name'],
                              email=request.json['email'],
                              description=desc)
        developer.insert_to_db()
        return jsonify({'dev_key': developer.dev_key}), 201
    else:
        return jsonify({'created': False}), 304


# 通过 platform 和 platform_id 来获取用户信息 
Example #4
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modify_developer(dev_key):
    developer = Developer.query.filter_by(dev_key=dev_key).first()
    if developer is None:
        abort(404)
    if 'name' in request.json:
        developer.username = request.json['name']
    if 'desc' in request.json:
        developer.description = request.json['desc']
    if 'avatar' in request.json:
        developer.avatar = request.json['avatar']
    if 'email' in request.json:
        developer.email = request.json['email']
    db.session.add(developer)
    try:
        db.session.commit()
        return jsonify({'modified': True}), 200
    except:
        db.session.rollback()
        abort(500)


# 在dev_key 下创建一个 channel 
Example #5
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def create_channel(dev_key):
    if not request.json or not 'channel' in request.json:
        abort(400)
    developer = Developer.query.filter_by(dev_key=dev_key).first()
    if developer is None:
        abort(404)
    channels = developer.channels
    if channels is None:
        create_channel_and_insert2db(developer, request.json['channel'])
    else:
        for channel in channels:
            if channel.channel == request.json['channel']:
                print("existed")
                return jsonify({'created': False, 'existed': True}), 304
        create_channel_and_insert2db(developer, request.json['channel'])
    return jsonify({'created': True, 'existed': False}), 201


# 获得 dev_key 下的所有 channel 
Example #6
Source File: developers.py    From jbox with MIT License 6 votes vote down vote up
def modificate_integration(dev_key, integration_id):
    if not request.json or not 'channel' in request.json:
        abort(400)
    developer = get_developer_with_devkey(dev_key)
    integration = Integration.query.filter_by(developer_id=developer.id, integration_id=integration_id).first()
    if integration is None:
        abort(400)
    integration.channel.channel = request.json['channel']
    if 'name' in request.json:
        integration.name = request.json['name']
    if 'description' in request.json:
        integration.description = request.json['description']
    if 'icon' in request.json:
        integration.icon = request.json['icon']
    db.session.add(integration)
    try:
        db.session.commit()
    except:
        db.session.rollback()
        abort(500)
    return jsonify({'modification': True}), 200


# 保存 github 集成,将所选的仓库与之前的仓库比较,新增则生成 webhook, 否则去掉之前的 webhook 
Example #7
Source File: __init__.py    From Flask-SocketIO with MIT License 6 votes vote down vote up
def on_event(self, message, handler, namespace=None):
        """Register a SocketIO event handler.

        ``on_event`` is the non-decorator version of ``'on'``.

        Example::

            def on_foo_event(json):
                print('received json: ' + str(json))

            socketio.on_event('my event', on_foo_event, namespace='/chat')

        :param message: The name of the event. This is normally a user defined
                        string, but a few event names are already defined. Use
                        ``'message'`` to define a handler that takes a string
                        payload, ``'json'`` to define a handler that takes a
                        JSON blob payload, ``'connect'`` or ``'disconnect'``
                        to create handlers for connection and disconnection
                        events.
        :param handler: The function that handles the event.
        :param namespace: The namespace on which the handler is to be
                          registered. Defaults to the global namespace.
        """
        self.on(message, namespace=namespace)(handler) 
Example #8
Source File: generic.py    From ceph-lcm with Apache License 2.0 6 votes vote down vote up
def dispatch_request(self, *args, **kwargs):
        response = super().dispatch_request(*args, **kwargs)

        if isinstance(response, flask.Response):
            return response

        try:
            response = self.prepare_response(response)
        except Exception as exc:
            LOG.error("Cannot build model response: %s", exc)
            raise exceptions.UnknownReturnValueError from exc

        try:
            response = flask.json.jsonify(response)
        except Exception as exc:
            LOG.error("Cannot convert %s to JSON: %s", response, exc)
            raise exceptions.CannotConvertResultToJSONError() from exc

        return response 
Example #9
Source File: hook.py    From mattermost-jira-info with GNU General Public License v2.0 5 votes vote down vote up
def send_message_back( payload ):
    resp = Response(
		json.dumps( payload ),
        status=200,
        mimetype='application/json')
    return resp 
Example #10
Source File: test_builds_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_wscan_builds(self):
        """Test case for project_wscan_builds

        Get all the weekly scan builds info for given project
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tag/{desired_tag}/wscan-builds'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example', desired_tag='desired_tag_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #11
Source File: exceptions.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def get_body(self, environ=None):
        error = self.error_name or self.__class__.__name__
        error = str(error)

        error_message = {
            "code": self.code,
            "error": error,
            "message": self.get_description(environ)
        }
        json_error = flask.json.dumps(error_message)

        return json_error 
Example #12
Source File: exceptions.py    From ceph-lcm with Apache License 2.0 5 votes vote down vote up
def get_headers(self, environ=None):
        return [("Content-Type", "application/json")] 
Example #13
Source File: test_infra_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_liveness(self):
        """Test case for liveness

        Get the liveness of API service
        """
        response = self.client.open(
            '/api/v1//liveness',
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #14
Source File: test_meta_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_namespace_projects(self):
        """Test case for namespace_projects

        Get all the projects in given namespace
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/projects'.format(namespace='namespace_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #15
Source File: test_meta_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_namespaces(self):
        """Test case for namespaces

        Get all available namespaces accessible over APIs
        """
        response = self.client.open(
            '/api/v1//namespaces',
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #16
Source File: test_projects_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_desired_tags(self):
        """Test case for project_desired_tags

        Get tags for given $app_id/$job_id with build status and image
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tags'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #17
Source File: test_projects_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_metadata(self):
        """Test case for project_metadata

        Get the metadata of the given project
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tag/{desired_tag}/metadata'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example', desired_tag='desired_tag_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #18
Source File: test_builds_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_build_logs(self):
        """Test case for project_build_logs

        Build logs for given build number
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tag/{desired_tag}/build/{build}/logs'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example', desired_tag='desired_tag_example', build='build_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #19
Source File: test_builds_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_builds(self):
        """Test case for project_builds

        Get all the builds info for given project
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tag'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example', desired_tag='desired_tag_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #20
Source File: test_builds_controller.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
def test_project_wscan_build_logs(self):
        """Test case for project_wscan_build_logs

        Weekly scan logs for given wscan-build number
        """
        response = self.client.open(
            '/api/v1//namespace/{namespace}/app-id/{app_id}/job-id/{job_id}/desired-tag/{desired_tag}/wscan-build/{build}/logs'.format(namespace='namespace_example', app_id='app_id_example', job_id='job_id_example', desired_tag='desired_tag_example', build='build_example'),
            method='GET',
            content_type='application/json')
        self.assert200(response,
                       'Response body is : ' + response.data.decode('utf-8')) 
Example #21
Source File: __init__.py    From Flask-SocketIO with MIT License 5 votes vote down vote up
def send(self, data, json=False, namespace=None, room=None,
             callback=None, include_self=True, skip_sid=None, **kwargs):
        """Send a server-generated SocketIO message.

        This function sends a simple SocketIO message to one or more connected
        clients. The message can be a string or a JSON blob. This is a simpler
        version of ``emit()``, which should be preferred. This function can be
        used outside of a SocketIO event context, so it is appropriate to use
        when the server is the originator of an event.

        :param data: The message to send, either a string or a JSON blob.
        :param json: ``True`` if ``message`` is a JSON blob, ``False``
                     otherwise.
        :param namespace: The namespace under which the message is to be sent.
                          Defaults to the global namespace.
        :param room: Send the message only to the users in the given room. If
                     this parameter is not included, the message is sent to
                     all connected users.
        :param include_self: ``True`` to include the sender when broadcasting
                             or addressing a room, or ``False`` to send to
                             everyone but the sender.
        :param skip_sid: The session id of a client to ignore when broadcasting
                         or addressing a room. This is typically set to the
                         originator of the message, so that everyone except
                         that client receive the message. To skip multiple sids
                         pass a list.
        :param callback: If given, this function will be called to acknowledge
                         that the client has received the message. The
                         arguments that will be passed to the function are
                         those provided by the client. Callback functions can
                         only be used when addressing an individual client.
        """
        skip_sid = flask.request.sid if not include_self else skip_sid
        if json:
            self.emit('json', data, namespace=namespace, room=room,
                      skip_sid=skip_sid, callback=callback, **kwargs)
        else:
            self.emit('message', data, namespace=namespace, room=room,
                      skip_sid=skip_sid, callback=callback, **kwargs) 
Example #22
Source File: __init__.py    From Flask-SocketIO with MIT License 5 votes vote down vote up
def on(self, message, namespace=None):
        """Decorator to register a SocketIO event handler.

        This decorator must be applied to SocketIO event handlers. Example::

            @socketio.on('my event', namespace='/chat')
            def handle_my_custom_event(json):
                print('received json: ' + str(json))

        :param message: The name of the event. This is normally a user defined
                        string, but a few event names are already defined. Use
                        ``'message'`` to define a handler that takes a string
                        payload, ``'json'`` to define a handler that takes a
                        JSON blob payload, ``'connect'`` or ``'disconnect'``
                        to create handlers for connection and disconnection
                        events.
        :param namespace: The namespace on which the handler is to be
                          registered. Defaults to the global namespace.
        """
        namespace = namespace or '/'

        def decorator(handler):
            @wraps(handler)
            def _handler(sid, *args):
                return self._handle_event(handler, message, namespace, sid,
                                          *args)

            if self.server:
                self.server.on(message, _handler, namespace=namespace)
            else:
                self.handlers.append((message, _handler, namespace))
            return handler
        return decorator 
Example #23
Source File: __init__.py    From webhook-shims with Apache License 2.0 5 votes vote down vote up
def callapi(url, method='post', payload=None, headers=None, auth=None, check=True):
    """
    Simple wrapper around `requests.post`, with excessive logging.
    Returns a Flask-friendly tuple on success or failure.
    Logs and re-raises any exceptions.
    """
    if not headers:
        headers = {'Content-type': 'application/json'}
    try:
        logging.info("URL=%s" % url)
        logging.info("Auth=%s" % str(auth))
        logging.info("Headers=%s" % headers)
        logging.info("Body=%s" % payload)
        logging.info("Check=%s" % check)
        if (auth is not None):
            r = requests.request(method, url, auth=auth, headers=headers, data=payload, verify=bool(strtobool(str(check))))
        else:
            r = requests.request(method, url, headers=headers, data=payload, verify=check)
        if r.status_code >= 200 and r.status_code < 300:
            if (payload is None):
                return r.text
            else:
                return ("OK", r.status_code, None)
    except:
        logging.exception("Can't create new payload. Check code and try again.")
        raise
    return ("%s" % r.text, r.status_code, None) 
Example #24
Source File: response.py    From assembly with MIT License 5 votes vote down vote up
def json(func):
    """
    Decorator to render as JSON
    :param func:
    :return:
    """
    if inspect.isclass(func):
        apply_function_to_members(func, json)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, jsonify)
        return decorated_view 
Example #25
Source File: patch.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def patch_flask():
    flask.json.jsonify = jsonify
    flask.jsonify = flask.json.jsonify
    Flask.json_encoder = JSONEncoder 
Example #26
Source File: spam.py    From lrrbot with Apache License 2.0 5 votes vote down vote up
def spam_redirects(session):
	redirects = await common.url.canonical_url(flask.request.values["url"].strip())
	return flask.json.jsonify(redirects=redirects, csrf_token=server.app.csrf_token()) 
Example #27
Source File: spam.py    From lrrbot with Apache License 2.0 5 votes vote down vote up
def spam_submit(session):
	link_spam = "link_spam" in flask.request.values
	data = flask.json.loads(flask.request.values['data'])

	# Validation checks
	error = verify_rules(data)
	if error:
		return flask.json.jsonify(error=error, csrf_token=server.app.csrf_token())

	if link_spam:
		await common.rpc.bot.link_spam.modify_link_spam_rules(data)
	else:
		await common.rpc.bot.spam.modify_spam_rules(data)
	history.store("link_spam" if link_spam else "spam", session['user']['id'], data)
	return flask.json.jsonify(success='OK', csrf_token=server.app.csrf_token()) 
Example #28
Source File: commands.py    From lrrbot with Apache License 2.0 5 votes vote down vote up
def commands_submit(session):
	data = flask.json.loads(flask.request.values['data'])
	# Server-side sanity checking
	for command, response_data in data.items():
		if not isinstance(command, str):
			raise ValueError("Key is not a string")
		if command == '':
			raise ValueError("Command is blank")
		if not isinstance(response_data, dict):
			raise ValueError("Response data is not a dict")
		if set(response_data.keys()) != set(('response', 'access')):
			raise ValueError("Incorrect keys for response_data")
		if not isinstance(response_data['response'], (tuple, list)):
			response_data['response'] = [response_data['response']]
		for response in response_data['response']:
			if not isinstance(response, str):
				raise ValueError("Value is not a string or list of strings")
			if response == '':
				raise ValueError("Response is blank")
			if not utils.check_length(response):
				raise ValueError("Response is too long")
		if len(response_data['response']) == 1:
			response_data['response'] = response_data['response'][0]
		if response_data['access'] not in ('any', 'sub', 'mod'):
			raise ValueError("Invalid access level")
	await common.rpc.bot.static.modify_commands(data)
	history.store('responses', session['user']['id'], data)
	return flask.json.jsonify(success='OK', csrf_token=server.app.csrf_token()) 
Example #29
Source File: result.py    From pyspider with Apache License 2.0 5 votes vote down vote up
def result():
    resultdb = app.config['resultdb']
    project = request.args.get('project')
    offset = int(request.args.get('offset', 0))
    limit = int(request.args.get('limit', 20))

    count = resultdb.count(project)
    results = list(resultdb.select(project, offset=offset, limit=limit))

    return render_template(
        "result.html", count=count, results=results,
        result_formater=result_dump.result_formater,
        project=project, offset=offset, limit=limit, json=json
    ) 
Example #30
Source File: __init__.py    From Flask-SocketIO with MIT License 4 votes vote down vote up
def send(message, **kwargs):
    """Send a SocketIO message.

    This function sends a simple SocketIO message to one or more connected
    clients. The message can be a string or a JSON blob. This is a simpler
    version of ``emit()``, which should be preferred. This is a function that
    can only be called from a SocketIO event handler.

    :param message: The message to send, either a string or a JSON blob.
    :param json: ``True`` if ``message`` is a JSON blob, ``False``
                     otherwise.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      An empty string can be used to use the global namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all connected clients, or
                      ``False`` to only reply to the sender of the originating
                      event.
    :param room: Send the message to all the users in the given room.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    :param skip_sid: The session id of a client to ignore when broadcasting
                     or addressing a room. This is typically set to the
                     originator of the message, so that everyone except
                     that client receive the message. To skip multiple sids
                     pass a list.
    :param ignore_queue: Only used when a message queue is configured. If
                         set to ``True``, the event is emitted to the
                         clients directly, without going through the queue.
                         This is more efficient, but only works when a
                         single server process is used, or when there is a
                         single addressee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    """
    json = kwargs.get('json', False)
    if 'namespace' in kwargs:
        namespace = kwargs['namespace']
    else:
        namespace = flask.request.namespace
    callback = kwargs.get('callback')
    broadcast = kwargs.get('broadcast')
    room = kwargs.get('room')
    if room is None and not broadcast:
        room = flask.request.sid
    include_self = kwargs.get('include_self', True)
    skip_sid = kwargs.get('skip_sid')
    ignore_queue = kwargs.get('ignore_queue', False)

    socketio = flask.current_app.extensions['socketio']
    return socketio.send(message, json=json, namespace=namespace, room=room,
                         include_self=include_self, skip_sid=skip_sid,
                         callback=callback, ignore_queue=ignore_queue)