Python flask.json.dumps() Examples

The following are 30 code examples of flask.json.dumps(). 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.json , or try the search function .
Example #1
Source File: demo1.py    From Python24 with MIT License 7 votes vote down vote up
def demo4():

    json_dict = {
        'name': 'zhangsan',
        'age': 18

    }

    # 使用falsk.json包下的dumps方法把一个字典对象转换为json格式的字符串
    json_str = json.dumps(json_dict)

    # 使用laod方法把json格式的字符串转换为一个字典对象
    # dict_obj = json.load('{ "name": "zhangsan","age": 18}')

    # json.dunps返回的json字符串在浏览器中Content-type是text/html
    # 但是使用jsonify来处理字典对象的话返回的也是str,但是浏览器的content-type就变成了application/json
    return jsonify(json_dict)


# 直接使用redirect函数进行重定向
# 重定向的反向解析:使用重定向路由的视图函数名字url_for(XXX),并且携带参数 
Example #2
Source File: run.py    From Portfolio-compute with Apache License 2.0 6 votes vote down vote up
def get_unit_test_portfolios():
    '''
    Returns the available user portfolio names in the Investment Portfolio service.
    Uses type='user_portfolio' to specify.
    '''
    portfolio_names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','unit test portfolio')
    try:
        for portfolios in res['portfolios']:
            portfolio_names.append(portfolios['name'])
        #returns the portfolio names as list
        print("Portfolio_names:" + str(portfolio_names))
        return json.dumps(portfolio_names)
    except:
        return "No portfolios found."

#Deletes all unit test holdings and portfolios for cleanup 
Example #3
Source File: etag.py    From flask-smorest with MIT License 6 votes vote down vote up
def _generate_etag(etag_data, etag_schema=None, extra_data=None):
        """Generate an ETag from data

        etag_data: Data to use to compute ETag
        etag_schema: Schema to dump data with before hashing
        extra_data: Extra data to add before hashing

        Typically, extra_data is used to add pagination metadata to the hash.
        It is not dumped through the Schema.
        """
        if etag_schema is None:
            raw_data = etag_data
        else:
            if isinstance(etag_schema, type):
                etag_schema = etag_schema()
            raw_data = etag_schema.dump(etag_data)
            if MARSHMALLOW_VERSION_MAJOR < 3:
                raw_data = raw_data.data
        if extra_data:
            raw_data = (raw_data, extra_data)
        # flask's json.dumps is needed here
        # as vanilla json.dumps chokes on lazy_strings
        data = json.dumps(raw_data, sort_keys=True)
        return hashlib.sha1(bytes(data, 'utf-8')).hexdigest() 
Example #4
Source File: skill_settings.py    From selene-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, skill_family_name):
        """Process an HTTP GET request"""
        self._authenticate()
        self.family_settings = self.setting_repository.get_family_settings(
            self.account.id,
            skill_family_name
        )
        self._parse_selection_options()
        response_data = self._build_response_data()

        # The response object is manually built here to bypass the
        # camel case conversion so settings are displayed correctly
        return Response(
            response=json.dumps(response_data),
            status=HTTPStatus.OK,
            content_type='application/json'
        ) 
Example #5
Source File: response.py    From flask-assistant with Apache License 2.0 6 votes vote down vote up
def _set_user_storage(self):
        from flask_assistant.core import user

        # If empty or unspecified,
        # the existing persisted token will be unchanged.
        user_storage = user.get("userStorage")
        if user_storage is None:
            return

        if isinstance(user_storage, dict):
            user_storage = json.dumps(user_storage)

        if len(user_storage.encode("utf-8")) > 10000:
            raise ValueError("UserStorage must not exceed 10k bytes")

        self._response["payload"]["google"]["userStorage"] = user_storage 
Example #6
Source File: app.py    From dataiku-contrib with Apache License 2.0 6 votes vote down vote up
def register_graph():
    digraph = request.args.get('digraph')
    dataset = request.args.get('dataset')
    treatment_name = request.args.get('treatment')
    outcome_name = request.args.get('outcome')
    df = dataiku.Dataset(dataset).get_dataframe()

    model = CausalModel(
        data=df,
        treatment=treatment_name,
        outcome=outcome_name,
        graph=digraph,
    )

    identified_estimand = model.identify_effect()
    causal_estimate_reg = model.estimate_effect(identified_estimand,
                                                method_name="backdoor.linear_regression",
                                                test_significance=True)

    d = {'results': str(causal_estimate_reg)}

    return json.dumps(d) 
