Python flask.json.loads() Examples

The following are code examples for showing how to use flask.json.loads(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: jenca-authentication   Author: bimlauncher   File: authentication.py    MIT License 6 votes vote down vote up
def load_user_from_id(user_id):
    """
    Flask-Login ``user_loader`` callback.

    The ``user_id`` was stored in the session environment by Flask-Login.
    user_loader stores the returned ``User`` object in ``current_user`` during
    every flask request.

    See https://flask-login.readthedocs.org/en/latest/#flask.ext.login.LoginManager.user_loader.  # noqa

    :param user_id: The ID of the user Flask is trying to load.
    :type user_id: string
    :return: The user which has the email address ``user_id`` or ``None`` if
        there is no such user.
    :rtype: ``User`` or ``None``.
    """
    url = urljoin(STORAGE_URL, 'users/{email}').format(email=user_id)
    response = requests.get(url, headers={'Content-Type': 'application/json'})

    if response.status_code == codes.OK:
        details = json.loads(response.text)
        return User(
            email=details['email'],
            password_hash=details['password_hash'],
        ) 
Example 2
Project: jenca-authentication   Author: bimlauncher   File: authentication.py    MIT License 6 votes vote down vote up
def load_user_from_token(auth_token):
    """
    Flask-Login token-loader callback.

    See https://flask-login.readthedocs.org/en/latest/#flask.ext.login.LoginManager.token_loader  # noqa

    :param auth_token: The authentication token of the user Flask is trying to
        load.
    :type user_id: string
    :return: The user which has the given authentication token or ``None`` if
        there is no such user.
    :rtype: ``User`` or ``None``.
    """
    response = requests.get(
        urljoin(STORAGE_URL, '/users'),
        headers={'Content-Type': 'application/json'},
    )

    for details in json.loads(response.text):
        user = User(
            email=details['email'],
            password_hash=details['password_hash'],
        )
        if user.get_auth_token() == auth_token:
            return user 
Example 3
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 6 votes vote down vote up
def get_user_portfolio_list():
    '''
    Returns the available user portfolio names in the Investment Portfolio service.
    Uses type='user_portfolio' to specify.
    '''
    names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','user_portfolio')
    p = json.loads(json.dumps(res))
    try:
        for a in p['portfolios']:
            names.append(a['name'])
        #Gather only unique names, as there's likely history for the benchmarks.
        names = list(set(names))
        return names
    except:
        return names 
Example 4
Project: Portfolio-Optimize   Author: IBM   File: run.py    Apache License 2.0 6 votes vote down vote up
def get_benchmark_list():
    '''
    Returns the available benchmark portfolio names in the Investment Portfolio service.
    Uses type='bechmark' to specify.
    '''
    names = []
    res = investmentportfolio.Get_Portfolios_by_Selector('type','benchmark')
    p = json.loads(json.dumps(res))
    try:
        for b in p['portfolios']:
            names.append(b['name'])
        #Gather only unique names, as there's likely history for the benchmarks.
        names = list(set(names))
        return names
    except:
        return names 
Example 5
Project: track-scanner   Author: skyderby   File: test_api_v1.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def track_test(self, filename, start, deploy):
        resp = self.app.post(
            '/api/v1/scan',
            data=self.request_data(filename)
        )

        data = json.loads(resp.data)

        expected_start = date_parser.parse(start)
        actual_start = date_parser.parse(data['flight_starts_at'])

        expected_deploy = date_parser.parse(deploy)
        actual_deploy = date_parser.parse(data['deploy_at'])

        self.assertAlmostEqual(expected_start,
                               actual_start,
                               delta=timedelta(seconds=3))
        self.assertAlmostEqual(expected_deploy,
                               actual_deploy,
                               delta=timedelta(seconds=3)) 
Example 6
Project: selene-backend   Author: MycroftAI   File: device.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _validate_request(self):
        request_data = json.loads(self.request.data)
        if self.request.method == 'POST':
            device = NewDeviceRequest()
            device.pairing_code = request_data['pairingCode']
        else:
            device = UpdateDeviceRequest()
        device.city = request_data['city']
        device.country = request_data['country']
        device.name = request_data['name']
        device.placement = request_data['placement']
        device.region = request_data['region']
        device.timezone = request_data['timezone']
        device.wake_word = request_data['wakeWord']
        device.voice = request_data['voice']
        device.validate()

        return device 
Example 7
Project: vibe   Author: 3ll3d00d   File: measurement.py    MIT License 6 votes vote down vote up
def put(self, measurementId, deviceId):
        """
        Store a bunch of data for this measurement session.
        :param measurementId:
        :param deviceId:
        :return:
        """
        data = request.get_json()
        if data is not None:
            parsedData = json.loads(data)
            logger.debug('Received payload ' + measurementId + '/' + deviceId + ': ' +
                         str(len(parsedData)) + ' records')
            if self._measurementController.recordData(measurementId, deviceId, parsedData):
                return None, 200
            else:
                logger.warning('Unable to record payload ' + measurementId + '/' + deviceId)
                return None, 404
        else:
            logger.error('Invalid data payload received ' + measurementId + '/' + deviceId)
            return None, 400 
Example 8
Project: vibe   Author: 3ll3d00d   File: measurement.py    MIT License 6 votes vote down vote up
def put(self, measurementId, deviceId):
        """
        Fails the measurement for this device.
        :param measurementId: the measurement name.
        :param deviceId: the device name.
        :return: 200 if
        """
        payload = request.get_json()
        failureReason = json.loads(payload).get('failureReason') if payload is not None else None
        logger.warning('Failing measurement ' + measurementId + ' for ' + deviceId + ' because ' + str(failureReason))
        if self._measurementController.failMeasurement(measurementId, deviceId, failureReason=failureReason):
            logger.warning('Failed measurement ' + measurementId + ' for ' + deviceId)
            return None, 200
        else:
            logger.error('Unable to fail measurement ' + measurementId + ' for ' + deviceId)
            return None, 404 
Example 9
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 6 votes vote down vote up
def report_ignition_version(filename):
    """
    Ignition version
    Report the current ignition behind matchbox
    ---
    tags:
      - matchbox
    responses:
      200:
        description: Status of the recorded entry
        schema:
            type: dict
    """
    versions = CACHE.get("ignition-version")
    if not versions:
        versions = dict()

    new_entry = False if filename in versions.keys() else True
    data = json.loads(request.data)
    versions.update({filename: data[filename]})
    CACHE.set("ignition-version", versions, timeout=0)
    return jsonify({"new": new_entry, "total": len(versions)}) 
Example 10
Project: geno-browser   Author: mbiokyle29   File: test_files.py    MIT License 6 votes vote down vote up
def testUploadFasta(self):
        LOG.info("Testing upload of fasta file to endpoint /files with POST")
        test_dir = os.path.dirname(os.path.abspath(__file__))

        # first create a user
        self.createTestUser()

        response = self.app.post('/api/files',
            data=dict(
                file=(open(test_dir+"/../var/B958-short.fasta", 'rb'), 'test.fasta'),
                type="fasta"
            ), 
            follow_redirects=True,
            headers=self.user_header
        )

        self.assert200(response)
        self.assertEqual(json.loads(response.get_data()).get('track_id'),1) 
Example 11
Project: geno-browser   Author: mbiokyle29   File: test_files.py    MIT License 6 votes vote down vote up
def testUploadWig(self):
        LOG.info("Testing upload of wig file to endpoint /files with POST")
        test_dir = os.path.dirname(os.path.abspath(__file__))

        # first create a user
        self.createTestUser()

        response = self.app.post('/api/files',
            data=dict(
                file=(open(test_dir+"/../var/shortWig.wig", 'rb'), 'test.wig'),
                type="wig"
            ), 
            follow_redirects=True,
            headers=self.user_header
        )

        self.assert200(response)
        self.assertEqual(json.loads(response.get_data()).get('track_ids'),[1,2,3,4]) 
Example 12
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 6 votes vote down vote up
def testGetView(self):
        LOG.info("Testing getting view endpoint /views with GET")
        self.createTestUser()
        self.uploadTestWig()
        self.createTestTrack()
        self.createTestView()

        response = self.app.get('/api/views/1',
            headers=self.user_header
        )
        self.assert200(response)
        
        data = json.loads(response.get_data())
        self.assertEqual(data.get('view_name'), 'TEST-VIEW')
        self.assertEqual(data.get('user_id'), 1)
        self.assertEqual(data.get('track_ids'), [1]) 
Example 13
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 6 votes vote down vote up
def testGetDataView(self):
        LOG.info("Testing getting view endpoint /views/data with GET")
        self.createTestUser()
        self.uploadTestWig()
        self.createTestTrack()
        self.createTestView()

        response = self.app.get('/api/views/data/1',
            headers=self.user_header
        )
        self.assert200(response)
        
        data = json.loads(response.get_data())
        self.assertEqual(data.get('view_name'), 'TEST-VIEW')
        self.assertEqual(data.get('user_id'), 1)
        self.assertTrue(data.has_key('view_tracks')) 
Example 14
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 6 votes vote down vote up
def testCreateView(self):
        LOG.info("Testing create view endpoint /views with POST")

        # first create a user
        self.createTestUser()
        self.uploadTestWig()
        self.createTestTrack()

        # Send post request
        response = self.app.post('/api/views', 
            data=json.dumps({
                'track_ids': [1], 
                'view_name': 'TEST-VIEW'
            }), 
            content_type='application/json',
            headers=self.user_header)

        self.assert200(response)
        self.assertEqual(json.loads(response.get_data()).get('view_id'),1) 
Example 15
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 6 votes vote down vote up
def testDeleteView(self):
        LOG.info("Testing delet view endpoint /views with DELETE")
        self.createTestUser()
        self.uploadTestWig()
        self.createTestTrack()
        self.createTestView()

        # delete it
        response = self.app.delete('/api/views/1',
            headers=self.user_header
        )

        # ensure delete happened correctly
        self.assert200(response)
        data = json.loads(response.get_data())
        self.assertEqual(data, {})

        # last make sure it is actually gone
        response = self.app.get('/api/views/1',
            headers=self.user_header
        )

        self.assert404(response) 
Example 16
Project: geno-browser   Author: mbiokyle29   File: test_tracks.py    MIT License 6 votes vote down vote up
def testCreateTrack(self):
        LOG.info("Testing create track endpoint /tracks with POST")

        # first create a user
        self.createTestUser()

        # Send post request
        response = self.app.post('/api/tracks', 
            data=json.dumps({
                'track_name': 'kyles track', 
                'data_type': 'wig',
                'data_id':1,
                'file_name':'mywig.wig'
            }), 
            content_type='application/json',
            headers=self.user_header)

        self.assert200(response)
        self.assertEqual(json.loads(response.get_data()).get('track_id'),1) 
Example 17
Project: geno-browser   Author: mbiokyle29   File: test_tracks.py    MIT License 6 votes vote down vote up
def testGetTrack(self):
        LOG.info("Testing track endpoint /tracks/<track_id> with GET")

        # Helper to create a user + track (has already been tested above)
        self.createTestUser()
        self.createTestTrack()

        # Check the user json returned
        response = self.app.get('/api/tracks/1',headers=self.user_header)
        self.assert200(response)

        # Make sure the user dict has the right fields
        track = json.loads(response.get_data())
        self.assertDictContainsSubset({
                'track_id' : 1,
                'track_name':'kyles track',
                'data_type':'wig',
                'data_id':1,
                'user_id':1,
                'file_name':'mywig.wig'
            },
            track
        ) 
Example 18
Project: geno-browser   Author: mbiokyle29   File: test_tracks.py    MIT License 6 votes vote down vote up
def testPutTrack(self):
        LOG.info("Testing track endoint /api/tracks/<track_id> with PUT")
        self.createTestUser()
        self.createTestTrack()
        track = self.getTestTrack()
        track['track_name'] = "New_TRACK_NAME"

        # Handle put request
        updated_json = json.dumps(track)
        response = self.app.put('/api/tracks/'+str(track.get('track_id')), 
           data=updated_json, 
           content_type='application/json',
           headers=self.user_header
        )
        self.assert200(response)

        # Check that PUT response matches request data
        json_up = json.loads(response.get_data())
        self.assertEqual(track,json_up)

        # Check that changes are still there when we GET
        track_refresh = self.getTestTrack()
        self.assertEqual(track_refresh,json_up) 
Example 19
Project: geno-browser   Author: mbiokyle29   File: test_users.py    MIT License 6 votes vote down vote up
def testPutUser(self):
        LOG.info("Testing user endoint /api/users/ with PUT")
        self.createTestUser()
        user = self.get_user()

        #Don't change the name because then I need to base64 encode <user:pass> again
        user['email'] = "[email protected]"

        # Handle put request
        updated_json = json.dumps(user)
        response = self.app.put('/api/users/', 
            headers=[('Authorization','Bearer ' + self.token)],
            data=updated_json, 
            content_type='application/json')
        self.assert200(response)
        
        # Check that PUT response matches request data
        json_up = json.loads(response.get_data())
        self.assertEqual(user,json_up)

        # Check that changes are still there when we GET
        user_refresh = self.get_user()
        self.assertEqual(user_refresh,json_up) 
Example 20
Project: zesje   Author: zesje   File: test_exams.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_exams(test_client, add_test_data):
    mc_option_1 = {
        'x': 100,
        'y': 40,
        'problem_id': 1,
        'page': 1,
        'label': 'a',
        'name': 'test'
    }
    test_client.put('/api/mult-choice/', data=mc_option_1)

    mc_option_2 = {
        'x': 100,
        'y': 40,
        'problem_id': 1,
        'page': 1,
        'label': 'a',
        'name': 'test'
    }
    test_client.put('/api/mult-choice/', data=mc_option_2)

    response = test_client.get('/api/exams/1')
    data = json.loads(response.data)

    assert len(data['problems'][0]['mc_options']) == 2 
Example 21
Project: zesje   Author: zesje   File: test_feedback.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_delete_with_mc_option(test_client, add_test_data):
    """
    Attempt to delete a FeedbackOption related to a MultipleChoiceOption
    """
    req = mco_json()

    result = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(result.data)

    assert data['feedback_id']

    fb_id = data['feedback_id']
    problem_id = 1  # Was inserted in add_test_data()

    result = test_client.delete(f'/api/feedback/{problem_id}/{fb_id}')
    data = json.loads(result.data)

    assert data['status'] == 401 
Example 22
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_add_get(test_client, add_test_data):
    req = mco_json()

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)

    assert data['mult_choice_id']

    id = data['mult_choice_id']

    result = test_client.get(f'/api/mult-choice/{id}')
    data = json.loads(result.data)

    exp_resp = {
        'id': 2,
        'name': 'test',
        'x': 100,
        'y': 40,
        'type': 'mcq_widget',
        'feedback_id': 1,
        'label': 'a',
    }

    assert exp_resp == data 
