requests.codes.ok

Here are the examples of the python api requests.codes.ok taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: presto-admin
Source File: test_collect.py
View license
    @patch('prestoadmin.collect.request_url')
    @patch("prestoadmin.collect.requests.get")
    def test_query_info_fail_invalid_id(self, req_get_mock, requests_url):
        env.host = "myhost"
        env.roledefs["coordinator"] = ["myhost"]
        query_id = "invalid_id"
        req_get_mock.return_value.status_code = requests.codes.ok + 10
        self.assertRaisesRegexp(SystemExit, "Unable to retrieve information. "
                                            "Please check that the query_id "
                                            "is correct, or check that server "
                                            "is up with command: "
                                            "server status",
                                collect.query_info, query_id)

Example 2

View license
    def _get_metadata(self, request): 
        """
        This method retrieves values from metadata service.
        
        request -- The request part after the metadata service address, for example if full request is:
                   'http://169.254.169.254/latest/meta-data/placement/availability-zone/' 
                   then the request part is 'latest/meta-data/placement/availability-zone/'.
        """
        session = Session()
        session.mount("http://", HTTPAdapter(max_retries=self._TOTAL_RETRIES))
        result = session.get(self.metadata_server + request, timeout=self._REQUEST_TIMEOUT)
        if result.status_code is codes.ok:
            return str(result.text)
        else:
            self._LOGGER.error("The request: '" + str(request) + "' failed with status code: '" + str(result.status_code) + "' and message: '" + str(result.text) +"'.")
            raise MetadataRequestException("Cannot retrieve configuration from metadata service. Status code: " + str(result.status_code))

Example 3

Project: collectd-cloudwatch
Source File: setup.py
View license
    def _get_metadata(self, request):
        """
        This method retrieves values from metadata service.

        request -- The request part after the metadata service address, for example if full request is:
                   'http://169.254.169.254/latest/meta-data/placement/availability-zone/'
                   then the request part is 'latest/meta-data/placement/availability-zone/'.
        """
        from requests import Session, codes
        from requests.adapters import HTTPAdapter
        try:
            session = Session()
            session.mount("http://", HTTPAdapter(max_retries=self._MAX_RETRIES))
            result = session.get(self.metadata_server + request, timeout=self._REQUEST_TIMEOUT)
        except Exception as e:
            raise MetadataRequestException("Cannot access metadata service. Cause: " + str(e))
        if result.status_code is not codes.ok:
            raise MetadataRequestException("Cannot retrieve configuration from metadata service. Status code: " + str(result.status_code))
        return str(result.text)

Example 4

Project: pushbullet.py
Source File: pushbullet.py
View license
    def edit_chat(self, chat, name):
        data = {"name": name}
        iden = chat.iden
        r = self._session.post("{}/{}".format(self.CHATS_URL, iden), data=json.dumps(data))
        if r.status_code == requests.codes.ok:
            new_chat = Chat(self, r.json())
            self.chats[self.chats.index(chat)] = new_chat
            return new_chat
        else:
            raise PushbulletError(r.text)

Example 5

Project: pushbullet.py
Source File: pushbullet.py
View license
    def remove_device(self, device):
        iden = device.device_iden
        r = self._session.delete("{}/{}".format(self.DEVICES_URL, iden))
        if r.status_code == requests.codes.ok:
            self.devices.remove(device)
        else:
            raise PushbulletError(r.text)

Example 6

Project: pushbullet.py
Source File: pushbullet.py
View license
    def remove_chat(self, chat):
        iden = chat.iden
        r = self._session.delete("{}/{}".format(self.CHATS_URL, iden))
        if r.status_code == requests.codes.ok:
            self.chats.remove(chat)
            return True
        else:
            raise PushbulletError(r.text)

Example 7

Project: pushbullet.py
Source File: pushbullet.py
View license
    def get_pushes(self, modified_after=None, limit=None, filter_inactive=True):
        data = {"modified_after": modified_after, "limit": limit}
        if filter_inactive:
            data['active'] = "true"

        pushes_list = []
        get_more_pushes = True
        while get_more_pushes:
            r = self._session.get(self.PUSH_URL, params=data)
            if r.status_code != requests.codes.ok:
                raise PushbulletError(r.text)

            pushes_list += r.json().get("pushes")
            if 'cursor' in r.json() and (not limit or len(pushes_list) < limit):
                data['cursor'] = r.json()['cursor']
            else:
                get_more_pushes = False

        return pushes_list

