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


Python httplib.CREATED屬性代碼示例

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


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

示例1: create_user

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def create_user():
    if not settings.load()['config'].get('allow_account_creation', False):
        return JSONResponse(status=httplib.FORBIDDEN)

    """ This API route is used by the create new account template to add a new user into Mongo """
    if isinstance(request.json, dict):
        args = request.json
        if args.get('username') and args.get('password'):
            try:
                user = users.create_user(args['username'], args['password'], args.get('email'), args.get('full_name'))
            except users.PasswordPolicyError as error:
                regex, rules = error.args
                return JSONResponse({'violation': {'regex': regex, 'rules': rules}}, httplib.BAD_REQUEST)

            if user is not None:
                response = Response(status=httplib.CREATED)
                response.set_cookie('user-token', user.generate_token(), max_age=datetime.timedelta(days=7))
                return response
            else:
                return JSONResponse({'message': 'Username already exists!'}, status=httplib.BAD_REQUEST)

    return JSONResponse({'message': 'Username, email and password are required'}, status=httplib.BAD_REQUEST) 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:24,代碼來源:api.py

示例2: parse_response

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def parse_response(self, response):

        if response.status == httplib.CREATED:
            self.newKey = True

        headers = response.headers
        self.etcd_index = int(headers.get('x-etcd-index', 1))
        self.raft_index = int(headers.get('x-raft-index', 1))
        self.raft_term = int(headers.get('x-raft-term', 0)) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:11,代碼來源:client.py

示例3: _handle_server_response

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def _handle_server_response(self, response):

        if response.status in (httplib.OK, httplib.CREATED,
                               httplib.NO_CONTENT):
            return response

        logger.debug('invalid response status:{st} body:{body}'.format(
                     st=response.status, body=response.data))

        EtcdError.handle(response) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:12,代碼來源:client.py

示例4: create_credentials

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def create_credentials(token, account_id):
        """
        Get client credentials, given a client token and an account_id.

        Reference:
            https://docs.brightcove.com/en/video-cloud/oauth-api/guides/get-client-credentials.html
        """
        headers = {'Authorization': 'BC_TOKEN {}'.format(token)}
        data = {
            "type": "credential",
            "maximum_scope": [{
                "identity": {
                    "type": "video-cloud-account",
                    "account-id": int(account_id),
                },
                "operations": [
                    "video-cloud/video/all",
                    "video-cloud/ingest-profiles/profile/read",
                    "video-cloud/ingest-profiles/account/read",
                    "video-cloud/ingest-profiles/profile/write",
                    "video-cloud/ingest-profiles/account/write",
                ],
            }],
            "name": "Open edX Video XBlock"
        }
        url = 'https://oauth.brightcove.com/v4/client_credentials'
        response = requests.post(url, json=data, headers=headers)
        response_data = response.json()
        # New resource must have been created.
        if response.status_code == httplib.CREATED and response_data:
            client_secret = response_data.get('client_secret')
            client_id = response_data.get('client_id')
            error_message = ''
        else:
            # For dev purposes, response_data.get('error_description') may also be considered.
            error_message = "Authentication to Brightcove API failed: no client credentials have been retrieved.\n" \
                            "Please ensure you have provided an appropriate BC token, using Video API Token field."
            raise BrightcoveApiClientError(error_message)
        return client_secret, client_id, error_message 
開發者ID:appsembler,項目名稱:xblock-video,代碼行數:41,代碼來源:brightcove.py

示例5: post

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

        Arguments:
            url (str): API url to fetch a resource from.
            payload (dict): POST data.
            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 ' + self.access_token,
            'Content-type': 'application/json'
        }
        if headers is not None:
            headers_.update(headers)

        resp = requests.post(url, data=payload, headers=headers_)
        log.debug("BC response status: {}".format(resp.status_code))
        if resp.status_code in (httplib.OK, httplib.CREATED):
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.post(url, payload, headers, can_retry=False)

        try:
            resp_dict = resp.json()[0]
            log.warn("API error code: %s - %s", resp_dict.get(u'error_code'), resp_dict.get(u'message'))
        except (ValueError, IndexError):
            message = _("Can't parse unexpected response during POST request to Brightcove API!")
            log.exception(message)
            resp_dict = {"message": message}
        return resp_dict 
開發者ID:appsembler,項目名稱:xblock-video,代碼行數:37,代碼來源:brightcove.py

示例6: _do_request

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def _do_request(address, path):
    conn = httplib.HTTPConnection(address)
    conn.request('GET', path)
    res = conn.getresponse()
    if res.status in (httplib.OK,
                      httplib.CREATED,
                      httplib.ACCEPTED,
                      httplib.NO_CONTENT):
        return res

    raise httplib.HTTPException(
        res, 'code %d reason %s' % (res.status, res.reason),
        res.getheaders(), res.read()) 
開發者ID:OpenState-SDN,項目名稱:ryu,代碼行數:15,代碼來源:proxy.py

示例7: _handle_post

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def _handle_post(gcs_stub, filename, headers):
  """Handle POST that starts object creation."""
  content_type = _ContentType(headers)
  token = gcs_stub.post_start_creation(filename, headers)
  response_headers = {
      'location': 'https://storage.googleapis.com/%s?%s' % (
          urllib.quote(filename),
          urllib.urlencode({'upload_id': token})),
      'content-type': content_type.value,
      'content-length': 0
  }
  return _FakeUrlFetchResult(httplib.CREATED, response_headers, '') 
開發者ID:GoogleCloudPlatform,項目名稱:python-compat-runtime,代碼行數:14,代碼來源:stub_dispatcher.py

示例8: query_session

# 需要導入模塊: import httplib [as 別名]
# 或者: from httplib import CREATED [as 別名]
def query_session(session, user=None):
    """
    :type session: Session
    :type user: User
    """
    session_id = session
    session = Session.objects.with_id(session)

    if request.method == 'GET':
        if session:
            return session, httplib.OK
        return None, httplib.NOT_FOUND

    elif request.method == 'PUT':
        # Create a new session if it doesn't exist
        if not session:
            session = Session(id=session_id)
            http_status = httplib.CREATED
        else:
            http_status = httplib.OK

        try:
            session.update(**request.json)
            session.validate()
        except mongoengine.ValidationError:
            return {'error': 'schema validation error'}, httplib.BAD_REQUEST

        session.save()
        return None, http_status

    elif request.method == 'POST':
        if 'reset' in request.args:
            DataModelEvent.objects(sessions=session).update(pull__sessions=session)
            AnalyticResult.objects(session=session).delete()
            Job.objects(session=session).delete()
            # Remove the session state
            session.update(state=SessionState())
            # Is this the right http error code?
            return None, httplib.RESET_CONTENT

        elif 'refresh' in request.args:
            for analytic_state in session.state.analytics:
                job = AnalyticJob.update_existing(analytic=analytic_state.analytic, mode=analytic_state.mode, user=user, session=session)
                job.submit()
            return None, httplib.RESET_CONTENT

    # TODO: Implement
    elif request.method == 'DELETE':
        DataModelEvent.objects(sessions=session).update(pull__sessions=session)
        AnalyticResult.objects(session=session).delete()
        Job.objects(session=session).delete()
        session.delete()
        return None, httplib.NO_CONTENT 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:55,代碼來源:api.py


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