Example 23
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_patch(test_client, add_test_data):
    req = mco_json()

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)

    assert data['mult_choice_id']

    id = data['mult_choice_id']

    req2 = {
        'x': 120,
        'y': 50,
        'problem_id': 4,
        'page': 1,
        'label': 'b',
        'name': 'test'
    }

    result = test_client.patch(f'/api/mult-choice/{id}', data=req2)
    data = json.loads(result.data)

    assert data['status'] == 200 
Example 24
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_delete_problem_check_mco(test_client, add_test_data):
    req = mco_json()
    problem_id = req['problem_id']

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)
    mult_choice_id = data['mult_choice_id']

    # Delete problem
    test_client.delete(f'/api/problems/{problem_id}')

    # Get mult choice option
    response = test_client.get(f'/api/mult-choice/{mult_choice_id}')
    data = json.loads(response.data)

    assert data['status'] == 404 
Example 25
Project: LOST   Author: kylemh   File: api.py    MIT License 5 votes vote down vote up
def revoke_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])
        print('This is the api_req', api_req)

        # If http request is missing a parameter...
        if 'username' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameter(s)'})
            return error_result

        # All parameters present in request.
        username = api_req['username']

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = helpers.db_query(matching_user, [username])

        # If user exists in database, deactivate user; otherwise, return "User Not Found" API Error.
        if user_does_exist:
            deactivate_existing_user = ("UPDATE users SET active = FALSE "
                                        "WHERE username = %s")
            helpers.db_change(deactivate_existing_user, [username])

            data = json.dumps({'result': 'OK'})
            return data
        else:
            error_result = json.dumps({'result': 'Error: User Not Found'})
            return error_result 
