當前位置: 首頁>>代碼示例>>Python>>正文


Python httplib.OK屬性代碼示例

本文整理匯總了Python中httplib.OK屬性的典型用法代碼示例。如果您正苦於以下問題:Python httplib.OK屬性的具體用法?Python httplib.OK怎麽用?Python httplib.OK使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在httplib的用法示例。


在下文中一共展示了httplib.OK屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_get

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def test_get(
      self, mock_config, mock_urlfetch, mock_app_identity, mock_logging):
    test_destination_url = cloud_datastore_export._DESTINATION_URL
    test_bucket_name = 'gcp_bucket_name'
    mock_config.side_effect = [test_bucket_name, True]
    expected_url = (
        cloud_datastore_export._DATASTORE_API_URL % self.test_application_id)
    mock_urlfetch.return_value.status_code = httplib.OK
    now = datetime.datetime(
        year=2017, month=1, day=1, hour=1, minute=1, second=15)
    with freezegun.freeze_time(now):
      self.testapp.get(self._CRON_URL)
      mock_urlfetch.assert_called_once_with(
          url=expected_url,
          payload=json.dumps({
              'project_id': self.test_application_id,
              'output_url_prefix': test_destination_url.format(
                  test_bucket_name, now.strftime('%Y_%m_%d-%H%M%S'))
          }),
          method=urlfetch.POST,
          deadline=60,
          headers={
              'Content-Type': 'application/json',
              'Authorization': 'Bearer mock_token'})
      self.assertEqual(mock_logging.call_count, 3) 
開發者ID:google,項目名稱:loaner,代碼行數:27,代碼來源:cloud_datastore_export_test.py

示例2: do_POST

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def do_POST(self):
    """Handles a single API request e.g. memcache.Get()."""
    self.send_response(httplib.OK)
    self.send_header('Content-Type', 'application/octet-stream')
    self.end_headers()

    response = remote_api_pb.Response()
    try:
      request = remote_api_pb.Request()



      request.ParseFromString(
          self.rfile.read(int(self.headers['content-length'])))
      api_response = _ExecuteRequest(request).Encode()
      response.set_response(api_response)
    except Exception, e:
      logging.debug('Exception while handling %s\n%s',
                    request,
                    traceback.format_exc())
      response.set_exception(pickle.dumps(e))
      if isinstance(e, apiproxy_errors.ApplicationError):
        application_error = response.mutable_application_error()
        application_error.set_code(e.application_error)
        application_error.set_detail(e.error_detail) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:27,代碼來源:api_server.py

示例3: query_job

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def query_job(job, user=None):
    """
    :type job: Job
    :type user: User
    """
    job = Job.objects.with_id(job), httplib.OK
    if job is None:
        return None, httplib.NOT_FOUND

    if request.method == 'GET':
        return job, httplib.OK

    elif request.method == 'POST':
        return job.modify(**request.json), httplib.OK

    elif job and request.method == 'DELETE':
        job.delete()
        return None, httplib.OK 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:20,代碼來源:api.py

示例4: automate_session

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def automate_session(session, user=None):
    """
    :type session: cascade.session.Session
    :type user: User
    """
    session = Session.objects.with_id(session)
    if not session:
        return None, httplib.NOT_FOUND

    if isinstance(request.json, dict):
        if request.json.get('analytics') is not None:
            requested_analytics = request.json['analytics']

            for requested_analytic in requested_analytics:
                analytic = Analytic.objects.with_id(requested_analytic['_id'])
                if analytic:
                    mode = requested_analytic.get('mode', analytic.mode)
                    config = AnalyticConfiguration(analytic=analytic, mode=mode)
                    session.update(add_to_set__state__analytics=config)
                    job = AnalyticJob.update_existing(analytic=analytic, user=user, session=session, mode=mode)
                    job.submit()
            return len(requested_analytics), httplib.OK

    return 0, httplib.BAD_REQUEST 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:26,代碼來源:api.py

示例5: submit_analytic

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def submit_analytic(user=None):
    if 'update_many' in request.args:
        if isinstance(request.json, dict) and request.json.get('analytics') is not None:
            count = 0
            for content in request.json['analytics']:
                _id = content.pop('_id', None)
                analytic = Analytic.objects.with_id(_id)
                if analytic is not None:
                    count += analytic.update(**content)

            return Analytic.objects(), httplib.OK
        return {}, httplib.BAD_REQUEST

    # creating a new analytic
    else:
        if request.json.get('platform', 'CASCADE') == 'CASCADE':
            analytic = CascadeAnalytic._from_son(request.json)
        else:
            analytic = ExternalAnalytic._from_son(request.json)
        analytic.save()

    return analytic.id, httplib.OK 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:24,代碼來源:api.py

示例6: make_query

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def make_query():
    try:
        query = parser.generate_query(request.json['query'])
        event_type, action = DataModelQueryLayer.get_data_model(query)
        return {'object': event_type.object_name, 'action': action, 'query': query}, httplib.OK

    except InvalidFieldError:
        return {'error': 'Invalid Data Model field in query'}, httplib.BAD_REQUEST

    except InvalidActionError:
        return {'error': 'Invalid Data Model action in query'}, httplib.BAD_REQUEST

    except InvalidObjectError:
        return {'error': 'Invalid Data Model object in query'}, httplib.BAD_REQUEST

    except parser.ParserError:
        return {'error': 'Unable to parse query'}, httplib.BAD_REQUEST 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:19,代碼來源:api.py