Example 8

Project: pushbullet.py
Source File: pushbullet.py
View license
    def dismiss_push(self, iden):
        data = {"dismissed": True}
        r = self._session.post("{}/{}".format(self.PUSH_URL, iden), data=json.dumps(data))

        if r.status_code != requests.codes.ok:
            raise PushbulletError(r.text)

Example 9

Project: pushbullet.py
Source File: pushbullet.py
View license
    def upload_file(self, f, file_name, file_type=None):
        if not file_type:
            file_type = get_file_type(f, file_name)

        data = {"file_name": file_name, "file_type": file_type}

        # Request url for file upload
        r = self._session.post(self.UPLOAD_REQUEST_URL, data=json.dumps(data))

        if r.status_code != requests.codes.ok:
            raise PushbulletError(r.text)

        upload_data = r.json().get("data")
        file_url = r.json().get("file_url")
        upload_url = r.json().get("upload_url")

        upload = requests.post(upload_url, data=upload_data, files={"file": f})

        return {"file_type": file_type, "file_url": file_url, "file_name": file_name}

Example 10

Project: pushbullet.py
Source File: pushbullet.py
View license
    def _push(self, data):
        r = self._session.post(self.PUSH_URL, data=json.dumps(data))

        if r.status_code == requests.codes.ok:
            return r.json()
        else:
            raise PushError(r.text)

Example 11

Project: s3ql
Source File: oauth_client.py
View license
def _parse_response(r):

    _log_response(r)
    if r.status_code != requests.codes.ok:
        raise QuietError('Connection failed with: %d %s'
                         % (r.status_code, r.reason))

    return r.json()

Example 12

Project: cookcountyjail
Source File: http.py
View license
    def get(self, url, number_attempts=_STD_NUMBER_ATTEMPTS, initial_sleep_period=_STD_INITIAL_SLEEP_PERIOD):
        attempt = 1
        sleep_period = initial_sleep_period
        while attempt <= number_attempts:
            gevent.sleep(sleep_period)
            try:
                request = grequests.get(url)
                grequests.map([request])
                if request.response is not None:
                    if request.response.status_code == requests.codes.ok:
                        return True, request.response.text
                else:
                    return False, BAD_URL_NETWORK_PROBLEM
            except requests.exceptions.RequestException:
                return False, BAD_URL_NETWORK_PROBLEM
            sleep_period = _get_next_sleep_period(sleep_period, attempt)
            attempt += 1
        return False, {'status-code': request.response.status_code}

Example 13

Project: maestro-ng
Source File: lifecycle.py
View license
    def _test_response(self, response):
        if self.match_regex:
            if getattr(response, 'text', None) and \
               self.match_regex.search(response.text):
                return True
        else:
            if response.status_code == requests.codes.ok:
                return True
        return False

Example 14

Project: geolocation-python
Source File: validators.py
View license
    def validate_response_status(self, response):
        """Method validates only request's response status."""
        self.status_code = response.status_code
        if self.status_code != requests.codes.ok:
            message = '%s %s' % (self.status_code, response.reason)
            raise ApiClientException(message)
        return self.status_code

Example 15

Project: tradewave-python
Source File: general.py
View license
def parse_response(response):
    """Analyses and parses JSON response"""
    # TODO: check for mime-type?
    # handle different response status codes
    if response.status_code == 400:
        data = parse_json(response.content)
        error = data.get('error', 'Unknown Error')
        raise ResponseError(error)
    elif response.status_code != requests.codes.ok:
        raise ResponseError(
            'Unexpected response status code: {code}, reason: {reason}'
            .format(code=response.status_code, reason=response.reason))

    # parse response into JSON
    if response.content:
        return parse_json(response.content)
    else:
        return ''