Example 26
Project: LOST   Author: kylemh   File: api.py    MIT License 5 votes vote down vote up
def revoke_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])
        print('This is the api_req', api_req)

        # If http request is missing a parameter...
        if 'username' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameter(s)'})
            return error_result


        # All parameters present in request.
        username = api_req['username']

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = db_query(matching_user, [username])

        # If user exists in database, deactivate user; otherwise, return "User Not Found" API Error.
        if user_does_exist:
            deactivate_existing_user = ("UPDATE users SET active = FALSE "
                                        "WHERE username = %s")
            db_change(deactivate_existing_user, [username])

            data = json.dumps({'result': 'OK'})
            return data
        else:
            error_result = json.dumps({'result': 'Error: User Not Found'})
            return error_result 
Example 27
Project: hdxscraper-world-bank-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def get_num_results(self, table):
        r = self.get_data(table)
        loaded = loads(r.data)
        return loaded['num_results'] 
Example 28
Project: hdxscraper-world-bank-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def get_type(self, table, id=1):
        r = self.get_data(table, id)
        loaded = loads(r.data)
        return loaded['type']['id'] 
Example 29
Project: Health-Checker   Author: KriAga   File: wrappers.py    MIT License 5 votes vote down vote up
def get_json(self, force=False, silent=False, cache=True):
        """Parse and return the data as JSON. If the mimetype does not
        indicate JSON (:mimetype:`application/json`, see
        :meth:`is_json`), this returns ``None`` unless ``force`` is
        true. If parsing fails, :meth:`on_json_loading_failed` is called
        and its return value is used as the return value.

        :param force: Ignore the mimetype and always try to parse JSON.
        :param silent: Silence parsing errors and return ``None``
            instead.
        :param cache: Store the parsed JSON to return for subsequent
            calls.
        """
        if cache and self._cached_json[silent] is not Ellipsis:
            return self._cached_json[silent]

        if not (force or self.is_json):
            return None

        data = self._get_data_for_json(cache=cache)

        try:
            rv = json.loads(data)
        except ValueError as e:
            if silent:
                rv = None
                if cache:
                    normal_rv, _ = self._cached_json
                    self._cached_json = (normal_rv, rv)
            else:
                rv = self.on_json_loading_failed(e)
                if cache:
                    _, silent_rv = self._cached_json
                    self._cached_json = (rv, silent_rv)
        else:
            if cache:
                self._cached_json = (rv, rv)

        return rv 
Example 30
Project: Health-Checker   Author: KriAga   File: tag.py    MIT License 5 votes vote down vote up
def loads(self, value):
        """Load data from a JSON string and deserialized any tagged objects."""
        return loads(value, object_hook=self.untag) 
Example 31
Project: recruit   Author: Frank-qlu   File: wrappers.py    Apache License 2.0 5 votes vote down vote up
def get_json(self, force=False, silent=False, cache=True):
        """Parse and return the data as JSON. If the mimetype does not
        indicate JSON (:mimetype:`application/json`, see
        :meth:`is_json`), this returns ``None`` unless ``force`` is
        true. If parsing fails, :meth:`on_json_loading_failed` is called
        and its return value is used as the return value.

        :param force: Ignore the mimetype and always try to parse JSON.
        :param silent: Silence parsing errors and return ``None``
            instead.
        :param cache: Store the parsed JSON to return for subsequent
            calls.
        """
        if cache and self._cached_json[silent] is not Ellipsis:
            return self._cached_json[silent]

        if not (force or self.is_json):
            return None

        data = self._get_data_for_json(cache=cache)

        try:
            rv = json.loads(data)
        except ValueError as e:
            if silent:
                rv = None
                if cache:
                    normal_rv, _ = self._cached_json
                    self._cached_json = (normal_rv, rv)
            else:
                rv = self.on_json_loading_failed(e)
                if cache:
                    _, silent_rv = self._cached_json
                    self._cached_json = (rv, silent_rv)
        else:
            if cache:
                self._cached_json = (rv, rv)

        return rv 
Example 32
Project: recruit   Author: Frank-qlu   File: tag.py    Apache License 2.0 5 votes vote down vote up
def loads(self, value):
        """Load data from a JSON string and deserialized any tagged objects."""
        return loads(value, object_hook=self.untag) 
Example 33
Project: track-scanner   Author: skyderby   File: test_api_v1.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_no_flight_data(self):
        with open('tests/fixtures/flysight_warmup.csv') as f:
            request_data = f.read()

        resp = self.app.post('/api/v1/scan', data=request_data)
        data = json.loads(resp.data)
        expected = {'error': 'no flight data'}

        self.assertEqual(422, resp.status_code)
        self.assertEqual(expected, data) 
Example 34
Project: flask-graphql-rest   Author: biosustain   File: utils.py    MIT License 5 votes vote down vote up
def json(self):
        return json.loads(self.data) 
Example 35
Project: oa_qian   Author: sunqb   File: views.py    Apache License 2.0 5 votes vote down vote up
def get(self):
        """Returns the result of evaluating the SQL functions specified in the
        body of the request.

        For a description of the request and response formats, see
        :ref:`functionevaluation`.

        """
        if 'q' not in request.args or not request.args.get('q'):
            return dict(message='Empty query parameter'), 400
        # if parsing JSON fails, return a 400 error in JSON format
        try:
            data = json.loads(str(request.args.get('q'))) or {}
        except (TypeError, ValueError, OverflowError) as exception:
            current_app.logger.exception(str(exception))
            return dict(message='Unable to decode data'), 400
        try:
            result = evaluate_functions(self.session, self.model,
                                        data.get('functions', []))
            if not result:
                return {}, 204
            return result
        except AttributeError as exception:
            current_app.logger.exception(str(exception))
            message = 'No such field "{0}"'.format(exception.field)
            return dict(message=message), 400
        except OperationalError as exception:
            current_app.logger.exception(str(exception))
            message = 'No such function "{0}"'.format(exception.function)
            return dict(message=message), 400 
