Python flask.json.loads() Examples

The following are 30 code examples of flask.json.loads(). 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: test_all.py    From cog with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_run_all_lotteries(app, admin):
    for _ in xrange(3):
        item = InventoryEntry('Item' + str(_), 'Wow lick my socks', 
            'http://test.co', 'Item', [], '', 3, item_type=ItemType.LOTTERY)        
        db.session.add(item)
        for _ in range(item.quantity +  3):
            request_item = RequestItem(item, 1)
            request = Request([request_item], admin.id, proposal='Test')
            db.session.add(request_item)
            db.session.add(request)
    db.session.commit()

    rv = app.post(url_for('run_all_lotteries'))

    assert json.loads(rv.data)['success'] == True 
    items = InventoryEntry.query.all()
    for item in items:
        assert RequestItem.query.filter_by(entry_id=item.id) \
                .join(Request).filter_by(status=RequestStatus.APPROVED).count() == 3 
Example #2
Source File: commands.py    From notifications-api with MIT License 7 votes vote down vote up
def get_letter_details_from_zips_sent_file(file_paths):
    """Get notification details from letters listed in zips_sent file(s)

    This takes one or more file paths for the zips_sent files in S3 as its parameters, for example:
    get-letter-details-from-zips-sent-file '2019-04-01/zips_sent/filename_1' '2019-04-01/zips_sent/filename_2'
    """

    rows_from_file = []

    for path in file_paths:
        file_contents = s3.get_s3_file(
            bucket_name=current_app.config['LETTERS_PDF_BUCKET_NAME'],
            file_location=path
        )
        rows_from_file.extend(json.loads(file_contents))

    notification_references = tuple(row[18:34] for row in rows_from_file)
    get_letters_data_from_references(notification_references) 
Example #3
Source File: test_receive_notification.py    From notifications-api with MIT License 6 votes vote down vote up
def test_receive_notification_returns_received_to_mmg(client, mocker, sample_service_full_permissions):
    mocked = mocker.patch("app.notifications.receive_notifications.tasks.send_inbound_sms_to_service.apply_async")
    prom_counter_labels_mock = mocker.patch('app.notifications.receive_notifications.INBOUND_SMS_COUNTER.labels')
    data = {
        "ID": "1234",
        "MSISDN": "447700900855",
        "Message": "Some message to notify",
        "Trigger": "Trigger?",
        "Number": sample_service_full_permissions.get_inbound_number(),
        "Channel": "SMS",
        "DateRecieved": "2012-06-27 12:33:00"
    }
    response = mmg_post(client, data)

    assert response.status_code == 200
    result = json.loads(response.get_data(as_text=True))
    assert result['status'] == 'ok'

    prom_counter_labels_mock.assert_called_once_with("mmg")
    prom_counter_labels_mock.return_value.inc.assert_called_once_with()

    inbound_sms_id = InboundSms.query.all()[0].id
    mocked.assert_called_once_with(
        [str(inbound_sms_id), str(sample_service_full_permissions.id)], queue="notify-internal-tasks") 
Example #4
Source File: server_test.py    From geofront with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_identity_403(fx_app, fx_token_store, fx_token_id):
    expires_at = (datetime.datetime.now(datetime.timezone.utc) +
                  datetime.timedelta(hours=1))
    fx_token_store.set(
        fx_token_id,
        Token(Identity(DummyTeam, 1, False), expires_at)
    )
    with fx_app.test_request_context():
        try:
            result = get_identity(fx_token_id)
        except HTTPException as e:
            response = e.get_response(request.environ)
            assert response.status_code == 403
            data = json.loads(response.get_data())
            assert data['error'] == 'not-authorized'
        else:
            fail('get_identity() does not raise HTTPException, but returns ' +
                 repr(result)) 
Example #5
Source File: server_test.py    From geofront with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_list_public_keys(fx_app, fx_key_store,
                          fx_authorized_identity,
                          fx_token_id):
    with fx_app.test_client() as c:
        response = c.get(get_url('list_public_keys', token_id=fx_token_id))
        assert response.status_code == 200
        assert response.mimetype == 'application/json'
        assert response.get_data() == b'{}'
    key = RSAKey.generate(1024)
    fx_key_store.register(fx_authorized_identity, key)
    with fx_app.test_client() as c:
        response = c.get(get_url('list_public_keys', token_id=fx_token_id))
        assert response.status_code == 200
        assert response.mimetype == 'application/json'
        data = {f: parse_openssh_pubkey(k)
                for f, k in json.loads(response.get_data()).items()}
        assert data == {get_key_fingerprint(key): key} 
Example #6
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_order_input_validation_string(self):
        data = dict(title="different text", order="not a number")
        response = self.app.post(url_for("index"),
                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["order"] + " is not an integer.", response_data["message"]) 
Example #7
Source File: test_notifications_ses_callback.py    From notifications-api with MIT License 5 votes vote down vote up
def test_process_ses_results_in_complaint_save_complaint_with_null_complaint_type(notify_api, sample_email_template):
    notification = create_notification(template=sample_email_template, reference='ref1')
    msg = json.loads(ses_complaint_callback_with_missing_complaint_type()['Message'])
    handle_complaint(msg)
    complaints = Complaint.query.all()
    assert len(complaints) == 1
    assert complaints[0].notification_id == notification.id
    assert not complaints[0].complaint_type 