Example 16

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_get_ride_receipt(authorized_sandbox_client):
    """Test to fetch ride receipt with access token."""
    response = authorized_sandbox_client.get_ride_receipt(RIDE_ID)
    assert response.status_code == codes.ok

    # assert response looks like ride receipt
    response = response.json
    assert EXPECTED_RECEIPT_KEYS.issubset(response)
    charges = response.get('charges')

    for charge in charges:
        assert EXPECTED_INDIVIDUAL_CHARGE_KEYS.issubset(charge)

Example 17

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_set_home_address(authorized_sandbox_client):
    """Test to update a user's home address with an access token."""
    response = authorized_sandbox_client.set_home_address(HOME_ADDRESS)
    assert response.status_code == codes.ok

    # assert response looks like places details
    response = response.json
    assert EXPECTED_PLACE_KEYS.issubset(response)
    assert response.get('address') == FULL_HOME_ADDRESS

Example 18

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_get_home_address(authorized_sandbox_client):
    """Test to fetch a user's home address with an access token."""
    response = authorized_sandbox_client.get_home_address()
    assert response.status_code == codes.ok

    # assert response looks like places details
    response = response.json
    assert EXPECTED_PLACE_KEYS.issubset(response)
    assert response.get('address') == FULL_HOME_ADDRESS

Example 19

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_set_work_address(authorized_sandbox_client):
    """Test to update a user's work address with an access token."""
    response = authorized_sandbox_client.set_work_address(WORK_ADDRESS)
    assert response.status_code == codes.ok

    # assert response looks like places details
    response = response.json
    assert EXPECTED_PLACE_KEYS.issubset(response)
    assert response.get('address') == FULL_WORK_ADDRESS

Example 20

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_get_work_address(authorized_sandbox_client):
    """Test to fetch a user's work address with an access token."""
    response = authorized_sandbox_client.get_work_address()
    assert response.status_code == codes.ok

    # assert response looks like places details
    response = response.json
    assert EXPECTED_PLACE_KEYS.issubset(response)
    assert response.get('address') == FULL_WORK_ADDRESS

Example 21

Project: rides-python-sdk
Source File: test_client.py
View license
@uber_vcr.use_cassette()
def test_get_payment_methods(authorized_sandbox_client):
    """Test to get a list of payment methods with an access token."""
    response = authorized_sandbox_client.get_payment_methods()
    assert response.status_code == codes.ok

    response = response.json
    payments = response.get('payment_methods')

    for payment in payments:
        assert EXPECTED_PAYMENT_KEYS.issubset(payment)

Example 22