Example 36
Project: selene-backend   Author: MycroftAI   File: account.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def post(self):
        self.request_data = json.loads(self.request.data)
        self._validate_post_request()
        email_address, password = self._determine_login_method()
        self._add_account(email_address, password)
        return jsonify('Account added successfully'), HTTPStatus.OK 
Example 37
Project: selene-backend   Author: MycroftAI   File: defaults.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _validate_request(self):
        request_data = json.loads(self.request.data)
        defaults = DefaultsRequest()
        defaults.city = request_data.get('city')
        defaults.country = request_data.get('country')
        defaults.region = request_data.get('region')
        defaults.timezone = request_data.get('timezone')
        defaults.voice = request_data['voice']
        defaults.wake_word = request_data['wakeWord']
        defaults.validate()

        return defaults 
Example 38
Project: selene-backend   Author: MycroftAI   File: device.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_pairing_data(self, pairing_code: str) -> dict:
        """Checking if there's one pairing session for the pairing code."""
        cache_key = 'pairing.code:' + pairing_code
        pairing_cache = self.cache.get(cache_key)
        pairing_data = json.loads(pairing_cache)

        return pairing_data 
Example 39
Project: flask-rak   Author: Huong-nt   File: core.py    Apache License 2.0 5 votes vote down vote up
def _rogo_request(self):
        app_name = flask_request.blueprint
        raw_body = flask_request.data
        rogo_request_payload = json.loads(raw_body)
        rogo_request_payload['app_name'] = app_name
        return rogo_request_payload 
Example 40
Project: hdxscraper-undp-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def get_num_results(self, table):
        r = self.get_data(table)
        loaded = loads(r.data)
        return loaded['num_results'] 
Example 41
Project: hdxscraper-undp-climate   Author: nerevu   File: __init__.py    MIT License 5 votes vote down vote up
def get_type(self, table, id=1):
        r = self.get_data(table, id)
        loaded = loads(r.data)
        return loaded['type']['id'] 
Example 42
Project: flaskr-intro   Author: ZoranPandovski   File: test_flaskr.py    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)
        self.assertEqual(data['message'], 'Post Deleted') 
Example 43
Project: flaskr-intro   Author: ZoranPandovski   File: test_flaskr.py    MIT License 5 votes vote down vote up
def test_delete_message_can_fail(self, db_mock):
        """Ensure the messages are being deleted"""
        db_mock.session.query = Mock(side_effect=Exception('Some message'))

        rv = self.app.get('/delete/1')
        data = json.loads(rv.data)
        self.assertEqual(data['status'], 0)
        self.assertEqual(data['message'], "Exception('Some message',)") 
Example 44
Project: Python24   Author: HaoZhang95   File: demo5_unit_test.py    MIT License 5 votes vote down vote up
def test_empty_username_password(self):
        response = app.test_client().post('/login', data={})
        resp_data = response.data
        json_dict = json.loads(resp_data)

        print(json_dict)

        self.assertIsNotNone(json_dict, '未获取到相关的返回数据')
        self.assertIn('errcode', json_dict, '返回的数据格式不正确')
        errcode = json_dict['errcode']
        self.assertEqual(errcode, -2, '返回的状态码错误')

    # 测试用户名或者密码不正确,会返回errcode = -1 
Example 45
Project: XMorbid   Author: NMTech0x90   File: wrappers.py    GNU General Public License v3.0 5 votes vote down vote up
def get_json(self, force=False, silent=False, cache=True):
        """Parse and return the data as JSON. If the mimetype does not
        indicate JSON (:mimetype:`application/json`, see
        :meth:`is_json`), this returns ``None`` unless ``force`` is
        true. If parsing fails, :meth:`on_json_loading_failed` is called
        and its return value is used as the return value.

        :param force: Ignore the mimetype and always try to parse JSON.
        :param silent: Silence parsing errors and return ``None``
            instead.
        :param cache: Store the parsed JSON to return for subsequent
            calls.
        """
        if cache and self._cached_json[silent] is not Ellipsis:
            return self._cached_json[silent]

        if not (force or self.is_json):
            return None

        data = self._get_data_for_json(cache=cache)

        try:
            rv = json.loads(data)
        except ValueError as e:
            if silent:
                rv = None
                if cache:
                    normal_rv, _ = self._cached_json
                    self._cached_json = (normal_rv, rv)
            else:
                rv = self.on_json_loading_failed(e)
                if cache:
                    _, silent_rv = self._cached_json
                    self._cached_json = (rv, silent_rv)
        else:
            if cache:
                self._cached_json = (rv, rv)

        return rv 
Example 46
Project: XMorbid   Author: NMTech0x90   File: tag.py    GNU General Public License v3.0 5 votes vote down vote up
def loads(self, value):
        """Load data from a JSON string and deserialized any tagged objects."""
        return loads(value, object_hook=self.untag) 
Example 47
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 5 votes vote down vote up
def submit_lifecycle_ignition(request_raw_query):
    """
    Lifecycle Ignition
    ---
    tags:
      - lifecycle
    responses:
      200:
        description: A JSON of the ignition status
    """
    try:
        machine_ignition = json.loads(request.get_data())
    except ValueError:
        app.logger.error("%s have incorrect content" % request.path)
        return jsonify({"message": "FlaskValueError"}), 406
    req = requests.get("%s/ignition?%s" % (EC.matchbox_uri, request_raw_query))
    try:
        matchbox_ignition = json.loads(req.content)
        req.close()
    except ValueError:
        app.logger.error("%s have incorrect matchbox return" % request.path)
        return jsonify({"message": "MatchboxValueError"}), 406

    @smartdb.cockroach_transaction
    def op(caller=request.url_rule):
        with SMART.new_session() as session:
            try:
                inject = crud.InjectLifecycle(session, request_raw_query=request_raw_query)
                if json.dumps(machine_ignition, sort_keys=True) == json.dumps(matchbox_ignition, sort_keys=True):
                    inject.refresh_lifecycle_ignition(True)
                    return jsonify({"message": "Up-to-date"}), 200
                else:
                    inject.refresh_lifecycle_ignition(False)
                    return jsonify({"message": "Outdated"}), 210
            except AttributeError:
                return jsonify({"message": "Unknown"}), 406

    return op(caller=request.url_rule) 
Example 48
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 5 votes vote down vote up
def record_discovery_data():
    """
    Discovery
    Report the current facts of a machine
    ---
    tags:
      - discovery
    responses:
      200:
        description: Number of machines and if the machine is new
        schema:
            type: dict
    """
    app.logger.info("%s %s" % (request.method, request.url))
    err = jsonify({u'boot-info': {}, u'lldp': {}, u'interfaces': [], u"disks": []}), 406
    try:
        discovery_data = json.loads(request.get_data())
    except (KeyError, TypeError, ValueError):
        logger.error("fail to parse discovery data: %s" % request.get_data())
        return err

    try:
        new = repositories.discovery.upsert(discovery_data)
        repositories.machine_state.update(discovery_data["boot-info"]["mac"], MachineStates.discovery)
        CACHE.delete(request.path)
        return jsonify({"new-discovery": new}), 200
    except TypeError as e:
        logger.error("fail to store discovery data: %s -> %s" % (request.get_data(), e))
        return err 
