Python httplib.CREATED Examples

The following are 8 code examples of httplib.CREATED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httplib , or try the search function .
Example #1
Source File: api.py    From cascade-server with Apache License 2.0 6 votes vote down vote up
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) 
Example #2
Source File: client.py    From pykit with MIT License 5 votes vote down vote up
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)) 
Example #3
Source File: client.py    From pykit with MIT License 5 votes vote down vote up
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) 
Example #4
Source File: brightcove.py    From xblock-video with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #5
Source File: brightcove.py    From xblock-video with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #6
Source File: proxy.py    From ryu with Apache License 2.0 5 votes vote down vote up
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()) 
Example #7
Source File: stub_dispatcher.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
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, '') 
Example #8
Source File: api.py    From cascade-server with Apache License 2.0 4 votes vote down vote up
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