示例7: query_baselines

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def query_baselines(user=None):
    if request.method == 'GET':
        return AnalyticBaseline.objects(), httplib.OK

    elif request.method == 'POST':
        if isinstance(request.json, dict):
            if request.json.get('analytics') is not None and request.json.get('time') is not None:
                requested_analytics = request.json.get('analytics', [])
                time_range = DateRange.get_range(request.json['time'])

                count = 0
                for requested_analytic in requested_analytics:
                    analytic_id = requested_analytic.pop('_id', requested_analytic.get('id'))
                    analytic = Analytic.objects.with_id(analytic_id)

                    if analytic is None:
                        continue

                    job = TuningJob.update_existing(analytic=analytic, range=time_range, user=user)
                    job.submit()
                    count += 1
                return count, httplib.OK
    return [], httplib.BAD_REQUEST 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:25,代碼來源:api.py

示例8: _refresh_access_token

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def _refresh_access_token(self):
        """
        Request new access token to send with requests to Brightcove. Access Token expires every 5 minutes.
        """
        url = "https://oauth.brightcove.com/v3/access_token"
        params = {"grant_type": "client_credentials"}
        auth_string = base64.encodestring(
            '{}:{}'.format(self.api_key, self.api_secret)
        ).replace('\n', '')
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Basic " + auth_string
        }
        try:
            resp = requests.post(url, headers=headers, data=params)
            if resp.status_code == httplib.OK:
                result = resp.json()
                return result['access_token']
        except IOError:
            log.exception(_("Connection issue. Couldn't refresh API access token."))
            return None 
開發者ID:appsembler,項目名稱:xblock-video,代碼行數:23,代碼來源:brightcove.py

示例9: get

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def get(self, url, headers=None, can_retry=True):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in python native data format.
        """
        headers_ = {'Authorization': 'Bearer ' + str(self.access_token)}
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.get(url, headers, can_retry=False)
        else:
            raise BrightcoveApiClientError 
開發者ID:appsembler,項目名稱:xblock-video,代碼行數:24,代碼來源:brightcove.py

示例10: get

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def get(self, url, headers=None, can_retry=False):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform
            authorised requests.
        Returns:
            Response in python native data format.
        """
        headers_ = {
            'Authorization': 'Bearer {}'.format(self.access_token.encode(encoding='utf-8')),
            'Accept': 'application/json'
        }
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        else:
            raise VimeoApiClientError(_("Can't fetch requested data from API.")) 
開發者ID:appsembler,項目名稱:xblock-video,代碼行數:24,代碼來源:vimeo.py

示例11: _logout

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def _logout(self):
        """Posts a logout request to the server.

            Returns:
                str     -   response string from server upon logout success

        """
        flag, response = self.make_request('POST', self._commcell_object._services['LOGOUT'])

        if flag:
            self._commcell_object._headers['Authtoken'] = None

            if response.status_code == httplib.OK:
                return response.text
            else:
                return 'Failed to logout the user'
        else:
            return 'User already logged out' 
開發者ID:CommvaultEngg,項目名稱:cvpysdk,代碼行數:20,代碼來源:cvpysdk.py

示例12: autoscroll

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def autoscroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("autoscroll", (data["is_enabled"], float(data["interval"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys is_enabled and interval not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid data type(s)."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
開發者ID:pimoroni,項目名稱:scroll-phat-hd,代碼行數:19,代碼來源:http.py

示例13: scroll

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def scroll():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("scroll", (int(data["x"]), int(data["y"]))))
    except KeyError:
        response = {"result": "KeyError", "error": "keys x and y not posted."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except ValueError:
        response = {"result": "ValueError", "error": "invalid integer."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
開發者ID:pimoroni,項目名稱:scroll-phat-hd,代碼行數:19,代碼來源:http.py

示例14: flip

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def flip():
    response = {"result": "success"}
    status_code = http_status.OK

    data = request.get_json()
    if data is None:
        data = request.form
    try:
        api_queue.put(Action("flip", (bool(data["x"]), bool(data["y"]))))
    except TypeError:
        response = {"result": "TypeError", "error": "Could not cast data correctly. Both `x` and `y` must be set to true or false."}
        status_code = http_status.UNPROCESSABLE_ENTITY
    except KeyError:
        response = {"result": "KeyError", "error": "Could not cast data correctly. Both `x` and `y` must be in the posted json data."}
        status_code = http_status.UNPROCESSABLE_ENTITY

    return jsonify(response), status_code 
開發者ID:pimoroni,項目名稱:scroll-phat-hd,代碼行數:19,代碼來源:http.py

示例15: test_client_request_with_parameters

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import OK [as 別名]
def test_client_request_with_parameters(jedihttp):
    filepath = utils.fixture_filepath('goto.py')
    request_data = {
        'source': read_file(filepath),
        'line': 10,
        'col': 3,
        'source_path': filepath
    }

    response = requests.post(
        'http://127.0.0.1:{0}/gotodefinition'.format(PORT),
        json=request_data,
        auth=HmacAuth(SECRET))

    assert_that(response.status_code, equal_to(httplib.OK))

    hmachelper = hmaclib.JediHTTPHmacHelper(SECRET)
    assert_that(hmachelper.is_response_authenticated(response.headers,
                                                     response.content)) 
開發者ID:vheon,項目名稱:JediHTTP,代碼行數:21,代碼來源:end_to_end_test.py


注:本文中的httplib.OK屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。