Example 49
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 5 votes vote down vote up
def scheduler_post():
    """
    Scheduler
    Affect a schedule to a machine
    ---
    tags:
      - scheduler
    responses:
      406:
        description: Incorrect body content
        schema:
            type: dict
      200:
        description: The body sent
        schema:
            type: dict
    """
    try:
        req = json.loads(request.get_data())
    except ValueError:
        return jsonify(
            {
                u"roles": model.ScheduleRoles.roles,
                u'selector': {
                    u"mac": ""
                }
            }), 406

    repositories.machine_schedule.create_schedule(req)
    CACHE.delete(request.path)
    return jsonify(req) 
Example 50
Project: Blockly-rduino-communication   Author: technologiescollege   File: wrappers.py    GNU General Public License v3.0 5 votes vote down vote up
def get_json(self, force=False, silent=False, cache=True):
        """Parse and return the data as JSON. If the mimetype does not
        indicate JSON (:mimetype:`application/json`, see
        :meth:`is_json`), this returns ``None`` unless ``force`` is
        true. If parsing fails, :meth:`on_json_loading_failed` is called
        and its return value is used as the return value.

        :param force: Ignore the mimetype and always try to parse JSON.
        :param silent: Silence parsing errors and return ``None``
            instead.
        :param cache: Store the parsed JSON to return for subsequent
            calls.
        """
        if cache and self._cached_json[silent] is not Ellipsis:
            return self._cached_json[silent]

        if not (force or self.is_json):
            return None

        data = self._get_data_for_json(cache=cache)

        try:
            rv = json.loads(data)
        except ValueError as e:
            if silent:
                rv = None
                if cache:
                    normal_rv, _ = self._cached_json
                    self._cached_json = (normal_rv, rv)
            else:
                rv = self.on_json_loading_failed(e)
                if cache:
                    _, silent_rv = self._cached_json
                    self._cached_json = (rv, silent_rv)
        else:
            if cache:
                self._cached_json = (rv, rv)

        return rv 
Example 51
Project: Blockly-rduino-communication   Author: technologiescollege   File: tag.py    GNU General Public License v3.0 5 votes vote down vote up
def loads(self, value):
        """Load data from a JSON string and deserialized any tagged objects."""
        return loads(value, object_hook=self.untag) 
Example 52
Project: xuemc   Author: skycucumber   File: views.py    GNU General Public License v2.0 5 votes vote down vote up
def get(self):
        """Returns the result of evaluating the SQL functions specified in the
        body of the request.

        For a description of the request and response formats, see
        :ref:`functionevaluation`.

        """
        if 'q' not in request.args or not request.args.get('q'):
            return dict(message='Empty query parameter'), 400
        # if parsing JSON fails, return a 400 error in JSON format
        try:
            data = json.loads(str(request.args.get('q'))) or {}
        except (TypeError, ValueError, OverflowError) as exception:
            current_app.logger.exception(str(exception))
            return dict(message='Unable to decode data'), 400
        try:
            result = evaluate_functions(self.session, self.model,
                                        data.get('functions', []))
            if not result:
                return {}, 204
            return result
        except AttributeError as exception:
            current_app.logger.exception(str(exception))
            message = 'No such field "{0}"'.format(exception.field)
            return dict(message=message), 400
        except OperationalError as exception:
            current_app.logger.exception(str(exception))
            message = 'No such function "{0}"'.format(exception.function)
            return dict(message=message), 400 
Example 53
Project: geno-browser   Author: mbiokyle29   File: test_files.py    MIT License 5 votes vote down vote up
def createTestUser(self):
        response = self.app.post('/api/users', 
            data=json.dumps({'username': 'kyle', 'email': '[email protected]','password':'SECRET'}), 
            content_type='application/json')

        response = self.app.post('api/auth',
                                 data=json.dumps({'username':'kyle', 'password':'SECRET'}),
                                 content_type='application/json')

        JSON = json.loads(response.get_data())
        token = str(JSON.get('token'))
        self.user_header = [('Authorization','Bearer ' + token)] 
Example 54
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 5 votes vote down vote up
def testUpdateView(self):
        LOG.info("Testing updating view endpoint /views with PUT")

        # first create a user
        self.createTestUser()
        self.uploadTestWig()
        self.createTestTrack()
        self.createAnotherTestTrack()
        self.createTestView()

        view = self.getTestView()

        response = self.app.put('/api/views/1', 
            data=json.dumps({
                'track_ids': [1,2],
                'view_name': 'NEW-NAME'
            }), 
            content_type='application/json',
            headers=self.user_header
        )

        self.assert200(response)

        data = json.loads(response.get_data())
        self.assertEqual(data.get('view_name'), 'NEW-NAME')
        self.assertEqual(data.get('user_id'), 1)
        self.assertEqual(data.get('track_ids'), [1,2]) 
Example 55
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 5 votes vote down vote up
def createTestUser(self):
        response = self.app.post('/api/users', 
            data=json.dumps({'username': 'kyle', 'email': '[email protected]','password':'SECRET'}), 
            content_type='application/json')

        response = self.app.post('api/auth',
                                 data=json.dumps({'username':'kyle', 'password':'SECRET'}),
                                 content_type='application/json')

        JSON = json.loads(response.get_data())
        token = str(JSON.get('token'))
        self.user_header = [('Authorization','Bearer ' + token)] 
Example 56
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 5 votes vote down vote up
def getTestTrack(self):
        response = self.app.get('/api/tracks/1',
            headers=self.user_header
        )
        track = json.loads(response.get_data())
        return track 
Example 57
Project: geno-browser   Author: mbiokyle29   File: test_views.py    MIT License 5 votes vote down vote up
def getTestDataView(self):
        response = self.app.get('/api/views/data/1',
            headers=self.user_header
        )
        self.assert200(response)
        data = json.loads(response.get_data())
        return data 
Example 58
Project: geno-browser   Author: mbiokyle29   File: test_tracks.py    MIT License 5 votes vote down vote up
def createTestUser(self):
        response = self.app.post('/api/users', 
            data=json.dumps({'username': 'kyle', 'email': '[email protected]','password':'SECRET'}),
            content_type='application/json')

        response = self.app.post('api/auth',
             data=json.dumps({'username':'kyle', 'password':'SECRET'}),
             content_type='application/json')

        JSON = json.loads(response.get_data())
        token = str(JSON.get('token'))
        self.user_header = [('Authorization','Bearer ' + token)] 
Example 59
Project: geno-browser   Author: mbiokyle29   File: test_users.py    MIT License 5 votes vote down vote up
def testCreateUser(self):
        LOG.info("Testing create user endpoint /api/users with POST")

        # Send post request
        response = self.app.post('/api/users', 
            data=json.dumps({'username': 'kyle', 'email': '[email protected]','password':'SECRET'}), 
            content_type='application/json')

        self.assert200(response)
        self.assertEqual(json.loads(response.get_data()).get('user_id'), 1) 
Example 60
Project: geno-browser   Author: mbiokyle29   File: test_users.py    MIT License 5 votes vote down vote up
def testGetUser(self):
        LOG.info("Testing user endpoint /api/users/ with GET")

        # Helper to create a user (has already been tested above)
        self.createTestUser()

        # Check the user json returned
        response = self.app.get('/api/users/', headers=[('Authorization','Bearer ' + self.token)])
        self.assert200(response)

        # Make sure the user dict has the right fields
        user = json.loads(response.get_data())
        self.assertDictContainsSubset({'username':'kyle','email':'[email protected]'},user) 