Example #7
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 #8
Source File: __init__.py    From beavy with Mozilla Public License 2.0 6 votes vote down vote up
def api_only(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        accepted = set(request.accept_mimetypes.values())
        explicit = not(not request.args.get("json", False))
        if not (accepted & API_MIMETYPES) and not explicit:
            return abort(415, "Unsupported Media Type")

        resp = fn(*args, **kwargs)
        if not isinstance(resp, ResponseBase):
            data, code, headers = unpack(resp)
            # we've found one, return json
            if isinstance(data, MarshalResult):
                data = data.data
            resp = make_response(json.dumps(data,
                                            indent=explicit and 4 or 0),
                                 code)

            if headers:
                resp.headers.update(headers)
            resp.headers["Content-Type"] = 'application/json'
        return resp
    return wrapped 
Example #9
Source File: index.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def counter():
    rpc = app.config['scheduler_rpc']
    if rpc is None:
        return json.dumps({})

    result = {}
    try:
        data = rpc.webui_update()
        for type, counters in iteritems(data['counter']):
            for project, counter in iteritems(counters):
                result.setdefault(project, {})[type] = counter
        for project, paused in iteritems(data['pause_status']):
            result.setdefault(project, {})['paused'] = paused
    except socket.error as e:
        app.logger.warning('connect to scheduler rpc error: %r', e)
        return json.dumps({}), 200, {'Content-Type': 'application/json'}

    return json.dumps(result), 200, {'Content-Type': 'application/json'} 
Example #10
Source File: task.py    From pyspider with Apache License 2.0 6 votes vote down vote up
def active_tasks():
    rpc = app.config['scheduler_rpc']
    taskdb = app.config['taskdb']
    project = request.args.get('project', "")
    limit = int(request.args.get('limit', 100))

    try:
        tasks = rpc.get_active_tasks(project, limit)
    except socket.error as e:
        app.logger.warning('connect to scheduler rpc error: %r', e)
        return '{}', 502, {'Content-Type': 'application/json'}

    result = []
    for updatetime, task in tasks:
        task['updatetime'] = updatetime
        task['updatetime_text'] = utils.format_date(updatetime)
        if 'status' in task:
            task['status_text'] = taskdb.status_to_string(task['status'])
        result.append(task)

    return json.dumps(result), 200, {'Content-Type': 'application/json'} 
Example #11
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_returns_entry(self):
        data = dict(title="some other text")
        response = self.app.post(url_for("index"),
                data=json.dumps(data), content_type="application/json")
        self.assertEqual(data["title"], json.loads(response.data)["title"]) 
Example #12
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_entry_allows_patching_title(self):
        data = dict(title="different text")
        response = self.app.patch(url_for("entry", entry_id=1),
                data=json.dumps(data), content_type="application/json")
        self.assertEqual(response.status_code, 200) 
Example #13
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_saves_posted_data(self):
        data = dict(title="different text")
        self.app.post(url_for("index"), data=json.dumps(data), content_type="application/json")
        response = self.app.get(url_for("index"))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(response_data[0]["title"], data["title"]) 
Example #14
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_deletes_all_entries_after_delete(self):
        data1 = dict(title="different text")
        self.app.post(url_for("index"), data=json.dumps(data1), content_type="application/json")
        data2 = dict(title="some different text")
        self.app.post(url_for("index"), data=json.dumps(data2), content_type="application/json")
        data3 = dict(title="more different text")
        self.app.post(url_for("index"), data=json.dumps(data3), content_type="application/json")
        self.app.delete(url_for("index"))
        response = self.app.get(url_for("index"))
        self.assertEqual(response.data.decode("utf-8"), "[]") 
Example #15
Source File: index.py    From pyspider with Apache License 2.0 5 votes vote down vote up
def get_queues():
    def try_get_qsize(queue):
        if queue is None:
            return 'None'
        try:
            return queue.qsize()
        except Exception as e:
            return "%r" % e

    result = {}
    queues = app.config.get('queues', {})
    for key in queues:
        result[key] = try_get_qsize(queues[key])
    return json.dumps(result), 200, {'Content-Type': 'application/json'} 
Example #16
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_returns_multiple_entries_properly_formatted(self):
        data1 = dict(title="different text")
        self.app.post(url_for("index"), data=json.dumps(data1), content_type="application/json")
        data2 = dict(title="some different text")
        self.app.post(url_for("index"), data=json.dumps(data2), content_type="application/json")
        data3 = dict(title="more different text")
        self.app.post(url_for("index"), data=json.dumps(data3), content_type="application/json")
        response = self.app.get(url_for("index"))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(response_data[0]["title"], data1["title"])
        self.assertEqual(response_data[1]["title"], data2["title"])
        self.assertEqual(response_data[2]["title"], data3["title"]) 
Example #17
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def setUp(self):
        BaseTestCase.setUp(self)
        self.data = dict(title="text", order=10)
        self.app.post(url_for("index"),
                data=json.dumps(self.data), content_type="application/json") 
Example #18
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_patching_completed_input_validation_string(self):
        data = dict(completed="not a bool")
        response = self.app.patch(url_for("entry", entry_id=1),
                data=json.dumps(data), content_type="application/json")
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(response.status_code, 400)
        self.assertEqual(data["completed"] + " is not a boolean.", response_data["message"]) 
Example #19
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_allows_posts(self):
        data = dict(title="some text")
        response = self.app.post(url_for("index"),
                data=json.dumps(data), content_type="application/json")
        self.assertEqual(response.status_code, 200) 
Example #20
Source File: openmoves.py    From openmoves with MIT License 5 votes vote down vote up
def import_strava(activity_id):
    move = strava.strava_import(current_user, activity_id)
    data = {'move_id': move.id}
    return Response(json.dumps(data), mimetype='application/json') 
Example #21
Source File: openmoves.py    From openmoves with MIT License 5 votes vote down vote up
def activity_types():
    activities = db.session.query(Move.activity).group_by(Move.activity).order_by(Move.activity.asc())
    data = [{'value': activity, 'text': activity} for activity, in activities]
    return Response(json.dumps(data), mimetype='application/json') 
Example #22
Source File: response.py    From hobbit-core with MIT License 5 votes vote down vote up
def __init__(self, response=None, status=None, headers=None,
                 mimetype='application/json', content_type=None,
                 direct_passthrough=False):
        assert sorted(response.keys()) == ['code', 'detail', 'message'], \
            'Error response, must include keys: code, detail, message'
        super(Result, self).__init__(
            response=dumps(response, indent=0, separators=(',', ':')) + '\n',
            status=status or self.status, headers=headers, mimetype=mimetype,
            content_type=content_type, direct_passthrough=direct_passthrough) 
Example #23
Source File: response.py    From assembly with MIT License 5 votes vote down vote up
def dumps(o, **kw):
    kw["cls"] = _JSONEnc
    return flask_dumps(o, **kw) 
Example #24
Source File: decorators.py    From learning-python with MIT License 5 votes vote down vote up
def jsonify(func):
    """JSON decorator."""

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        r = func(*args, **kwargs)
        if isinstance(r, tuple):
            code, data = r
        else:
            code, data = 200, r
        return Response(json.dumps(data), status=code, mimetype='application/json')

    return wrapper 
Example #25
Source File: extend.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def create(self, extend):
        """Create a new extend"""
        attributes = dumps(extend.attributes)
        return db.execute('INSERT INTO extend (`type`, `label`, `field`, `key`, `attributes`) VALUES (%s, %s, %s, %s, %s)',
                (extend.type, extend.label, extend.field, extend.key, attributes)) 
Example #26
Source File: meta.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def save(self, meta):
        data = dumps(meta.data)
        return (db.update(self.table).mset(
            dict(node_id=meta.node_id,
                 type=meta.type,
                 extend=meta.extend,
                 data=data)).condition('mid', meta.mid).execute()) 
Example #27
Source File: meta.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def create(self, meta):
        data = dumps(meta.data)
        return (db.insert(self.table).fields('node_id', 'type', 'extend', 'data')
                .values((meta.node_id, meta.type, meta.extend, data)).execute()) 
Example #28
Source File: storage.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def update_site_meta(self, sitename, description, site_page,
                         posts_per_page, auto_published_comments,  comment_moderation_keys):

        meta = self.site_meta()
        config = meta.json_value()

        try:
            sitename = sitename or sitename.strip()
            if sitename:
                config['sitename'] = sitename

            description = description or description.strip()
            if description:
                config['description'] = description

            site_page = int(site_page)
            if site_page >= 0:
                config['site_page'] = site_page

            posts_per_page = int(posts_per_page)
            if posts_per_page:
                config['posts_per_page'] = posts_per_page

            auto_published_comments = bool(auto_published_comments)
            config['auto_published_comments'] = auto_published_comments
            if comment_moderation_keys is not None:
                keys = [key.strip() for key in re.split(' +', comment_moderation_keys) if key.strip()]
                config['comment_moderation_keys'] = keys
            meta.value = dumps(config)
            self.pair_repo.update(meta)
            return True
        except:
            return False 
Example #29
Source File: chronograph_http.py    From openprocurement.auction with Apache License 2.0 5 votes vote down vote up
def shutdown():
    if chronograph_webapp.chronograph.scheduler.running:
        spawn(chronograph_webapp.chronograph.scheduler.shutdown, True)
    return dumps('Start shutdown') 
Example #30
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_entries_contain_completed_property(self):
        data = dict(title="different text")
        self.app.post(url_for("index"), data=json.dumps(data), content_type="application/json")
        response = self.app.get(url_for("index"))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertIn("completed", response_data[0])