Project: pyvcloud
Source File: score.py
View license
    def delete(self, blueprint_id):
        self.score.response = Http.delete(self.score.url +
                                          '/blueprints/%s' % blueprint_id,
                                          headers=self.score.get_headers(),
                                          verify=self.score.verify,
                                          logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 23

Project: pyvcloud
Source File: score.py
View license
    def list(self):
        self.score.response = Http.get(self.score.url + '/deployments',
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 24

Project: pyvcloud
Source File: score.py
View license
    def get(self, deployment_id):
        self.score.response = Http.get(self.score.url +
                                       '/deployments/%s' % deployment_id,
                                       headers=self.score.get_headers(),
                                       verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 25

Project: pyvcloud
Source File: score.py
View license
    def delete(self, deployment_id, force_delete=False):

        self.score.response = Http.delete(
            self.score.url + '/deployments/%s' % deployment_id,
            params={"ignore_live_nodes": force_delete},
            headers=self.score.get_headers(),
            verify=self.score.verify,
            logger=self.logger)

        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 26

Project: pyvcloud
Source File: score.py
View license
    def outputs(self, deployment_id):
        headers = self.score.get_headers()
        self.score.response = Http.get(self.score.url +
                                       '/deployments/%s/outputs'
                                       % deployment_id,
                                       headers=headers,
                                       verify=self.score.verify,
                                       logger=self.logger)

        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 27

Project: pyvcloud
Source File: score.py
View license
    def list(self, deployment_id):
        params = {'deployment_id': deployment_id}
        self.score.response = Http.get(self.score.url + '/executions',
                                       headers=self.score.get_headers(),
                                       params=params, verify=self.score.verify,
                                       logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            Log.error(self.logger, 'list executions returned %s' %
                      self.score.response.status_code)
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 28

Project: pyvcloud
Source File: score.py
View license
    def start(self, deployment_id, workflow_id, parameters=None,
              allow_custom_parameters=False, force=False):
        data = {
            'deployment_id': deployment_id,
            'workflow_id': workflow_id,
            'parameters': parameters,
            'allow_custom_parameters': allow_custom_parameters,
            'force': force,
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.post(self.score.url + '/executions',
                                        headers=headers,
                                        data=json.dumps(data),
                                        verify=self.score.verify,
                                        logger=self.logger)
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 29

Project: pyvcloud
Source File: score.py
View license
    def cancel(self, execution_id, force=False):
        data = {
            'execution_id': execution_id,
            'force': force
        }
        headers = self.score.get_headers()
        headers['Content-type'] = 'application/json'
        self.score.response = Http.post(
            self.score.url + '/executions/' + execution_id,
            headers=headers, data=json.dumps(data),
            verify=self.score.verify,
            logger=self.logger
        )
        if self.score.response.status_code != requests.codes.ok:
            raise exceptions.from_response(self.score.response)
        return json.loads(self.score.response.content)

Example 30

Project: onedrive-d-old
Source File: od_onedrive_api.py
View license
	def get_user_info(self, user_id='me'):
		while True:
			try:
				r = self.http_client.get(OneDriveAPI.API_URI + user_id)
				return self.parse_response(r, OneDriveAPIException, requests.codes.ok)
			except OneDriveAuthError:
				self.auto_recover_auth_error()
			except requests.exceptions.ConnectionError:
				self.logger.info('network connection error.')
				self.threadman.hang_caller()

Example 31

Project: onedrive-d-old
Source File: od_onedrive_api.py
View license
	def get_contact_list(self, user_id='me'):
		while True:
			try:
				r = self.http_client.get(OneDriveAPI.API_URI + user_id + '/friends')
				return self.parse_response(r, OneDriveAPIException, requests.codes.ok)
			except OneDriveAuthError:
				self.auto_recover_auth_error()
			except requests.exceptions.ConnectionError:
				self.logger.info('network connection error.')
				self.threadman.hang_caller()

Example 32

Project: bravado
Source File: client_test.py
View license
    @httpretty.activate
    def test_post_and_optional_params(self):
        httpretty.register_uri(
            httpretty.POST, "http://swagger.py/swagger-test/pet",
            status=requests.codes.ok,
            body='"Spark is born"')

        resp = self.uut.pet.createPet(
            name='Sparky', birthday=datetime.date(2014, 1, 2)).result()
        self.assertEqual('Spark is born', resp)
        self.assertEqual({'name': ['Sparky'], 'birthday': ['2014-01-02']},
                         httpretty.last_request().querystring)
        resp = self.uut.pet.createPet(name='Sparky').result()
        self.assertEqual('Spark is born', resp)
        self.assertEqual({'name': ['Sparky']},
                         httpretty.last_request().querystring)

Example 33

Project: virustotal-api
Source File: api.py
View license
def _return_response_and_status_code(response):
    """ Output the requests response JSON and status code

    :rtype : dict
    :param response: requests response object
    :return: dict containing the JSON response and/or the status code with error string.
    """
    if response.status_code == requests.codes.ok:
        return dict(results=response.json(), response_code=response.status_code)
    elif response.status_code == 204:
        return dict(error='You exceeded the public API request rate limit (4 requests of any nature per minute)',
                    response_code=response.status_code)
    elif response.status_code == 403:
        return dict(error='You tried to perform calls to functions for which you require a Private API key.',
                    response_code=response.status_code)
    else:
        return dict(response_code=response.status_code)

Example 34

Project: python-furs-fiscal
Source File: base_api.py
View license
    def is_server_accessible(self):
        """
        Check if FURS server is accessible. Will return False if server responds with anything else
        than HTTP Code: 200 or if the request timeouts.

        :return: (boolean) True for ok, False if there was a problem accessing server.
        """
        try:
            return self.connector.send_echo().status_code == codes.ok
        except Timeout as e:
            return False

Example 35

Project: osf.io
Source File: utils.py
View license
    def call_get(self, service, params=None):
        """ Calls a GET API for the given service name and URL parameters."""
        url = self.build_url(service)
        r = self.oauth.get(url, params=params)
        if r.status_code != requests.codes.ok:
            raise DeskError('Desk error', r.status_code, r.content)
        return r.json()  # json.loads(r.content)

Example 36

Project: tile-generator
Source File: opsmgr.py
View license
def check_response(response, check=True):
	if check and response.status_code != requests.codes.ok:
		print('-', response.status_code, response.request.url, file=sys.stderr)
		try:
			errors = response.json()["errors"]
			print('- '+('\n- '.join(json.dumps(errors, indent=4).splitlines())), file=sys.stderr)
		except:
			print(response.text, file=sys.stderr)
		sys.exit(1)

Example 37

Project: tile-generator
Source File: opsmgr.py
View license
def get_version():
	# 1.7 and 1.8 have version in the diagnostic report.
	response = get('/api/v0/diagnostic_report', check=False)
	if response.status_code == requests.codes.ok:
		diag = response.json()
		version = diag['versions']['release_version']
		return [ int(x) for x in version.split('.') ]
	# 1.6 (and maybe earlier?) has the version in the p-bosh (Ops Manager Director) product.
	products = get('/api/products').json()
	for product in products:
		if product['name'] == 'p-bosh':
			version = product['product_version']
			return [ int(x) for x in version.split('.') ]
	print('Error: could not determine Ops Manager version.', file=sys.stderr)
	sys.exit(1)

Example 38

Project: jiaowu
Source File: base.py
View license
    def get(self, url, **kwargs):
        r = self.session.get(url, **kwargs)
        if r.status_code == requests.codes.ok:
            r.encoding = self.get_encoding_from_reponse(r)
            return r
        else:
            raise CollegeJiaowuRequestException(r.status_code, 'get url error: ' + url)

Example 39

Project: jiaowu
Source File: base.py
View license
    def post(self, url, data=None, json=None, **kwargs):
        r = self.session.post(url, data=data, json=json, **kwargs)
        if r.status_code == requests.codes.ok:
            r.encoding = self.get_encoding_from_reponse(r)
            return r
        else:
            raise CollegeJiaowuRequestException(r.status_code, 'post url error: ' + url)

Example 40

Project: zeroclickinfo-fathead
Source File: fetch.py
View license
def download_package_dict(package_name):
    """Download the given package, returning the response's JSON as a dict or None if an error occurred."""

    global download_count, not_found_count

    download_count += 1
    if download_count % 1000 == 0:
        logger.info('Downloaded %s packages (%s not found)', download_count, not_found_count)

    response = session.get('https://pypi.python.org/pypi/%s/json' % package_name)
    if response.status_code == requests.codes.ok:
        return response.json()
    elif response.status_code == requests.codes.not_found:
        not_found_count += 1
    else:
        logger.warning('Unexpected error code for package %s: %s', package_name, response.status_code)

Example 41

Project: eulexistdb
Source File: db.py
View license
    def getDocument(self, name):
        """Retrieve a document from the database.

        :param name: database document path to retrieve
        :rtype: string contents of the document

        """
        # REST api; need an error wrapper?
        logger.debug('getDocument %s', self.restapi_path(name))
        response = self.session.get(self.restapi_path(name), stream=False,
                                    **self.session_opts)
        if response.status_code == requests.codes.ok:
            return response.content
        if response.status_code == requests.codes.not_found:
            # matching previous xmlrpc behavior;
            # TODO: use custom exception classes here
            raise ExistDBException('%s not found' % name)

Example 42

Project: eulfedora
Source File: api.py
View license
    def setDatastreamState(self, pid, dsID, dsState):
        '''Update datastream state.

        :param pid: object pid
        :param dsID: datastream id
        :param dsState: datastream state
        :returns: boolean success
        '''
        # /objects/{pid}/datastreams/{dsID} ? [dsState]
        http_args = {'dsState' : dsState}
        url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID}
        response = self.put(url, params=http_args)
        # returns response code 200 on success
        return response.status_code == requests.codes.ok

Example 43

Project: eulfedora
Source File: api.py
View license
    def setDatastreamVersionable(self, pid, dsID, versionable):
        '''Update datastream versionable setting.

        :param pid: object pid
        :param dsID: datastream id
        :param versionable: boolean
        :returns: boolean success
        '''
        # /objects/{pid}/datastreams/{dsID} ? [versionable]
        http_args = {'versionable': versionable}
        url = 'objects/%(pid)s/datastreams/%(dsid)s' % {'pid': pid, 'dsid': dsID}
        response = self.put(url, params=http_args)
        # returns response code 200 on success
        return response.status_code == requests.codes.ok

Example 44

Project: eulfedora
Source File: server.py
View license
    def purge_object(self, pid, log_message=None):
        """
        Purge an object from Fedora.  Calls :meth:`ApiFacade.purgeObject`.

        :param pid: pid of the object to be purged
        :param log_message: optional log message
        :rtype: boolean
        """
        kwargs = {'pid': pid}
        if log_message:
            kwargs['logMessage'] = log_message
        response = self.api.purgeObject(**kwargs)
        return response.status_code == requests.codes.ok

Example 45

Project: eulfedora
Source File: test_api.py
View license
    def test_purgeObject(self):
        obj = load_fixture_data('basic-object.foxml')
        r = self.rest_api.ingest(obj)
        pid = r.text
        r = self.rest_api.purgeObject(pid)
        purged = (r.status_code == requests.codes.ok)
        self.assertTrue(purged)

        # NOTE: fedora doesn't notice the object has been purged right away
        sleep(7)    # 5-6 was fastest this worked; padding to avoid spurious failures
        self.assertRaises(Exception, self.rest_api.getObjectProfile, pid)

        # bad pid
        self.assertRaises(RequestFailed, self.rest_api.purgeObject, "bogus:pid")

Example 46

Project: dftools
Source File: dftlib.py
View license
def download_file(url, path_file):
    """ Download a file. """

    raw_file, status_code = get_url(url)

    if status_code == requests.codes.ok:
        with open(path_file, "wb") as archive:
            archive.write(raw_file)

Example 47

Project: eo-python
Source File: eo.py
View license
    def set_url(self, url):
        """Display the given URL on the first device associated with the signed-in user.
        Return True on success.
        """
        devs = self.devices()
        if not devs:
            self.logger.error("in set_url: no devices returned.")
            return 0
        device_index = 0  # First device of user.
        device_id = devs[device_index]["id"]

        request_url = self.api.base_url + "set_url"
        params = {
          "device_id": device_id,
          "custom_url": url
        }
        response = self.api.net.post_with_authenticity(request_url, params)
        return response.status_code == requests.codes.ok

Example 48

View license
    @staticmethod
    def get_response(response):
        if response.status_code != requests.codes.ok:
            return {}
        result = response.json()
        if result['code'] != 0:
            raise Iamport.ResponseError(result.get('code'), result.get('message'))
        return result.get('response')

Example 49

Project: inasafe
Source File: test_push_rest.py
View license
    def test_login(self):
        headers = {
            'X-CSRFTOKEN': self.inasafe_django.csrf_token
        }
        r = self.inasafe_django.rest.is_logged_in.GET(headers=headers)
        self.assertEqual(r.status_code, codes.ok)
        self.assertTrue(r.json().get('is_logged_in'))

Example 50

Project: python_tutorial
Source File: outlookservice.py
View license
def get_me(access_token):
  get_me_url = outlook_api_endpoint.format('/Me')

  # Use OData query parameters to control the results
  #  - Only return the DisplayName and EmailAddress fields
  query_parameters = {'$select': 'DisplayName,EmailAddress'}

  r = make_api_call('GET', get_me_url, access_token, "", parameters = query_parameters)

  if (r.status_code == requests.codes.ok):
    return r.json()
  else:
    return "{0}: {1}".format(r.status_code, r.text)