Example 61
Project: geno-browser   Author: mbiokyle29   File: test_users.py    MIT License 5 votes vote down vote up
def createTestUser(self):
        response = self.app.post('/api/users', 
            data=json.dumps({'username': 'kyle', 'email': '[email protected]', 'password':'SECRET'}), 
            content_type='application/json')

        response = self.app.post('api/auth',
            data=json.dumps({'username':'kyle', 'password':'SECRET'}),
            content_type='application/json')

        JSON = json.loads(response.get_data())
        self.token = str(JSON.get('token')) 
Example 62
Project: geno-browser   Author: mbiokyle29   File: test_users.py    MIT License 5 votes vote down vote up
def get_user(self):
        response = self.app.get('/api/users', headers=[('Authorization','Bearer ' + self.token)])
        self.assert200(response)
        user = json.loads(response.get_data())
        return user 
Example 63
Project: zesje   Author: zesje   File: test_widgets.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_mco_finalized_exam(test_client, add_test_data):
    """
    Attempt to update a ProblemWidget in a finalized exam
    """
    widget_id = 2

    req_body = {'x': 50}

    result = test_client.patch(f'/api/widgets/{widget_id}', data=req_body)
    data = json.loads(result.data)

    assert data['status'] == 405 
Example 64
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_present(test_client, add_test_data):
    result = test_client.get('/api/mult-choice/1')
    data = json.loads(result.data)

    assert data['status'] == 404 
Example 65
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_problem_not_present(test_client, add_test_data):
    req_json = {
        'x': 100,
        'y': 40,
        'problem_id': 99,
        'page': 1,
        'label': 'a',
        'name': 'test'
    }

    result = test_client.put('/api/mult-choice/', data=req_json)
    data = json.loads(result.data)

    assert data['status'] == 404 
Example 66
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_finalized_exam(test_client, add_test_data, monkeypatch_write_finalized_exam):
    req = mco_json()

    # Link mc_option to finalized exam
    req['problem_id'] = '1'

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)

    assert data['mult_choice_id']

    test_client.put('api/exams/1', data={'finalized': 'true'})

    id = data['mult_choice_id']

    req2 = {
        'x': 120,
        'y': 50,
        'problem_id': 4,
        'page': 1,
        'label': 'b',
        'name': 'test'
    }

    result = test_client.patch(f'/api/mult-choice/{id}', data=req2)
    data = json.loads(result.data)

    assert data['status'] == 405 
Example 67
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete(test_client, add_test_data):
    req = mco_json()

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)
    id = data['mult_choice_id']

    response = test_client.delete(f'/api/mult-choice/{id}')
    data = json.loads(response.data)

    assert data['status'] == 200 
Example 68
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_not_present(test_client, add_test_data):
    id = 100

    response = test_client.delete(f'/api/mult-choice/{id}')
    data = json.loads(response.data)

    assert data['status'] == 404 
Example 69
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_add_finalized_exam(test_client, add_test_data):
    mc_option_json = {
        'x': 100,
        'y': 40,
        'problem_id': 2,
        'page': 1,
        'label': 'a',
        'name': 'test'
    }

    response = test_client.put('/api/mult-choice/', data=mc_option_json)
    data = json.loads(response.data)

    assert data['status'] == 405 
Example 70
Project: zesje   Author: zesje   File: test_mc_option.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_delete_finalized_exam(test_client, add_test_data, monkeypatch_write_finalized_exam):
    req = mco_json()

    response = test_client.put('/api/mult-choice/', data=req)
    data = json.loads(response.data)
    mc_id = data['mult_choice_id']

    test_client.put('api/exams/1', data={'finalized': 'true'})

    response = test_client.delete(f'/api/mult-choice/{mc_id}')
    data = json.loads(response.data)

    assert data['status'] == 405 
Example 71
Project: LOST   Author: kylemh   File: api.py    MIT License 4 votes vote down vote up
def activate_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])

        # If http request is missing a parameter...
        if 'username' not in api_req or 'password' not in api_req or 'role' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameters'})
            return error_result
        else:
            username = api_req['username']
            password = api_req['password']
            role = api_req['role']

        # Handle errors within CLI arguments.
        if len(username) > 16 or len(password) > 16:
            error_result = json.dumps({'result': 'Error: Username or Password Too Long'})
            return error_result

        # All parameters are valid.
        if role == 'logofc':
            role = 2
        elif role == 'facofc':  # facofc
            role = 3
        else:
            error_result = json.dumps({'result': 'Error: Unsupported Role'})
            return error_result

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = helpers.db_query(matching_user, [username])

        # If user exists in database, activate user; otherwise, create and activate new user.
        if user_does_exist:
            activate_existing_user = ("UPDATE users SET password = %s, active = TRUE "
                                      "WHERE username = %s")
            helpers.db_change(activate_existing_user, [password, username])
        else:
            create_user = ("INSERT INTO users (user_pk, role_fk, username, password, active) "
                           "VALUES (DEFAULT, %s, %s, %s, TRUE)")
            helpers.db_change(create_user, [role, username, password])

        data = json.dumps({'result': 'OK'})
        return data 
Example 72
Project: LOST   Author: kylemh   File: api.py    MIT License 4 votes vote down vote up
def activate_user():
    if request.method == 'POST' and 'arguments' in request.form:
        api_req = json.loads(request.form['arguments'])

        # If http request is missing a parameter...
        if 'username' not in api_req or 'password' not in api_req or 'role' not in api_req:
            error_result = json.dumps({'result': 'Error: Missing Parameters'})
            return error_result
        else:
            username = api_req['username']
            password = api_req['password']
            role = api_req['role']

        # Handle errors within CLI arguments.
        if len(username) > 16:
            error_result = json.dumps({'result': 'Error: Username Too Long'})
            return error_result

        # All parameters are valid.
        if role == 'logofc':
            role = 2
        elif role == 'facofc':  # facofc
            role = 3
        else:
            error_result = json.dumps({'result': 'Error: Unsupported Role'})
            return error_result

        matching_user = "SELECT * FROM users WHERE username = %s"
        user_does_exist = db_query(matching_user, [username])

        # If user exists in database, activate user; otherwise, create and activate new user.
        if user_does_exist:
            activate_existing_user = ("UPDATE users SET password = %s, active = TRUE "
                                      "WHERE username = %s")
            db_change(activate_existing_user, [password, username])
        else:
            create_user = ("INSERT INTO users (user_pk, role_fk, username, password, active) "
                           "VALUES (DEFAULT, %s, %s, %s, TRUE)")
            db_change(create_user, [role, username, password])

        data = json.dumps({'result': 'OK'})
        return data 