Example #8
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_order_input_validation_float(self):
        data = dict(title="different text", order=23.3)
        response = self.app.post(url_for("index"),
                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(str(data["order"]) + " is not an integer.", response_data["message"]) 
Example #9
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_entry_returns_correct_entry(self):
        response = self.app.get(url_for("entry", entry_id=1))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(self.data["title"], response_data["title"]) 
Example #10
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_patching_entry_changes_title(self):
        data = dict(title="different text")
        self.app.patch(url_for("entry", entry_id=1),
                data=json.dumps(data), content_type="application/json")
        response = self.app.get(url_for("entry", entry_id=1))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(data["title"], response_data["title"]) 
Example #11
Source File: test_notifications_ses_callback.py    From notifications-api with MIT License 5 votes vote down vote up
def test_handle_complaint_does_not_raise_exception_if_reference_is_missing(notify_api):
    response = json.loads(ses_complaint_callback_malformed_message_id()['Message'])
    handle_complaint(response)
    assert len(Complaint.query.all()) == 0 
Example #12
Source File: test_jwt.py    From flask-jwt with MIT License 5 votes vote down vote up
def post_json(client, url, data):
    data = json.dumps(data)
    resp = client.post(url, headers={'Content-Type': 'application/json'}, data=data)
    return resp, json.loads(resp.data) 
Example #13
Source File: test_jwt.py    From flask-jwt with MIT License 5 votes vote down vote up
def assert_error_response(r, code, msg, desc):
    assert r.status_code == code
    jdata = json.loads(r.data)
    assert jdata['status_code'] == code
    assert jdata['error'] == msg
    assert jdata['description'] == desc 
Example #14
Source File: notifications_sms_callback.py    From notifications-api with MIT License 5 votes vote down vote up
def process_mmg_response():
    client_name = 'MMG'
    data = json.loads(request.data)
    errors = validate_callback_data(data=data,
                                    fields=['status', 'CID'],
                                    client_name=client_name)
    if errors:
        raise InvalidRequest(errors, status_code=400)

    status = str(data.get('status'))
    detailed_status_code = str(data.get('substatus'))

    provider_reference = data.get('CID')

    process_sms_client_response.apply_async(
        [status, provider_reference, client_name, detailed_status_code],
        queue=QueueNames.SMS_CALLBACKS,
    )

    safe_to_log = data.copy()
    safe_to_log.pop("MSISDN")
    current_app.logger.debug(
        f"Full delivery response from {client_name} for notification: {provider_reference}\n{safe_to_log}"
    )

    return jsonify(result='success'), 200 
Example #15
Source File: test_notifications_ses_callback.py    From notifications-api with MIT License 5 votes vote down vote up
def test_process_ses_results_in_complaint(sample_email_template):
    notification = create_notification(template=sample_email_template, reference='ref1')
    handle_complaint(json.loads(ses_complaint_callback()['Message']))
    complaints = Complaint.query.all()
    assert len(complaints) == 1
    assert complaints[0].notification_id == notification.id 
Example #16
Source File: test_notifications_ses_callback.py    From notifications-api with MIT License 5 votes vote down vote up
def test_process_ses_results_in_complaint_if_notification_does_not_exist(sample_email_template):
    notification = create_notification_history(template=sample_email_template, reference='ref1')
    handle_complaint(json.loads(ses_complaint_callback()['Message']))
    complaints = Complaint.query.all()
    assert len(complaints) == 1
    assert complaints[0].notification_id == notification.id 
Example #17
Source File: app-test.py    From learning-python with MIT License 5 votes vote down vote up
def test_delete_message(self):
        """Ensure the messages are being deleted"""
        rv = self.app.get('/delete/1')
        data = json.loads(rv.data)
        self.assertEqual(data['status'], 1) 
Example #18
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_with_order_have_correct_order_property(self):
        data = dict(title="different text", order=10)
        self.app.post(url_for("index"),
                data=json.dumps(data), content_type="application/json")
        response = self.app.get(url_for("entry", entry_id=1))
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(data["order"], response_data["order"]) 
Example #19
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_entries_have_proper_url(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(url_for("entry", entry_id=1, _external=True), response_data[0]["url"]) 
Example #20
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_entries_have_url_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("url", response_data[0]) 
Example #21
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_have_url_property(self):
        data = dict(title="different text")
        response = self.app.post(url_for("index"),
                data=json.dumps(data), content_type="application/json")
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertIn("url", response_data) 
Example #22
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_are_not_completed_get(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]["completed"], False) 
Example #23
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_new_entries_are_not_completed_post(self):
        data = dict(title="different text")
        response = self.app.post(url_for("index"),
                data=json.dumps(data), content_type="application/json")
        response_data = json.loads(response.data.decode("utf-8"))
        self.assertEqual(response_data["completed"], False) 
Example #24
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]) 
Example #25
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 #26
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 #27
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 #28
Source File: test_views.py    From todo-backend-flask with MIT License 5 votes vote down vote up
def test_index_returns_lists(self):
        response = self.app.get(url_for("index") )
        self.assertIsInstance(json.loads(response.data.decode("utf-8")), list) 
Example #29
Source File: test_openmoves.py    From openmoves with MIT License 5 votes vote down vote up
def _validate_response(self, response, tmpdir=None, code=200, check_content=True):
        if tmpdir:
            tmpdir.join("response.html").write(response.data, mode='wb')

        assert response.status_code == code, "HTTP status: %s" % response.status

        if response.data:
            response_data = response.data.decode('utf-8')

            if check_content:
                if response.mimetype == 'text/html':
                    self._validate_html5(response_data)
                elif response.mimetype == 'application/json':
                    return json.loads(response_data)
                else:
                    raise ValueError("illegal mimetype: '%s'" % response.mimetype)

            return response_data 
Example #30
Source File: meta.py    From white with GNU General Public License v2.0 5 votes vote down vote up
def load(self, data):
        data = list(data)
        try:
            data[3] = loads(data[3])
        except:
            data[3] = dict()
        return BaseMapper.load(self, data, self.model)