Example 73
Project: rosie-ci   Author: adafruit   File: rosie-ci.py    MIT License 4 votes vote down vote up
def travis():
    signature = base64.b64decode(request.headers.get('Signature'))
    try:
        public_key = _get_travis_public_key()
    except requests.Timeout:
        print("Timed out when attempting to retrieve Travis CI public key")
        abort(500)
    except requests.RequestException as e:
        print("Failed to retrieve Travis CI public key")
        abort(500)
    try:
        check_authorized(signature, public_key, request.form["payload"])
    except SignatureError:
        abort(401)
    data = json.loads(request.form["payload"])

    repo = data["repository"]["owner_name"] + "/" + data["repository"]["name"]
    build_number = data["id"]
    sha = data["commit"]
    if data["type"] == "pull_request":
        sha = data["head_commit"]
    tag = None
    if data["type"] == "push" and data["tag"] != None:
        tag = data["tag"]
    print(data)

    key = sha
    if tag is not None:
        key = tag

    upload_lock = "upload-lock:" + sha

    if data["state"] in ("started", ):
        print("travis started", key)
        # Handle pulls differently.
        if data["pull_request"]:
            load_code.delay(repo, "pull/" + str(data["pull_request_number"]) + "/head")
        elif data["tag"]:
            load_code.delay(repo, "refs/tags/" + tag)
        else:
            load_code.delay(repo, "refs/heads/" + data["branch"])
        redis.setex(upload_lock, 20 * 60, "locked")
        set_status(repo, sha, "pending", data["build_url"], "Waiting on Travis to complete.")
    elif data["state"] in ("passed", "failed"):
        print("travis finished")
        key = repo + "/" + key
        set_status(repo, sha, "pending", "https://rosie-ci.ngrok.io/log/" + key, "Queueing Rosie test.")
        redis.delete(upload_lock)
        test_commit(repo, sha, tag)
    elif data["state"] is ("cancelled", ):
        print("travis cancelled")
        redis.delete(upload_lock)
        set_status(repo, sha, "error", data["build_url"], "Travis cancelled.")
    elif data["status"] is None:
        set_status(repo, sha, "error", data["build_url"], "Travis error.")
    else:
        print("unhandled state:", data["state"])
        print(data)
    return jsonify({'status': 'received'}) 
Example 74
Project: oa_qian   Author: sunqb   File: views.py    Apache License 2.0 4 votes vote down vote up
def jsonpify(*args, **kw):
    """Passes the specified arguments directly to :func:`jsonify` with a status
    code of 200, then wraps the response with the name of a JSON-P callback
    function specified as a query parameter called ``'callback'`` (or does
    nothing if no such callback function is specified in the request).

    If the keyword arguments include the string specified by :data:`_HEADERS`,
    its value must be a dictionary specifying headers to set before sending the
    JSONified response to the client. Headers on the response will be
    overwritten by headers specified in this dictionary.

    If the keyword arguments include the string specified by :data:`_STATUS`,
    its value must be an integer representing the status code of the response.
    Otherwise, the status code of the response will be :http:status:`200`.

    """
    # HACK In order to make the headers and status code available in the
    # content of the response, we need to send it from the view function to
    # this jsonpify function via its keyword arguments. This is a limitation of
    # the mimerender library: it has no way of making the headers and status
    # code known to the rendering functions.
    headers = kw.pop(_HEADERS, {})
    status_code = kw.pop(_STATUS, 200)
    response = jsonify(*args, **kw)
    callback = request.args.get('callback', False)
    if callback:
        # Reload the data from the constructed JSON string so we can wrap it in
        # a JSONP function.
        data = json.loads(response.data)
        # Force the 'Content-Type' header to be 'application/javascript'.
        #
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is valid
        # Javascript, but not valid JSON.
        headers['Content-Type'] = 'application/javascript'
        # Add the headers and status code as metadata to the JSONP response.
        meta = _headers_to_json(headers) if headers is not None else {}
        meta['status'] = status_code
        inner = json.dumps(dict(meta=meta, data=data))
        content = '{0}({1})'.format(callback, inner)
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is not valid JSON.
        mimetype = 'application/javascript'
        response = current_app.response_class(content, mimetype=mimetype)
    # Set the headers on the HTTP response as well.
    if headers:
        set_headers(response, headers)
    response.status_code = status_code
    return response 
Example 75
Project: Python24   Author: HaoZhang95   File: views.py    MIT License 4 votes vote down vote up
def register():
    params_dict = json.loads(request.data)
    mobile = params_dict.get('mobile')
    smscode = params_dict.get('sms_code')
    password = params_dict.get('password')

    # 验证参数
    if not all([mobile, smscode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 验证手机号是否正确
    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号码格式不正确')

    # 从redis出取出验证码
    try:
        real_sms_code = redis_store.get('SMS_' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    # 表示验证码过期,一定要记住从redis取出后进行decode,否则怎么死的都不知道
    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg='手机验证码错误或者已过期')
    else:
        real_sms_code = real_sms_code.decode()

    # 对比验证码
    if real_sms_code != smscode:
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')

    # 进行用户注册
    user = User()
    user.mobile = mobile
    user.nick_name = mobile
    # 第一次注册的时候最后一次登录信息就直接伴随着模型的创建写入到了数据库
    user.last_login = datetime.now()
    # 对密码进行处理,在user的数据模型类中自动加密,将加密解锁设置到user.password_hash
    user.password = password

    # 添加到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')

    # 往session中保存状态表示当前已登录
    """
        这里的session是使用的是Config类中的存储在redis中的session,下面这几个变量值都是存在一个相同的session——id下面的
        并不是在redis分开存储了3个,而是在一个session_id下,值为一个字典,字典里面包含这3个变量
    """
    session['user_id'] = user.id
    session['mobile'] = user.mobile
    session['nick_name'] = user.nick_name

    # 返回响应
    return jsonify(errno=RET.OK, errmsg='注册成功') 
Example 76
Project: Python24   Author: HaoZhang95   File: views.py    MIT License 4 votes vote down vote up
def send_sms_code():
    # 获取参数
    # params_dict = json.loads(request.data)
    params_dict = request.json
    mobile = params_dict.get('mobile')
    image_code = params_dict.get('image_code')
    image_code_id = params_dict.get('image_code_id')

    # 验证参数
    if not all( [mobile, image_code, image_code_id] ):
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    # 验证手机号是否正确
    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号码格式不正确')

    # 从redis出取出验证码
    try:
        real_image_code = redis_store.get('ImageCodeId_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    if not real_image_code:
        # 表示验证码过期
        return jsonify(errno=RET.NODATA, errmsg='图片验证码已过期')
    else:
        # 如果能够取出来值进行解码,否则输出是b'XXXX'永远不会想等,删除redis中缓存的内容
        real_image_code = real_image_code.decode()

    # 对比验证码
    # print("real_image_code: %s, image_code: %s" % (real_image_code.upper(), image_code.upper()))
    if real_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')

    # 验证码正确,发送短信验证码,随机生成6位数,06d表示不够6位前面补上0
    # sms_code_str = "%06d" % random.randint(0, 999999)
    sms_code_str = "888888"

    # 发送短信验证码,假设验证码发送成功,并且向redis存入一个验证码=888888
    # result = CCP().send_template_sms(mobile, [sms_code_str, constants.SMS_CODE_REDIS_EXPIRES / 5], '1')
    result = 0

    if result != 0:
        # 代表发送失败
        return jsonify(errno=RET.THIRDERR, errmsg='短信发送失败')

    # 6. redis中保存短信验证码内容, 等待用户提交表单进行验证
    try:
        redis_store.set("SMS_" + mobile, sms_code_str, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        # 保存短信验证码失败
        return jsonify(errno=RET.DBERR, errmsg="redis保存短信验证码失败")

    return jsonify(errno=RET.OK, errmsg='发送成功') 
Example 77
Project: enjoliver   Author: JulienBalestra   File: api.py    MIT License 4 votes vote down vote up
def change_lifecycle_rolling(request_raw_query):
    """
    Lifecycle Rolling Update
    Change the current policy for a given machine by MAC
    ---
    tags:
      - lifecycle
    parameters:
      - name: request_raw_query
        in: path
        description: Pass the mac as 'mac=<mac>'
        required: true
        type: string
    responses:
      200:
        description: Rolling Update is enable
        schema:
            type: dict
      401:
        description: Mac address is not in database
        schema:
            type: dict
    """

    app.logger.info("%s %s" % (request.method, request.url))
    try:
        strategy = json.loads(request.get_data())["strategy"]
        app.logger.info("%s %s rolling strategy: setting to %s" % (request.method, request.url, strategy))
    except (KeyError, ValueError):
        # JSONDecodeError is a subclass of ValueError
        # Cannot use JSONDecodeError because the import is not consistent between python3.X
        app.logger.info("%s %s rolling strategy: setting default to kexec" % (request.method, request.url))
        strategy = "kexec"

    @smartdb.cockroach_transaction
    def op(caller=request.url_rule):
        with SMART.new_session() as session:
            try:
                life = crud.InjectLifecycle(session, request_raw_query)
                life.apply_lifecycle_rolling(True, strategy)
                return jsonify({"enable": True, "request_raw_query": request_raw_query, "strategy": strategy}), 200
            except AttributeError:
                return jsonify({"enable": None, "request_raw_query": request_raw_query, "strategy": strategy}), 401

    return op(caller=request.url_rule) 
Example 78
Project: xuemc   Author: skycucumber   File: views.py    GNU General Public License v2.0 4 votes vote down vote up
def jsonpify(*args, **kw):
    """Passes the specified arguments directly to :func:`jsonify` with a status
    code of 200, then wraps the response with the name of a JSON-P callback
    function specified as a query parameter called ``'callback'`` (or does
    nothing if no such callback function is specified in the request).

    If the keyword arguments include the string specified by :data:`_HEADERS`,
    its value must be a dictionary specifying headers to set before sending the
    JSONified response to the client. Headers on the response will be
    overwritten by headers specified in this dictionary.

    If the keyword arguments include the string specified by :data:`_STATUS`,
    its value must be an integer representing the status code of the response.
    Otherwise, the status code of the response will be :http:status:`200`.

    """
    # HACK In order to make the headers and status code available in the
    # content of the response, we need to send it from the view function to
    # this jsonpify function via its keyword arguments. This is a limitation of
    # the mimerender library: it has no way of making the headers and status
    # code known to the rendering functions.
    headers = kw.pop(_HEADERS, {})
    status_code = kw.pop(_STATUS, 200)
    response = jsonify(*args, **kw)
    callback = request.args.get('callback', False)
    if callback:
        # Reload the data from the constructed JSON string so we can wrap it in
        # a JSONP function.
        data = json.loads(response.data)
        # Force the 'Content-Type' header to be 'application/javascript'.
        #
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is valid
        # Javascript, but not valid JSON.
        headers['Content-Type'] = 'application/javascript'
        # Add the headers and status code as metadata to the JSONP response.
        meta = _headers_to_json(headers) if headers is not None else {}
        meta['status'] = status_code
        inner = json.dumps(dict(meta=meta, data=data))
        content = '{0}({1})'.format(callback, inner)
        # Note that this is different from the mimetype used in Flask for JSON
        # responses; Flask uses 'application/json'. We use
        # 'application/javascript' because a JSONP response is not valid JSON.
        mimetype = 'application/javascript'
        response = current_app.response_class(content, mimetype=mimetype)
    # Set the headers on the HTTP response as well.
    if headers:
        set_headers(response, headers)
    response.status_code = status_code
    return response 
Example 79
Project: xuemc   Author: skycucumber   File: views.py    GNU General Public License v2.0 4 votes vote down vote up
def _delete_many(self):
        """Deletes multiple instances of the model.

        If search parameters are provided via the ``q`` query parameter, only
        those instances matching the search parameters will be deleted.

        If no instances were deleted, this returns a
        :http:status:`404`. Otherwise, it returns a :http:status:`200` with the
        number of deleted instances in the body of the response.

        """
        # try to get search query from the request query parameters
        try:
            search_params = json.loads(request.args.get('q', '{}'))
        except (TypeError, ValueError, OverflowError) as exception:
            current_app.logger.exception(str(exception))
            return dict(message='Unable to decode search query'), 400

        for preprocessor in self.preprocessors['DELETE_MANY']:
            preprocessor(search_params=search_params)

        # perform a filtered search
        try:
            # HACK We need to ignore any ``order_by`` request from the client,
            # because for some reason, SQLAlchemy does not allow calling
            # delete() on a query that has an ``order_by()`` on it. If you
            # attempt to call delete(), you get this error:
            #
            #     sqlalchemy.exc.InvalidRequestError: Can't call Query.delete()
            #     when order_by() has been called
            #
            result = search(self.session, self.model, search_params,
                            _ignore_order_by=True)
        except NoResultFound:
            return dict(message='No result found'), 404
        except MultipleResultsFound:
            return dict(message='Multiple results found'), 400
        except Exception as exception:
            current_app.logger.exception(str(exception))
            return dict(message='Unable to construct query'), 400

        # for security purposes, don't transmit list as top-level JSON
        if isinstance(result, Query):
            # Implementation note: `synchronize_session=False`, described in
            # the SQLAlchemy documentation for
            # :meth:`sqlalchemy.orm.query.Query.delete`, states that this is
            # the most efficient option for bulk deletion, and is reliable once
            # the session has expired, which occurs after the session commit
            # below.
            num_deleted = result.delete(synchronize_session=False)
        else:
            self.session.delete(result)
            num_deleted = 1
        self.session.commit()
        result = dict(num_deleted=num_deleted)
        for postprocessor in self.postprocessors['DELETE_MANY']:
            postprocessor(result=result, search_params=search_params)
        return (result, 200) if num_deleted > 0 else 404 
Example 80
Project: Portfolio-compute   Author: IBM   File: run.py    Apache License 2.0 4 votes vote down vote up
def compute_unit_tests():
    '''
    Calculates analytics for a portfolio.
    Breaks into 500 instrument chunks to comply with container constraints.
    '''
    if request.method == 'POST':
        portfolios = []
        data = json.loads(request.data)
        portfolios.append(data["portfolio"])

    #Stopwatch
    start_time = datetime.datetime.now()
    if data:
        analytics = data["analytics"]
    else:
        analytics = ['THEO/Price','THEO/Value']
    results = []

    for p in portfolios:
        portfolio_start = datetime.datetime.now()
        holdings = investmentportfolio.Get_Portfolio_Holdings(p,False)['holdings']
        #Since the payload is too large, odds are there are 500-instrument chunks added to the portfolio.
        for ph in range(0,len(holdings)):
            instruments = [row['instrumentId'] for row in holdings[ph]['holdings']]
            print("Processing " + str(p) + " portfolio segment #"+str(ph) +".")
            #send 500 IDs at a time to Instrument Analytics Service:
            #for i in instruments...
            for i in range(0,len(instruments),500):
                ids = instruments[i:i+500]
                ia = instrumentanalytics.Compute_InstrumentAnalytics(ids,analytics)
                #for j in results...
                if 'error' not in ia:
                    for j in ia:
                        r = {
                            "portfolio":p,
                            "id":j['instrument']}
                        for a in analytics:
                            r[a] = j['values'][0][a]
                        r["date"] = j['values'][0]['date']
                        h = [row for row in holdings[0]['holdings'] if j['instrument']==row['instrumentId']][0]
                        for key,value in h.items():
                            if key not in ['instrumentId']:
                                r[key] = value
                        results.append(r)
                #Debug
                if i+500<len(instruments):
                    l = i+500
                else:
                    l = len(instruments)
                print("Processed securities " + str(i) + " through " + str(l) + ". Time elapsed on this portfolio: " + str(datetime.datetime.now() - portfolio_start))

    print("Unit testing completed. Total time elapsed: " + str(datetime.datetime.now() - start_time))
    return Response(json.dumps(results), mimetype='application/json')