Python http.HTTPStatus.CREATED Examples

The following are 30 code examples of http.HTTPStatus.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 http.HTTPStatus , or try the search function .
Example #1
Source File: test_service_bindings.py    From cf-python-client with Apache License 2.0 6 votes vote down vote up
def test_create(self):
        self.client.post.return_value = self.mock_response(
            '/v2/service_bindings',
            HTTPStatus.CREATED,
            None,
            'v2', 'service_bindings', 'POST_response.json')
        service_binding = self.client.v2.service_bindings.create('app_guid', 'instance_guid',
                                                                 dict(the_service_broker='wants this object'),
                                                                 'binding_name')
        self.client.post.assert_called_with(self.client.post.return_value.url,
                                            json=dict(app_guid='app_guid',
                                                      service_instance_guid='instance_guid',
                                                      name='binding_name',
                                                      parameters=dict(
                                                          the_service_broker='wants this object')))
        self.assertIsNotNone(service_binding) 
Example #2
Source File: test_service_instances.py    From cf-python-client with Apache License 2.0 6 votes vote down vote up
def test_create(self):
        self.client.post.return_value = self.mock_response(
            '/v2/service_instances',
            HTTPStatus.CREATED,
            None,
            'v2', 'service_instances', 'POST_response.json')
        service_instance = self.client.v2.service_instances.create('space_guid', 'name', 'plan_id',
                                                                   parameters=dict(
                                                                       the_service_broker="wants this object"),
                                                                   tags=['mongodb'],
                                                                   accepts_incomplete=True)
        self.client.post.assert_called_with(self.client.post.return_value.url,
                                            json=dict(name='name',
                                                      space_guid='space_guid',
                                                      service_plan_guid='plan_id',
                                                      parameters=dict(
                                                          the_service_broker="wants this object"),
                                                      tags=['mongodb']),
                                            params=dict(accepts_incomplete="true")
                                            )
        self.assertIsNotNone(service_instance) 
Example #3
Source File: schedule.py    From zimfarm with GNU General Public License v3.0 6 votes vote down vote up
def post(self, token: AccessToken.Payload):
        """create a new schedule"""

        try:
            document = ScheduleSchema().load(request.get_json())
        except ValidationError as e:
            raise InvalidRequestJSON(e.messages)

        # make sure it's not a duplicate
        if Schedules().find_one({"name": document["name"]}, {"name": 1}):
            raise BadRequest(
                "schedule with name `{}` already exists".format(document["name"])
            )

        document["duration"] = {"default": get_default_duration()}
        schedule_id = Schedules().insert_one(document).inserted_id

        return make_response(jsonify({"_id": str(schedule_id)}), HTTPStatus.CREATED) 
Example #4
Source File: main.py    From alembic-quickstart with MIT License 6 votes vote down vote up
def handle_create_user(request):
    """
    Handler, creates new user
    """
    data = await request.json()

    try:
        query = users_table.insert().values(
            email=data['email'],
            name=data.get('name'),
            gender=data.get('gender'),
            floor=data.get('floor'),
            seat=data.get('seat')
        ).returning(users_table)
        row = await request.app['pg'].fetchrow(query)
        return json_response(dict(row), status=HTTPStatus.CREATED)
    except NotNullViolationError:
        raise HTTPBadRequest() 
Example #5
Source File: test_domains.py    From cf-python-client with Apache License 2.0 6 votes vote down vote up
def test_share_domain(self):
        self.client.post.return_value = self.mock_response(
            '/v3/domains/domain_id/relationships/shared_organizations',
            HTTPStatus.CREATED,
            None,
            'v3', 'domains', 'POST_{id}_relationships_shared_organizations_response.json')
        result = self.client.v3.domains.share_domain('domain_id',
                                                     ToManyRelationship('organization-guid-1', 'organization-guid-2'))
        self.client.post.assert_called_with(self.client.post.return_value.url,
                                            files=None,
                                            json={
                                                'data': [
                                                    {'guid': 'organization-guid-1'},
                                                    {'guid': 'organization-guid-2'}
                                                ]
                                            })
        self.assertIsNotNone(result)
        self.assertIsInstance(result, ToManyRelationship)
        result.guids[0] = 'organization-guid-1'
        result.guids[1] = 'organization-guid-1' 
Example #6
Source File: test_drivers_microsoft.py    From cloudstorage with MIT License 6 votes vote down vote up
def test_container_generate_upload_url(container, binary_stream):
    form_post = container.generate_upload_url(
        blob_name="prefix_", **settings.BINARY_OPTIONS
    )
    assert "url" in form_post and "fields" in form_post
    assert uri_validator(form_post["url"])

    url = form_post["url"]
    headers = form_post["headers"]
    multipart_form_data = {
        "file": (settings.BINARY_FORM_FILENAME, binary_stream, "image/png"),
    }

    # https://blogs.msdn.microsoft.com/azureossds/2015/03/30/uploading-files-to-
    # azure-storage-using-sasshared-access-signature/
    response = requests.put(url, headers=headers, files=multipart_form_data)
    assert response.status_code == HTTPStatus.CREATED, response.text

    blob = container.get_blob("prefix_")
    assert blob.meta_data == settings.BINARY_OPTIONS["meta_data"]
    assert blob.content_type == settings.BINARY_OPTIONS["content_type"]
    assert blob.content_disposition == settings.BINARY_OPTIONS["content_disposition"]
    assert blob.cache_control == settings.BINARY_OPTIONS["cache_control"] 
Example #7
Source File: test_drivers_rackspace.py    From cloudstorage with MIT License 6 votes vote down vote up
def test_container_generate_upload_url(container, binary_stream):
    form_post = container.generate_upload_url(blob_name="prefix_")
    assert "url" in form_post and "fields" in form_post
    assert uri_validator(form_post["url"])

    url = form_post["url"]
    fields = form_post["fields"]
    multipart_form_data = {
        "file": (settings.BINARY_FORM_FILENAME, binary_stream, "image/png"),
    }
    response = requests.post(url, data=fields, files=multipart_form_data)
    assert response.status_code == HTTPStatus.CREATED, response.text

    blob = container.get_blob("prefix_" + settings.BINARY_FORM_FILENAME)
    # Options not supported: meta_data, content_disposition, and cache_control.
    assert blob.content_type == settings.BINARY_OPTIONS["content_type"] 
Example #8
Source File: users.py    From asgard-api with MIT License 6 votes vote down vote up
def create_user(wrapper: RequestWrapper):
    status_code = HTTPStatus.CREATED
    try:
        user = User(**await wrapper.http_request.json())
    except ValueError:
        return web.json_response(
            UserResource().dict(), status=HTTPStatus.BAD_REQUEST
        )

    try:
        created_user = await UsersService.create_user(user, UsersBackend())
    except DuplicateEntity as de:
        return web.json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(de))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )

    return web.json_response(
        UserResource(user=created_user).dict(), status=status_code
    ) 
Example #9
Source File: ch13_ex5.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 6 votes vote down vote up
def create_roll() -> Tuple[Any, HTTPStatus, Dict[str, Any]]:
    body = request.get_json(force=True)
    if set(body.keys()) != {"dice"}:
        raise BadRequest(f"Extra fields in {body!r}")
    try:
        n_dice = int(body["dice"])
    except ValueError as ex:
        raise BadRequest(f"Bad 'dice' value in {body!r}")

    roll = [random.randint(1, 6) for _ in range(n_dice)]
    identifier = secrets.token_urlsafe(8)
    SESSIONS[identifier] = roll
    current_app.logger.info(f"Rolled roll={roll!r}, id={identifier!r}")

    headers = {"Location": url_for("roll.get_roll", identifier=identifier)}
    return jsonify(
        roll=roll, identifier=identifier, status="Created"
    ), HTTPStatus.CREATED, headers 
Example #10
Source File: rackspace.py    From cloudstorage with MIT License 5 votes vote down vote up
def disable_container_cdn(self, container: Container) -> bool:
        endpoint_url = (
            self._get_server_public_url("cloudFilesCDN") + "/" + container.name
        )
        headers = {
            "X-Auth-Token": self._token,
            "X-CDN-Enabled": str(False),
        }

        response = requests.put(endpoint_url, headers=headers)
        return response.status_code in (
            HTTPStatus.CREATED,
            HTTPStatus.ACCEPTED,
            HTTPStatus.NO_CONTENT,
        ) 
Example #11
Source File: test_apps.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_update(self):
        self.client.put.return_value = self.mock_response(
            '/v2/apps/app_id',
            HTTPStatus.CREATED,
            None,
            'v2', 'apps', 'PUT_{id}_response.json')
        application = self.client.v2.apps.update('app_id', stack_guid='82f9c01c-72f2-4d3e-b5ed-eab97a6203cf',
                                                 memory=1024,
                                                 instances=1, disk_quota=1024, health_check_type="port")
        self.client.put.assert_called_with(self.client.put.return_value.url,
                                           json=dict(stack_guid='82f9c01c-72f2-4d3e-b5ed-eab97a6203cf', memory=1024,
                                                     instances=1, disk_quota=1024, health_check_type="port"))
        self.assertIsNotNone(application) 
Example #12
Source File: test_apps.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_main_restage_app(self):
        with patch('cloudfoundry_client.main.main.build_client_from_configuration',
                   new=lambda: self.client):
            self.client.post.return_value = self.mock_response('/v2/apps/906775ea-622e-4bc7-af5d-9aab3b652f81/restage',
                                                               HTTPStatus.CREATED,
                                                               None,
                                                               'v2', 'apps', 'POST_{id}_restage_response.json')
            main.main()
            self.client.post.assert_called_with(self.client.post.return_value.url, json=None) 
Example #13
Source File: test_buildpacks.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_update(self):
        self.client.put.return_value = self.mock_response(
            '/v2/buildpacks/build_pack_id',
            HTTPStatus.CREATED,
            None,
            'v2', 'apps', 'PUT_{id}_response.json')
        result = self.client.v2.buildpacks.update('build_pack_id', dict(enabled=False))
        self.client.put.assert_called_with(self.client.put.return_value.url,
                                           json=dict(enabled=False))
        self.assertIsNotNone(result) 
Example #14
Source File: test_tasks.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_create(self):
        self.client.post.return_value = self.mock_response(
            '/v3/apps/app_guid/tasks',
            HTTPStatus.CREATED,
            None,
            'v3', 'tasks', 'POST_response.json')
        task = self.client.v3.tasks.create('app_guid', command='rake db:migrate')
        self.client.post.assert_called_with(self.client.post.return_value.url,
                                            files=None,
                                            json=dict(command='rake db:migrate'))
        self.assertIsNotNone(task) 
Example #15
Source File: test_tasks.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_cancel_task(self):
        with patch('cloudfoundry_client.main.main.build_client_from_configuration',
                   new=lambda: self.client):
            self.client.post.return_value = self.mock_response('/v3/tasks/task_id/actions/cancel',
                                                               HTTPStatus.CREATED,
                                                               None,
                                                               'v3', 'tasks', 'POST_{id}_actions_cancel_response.json')
            main.main()
            self.client.post.assert_called_with(self.client.post.return_value.url, files=None, json=None) 
Example #16
Source File: ch13_ex3.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 5 votes vote down vote up
def make_dice(n_dice: int) -> Dice:
    # Could also be a @classmethod
    return Dice(
        roll=[random.randint(1, 6) for _ in range(n_dice)],
        identifier=secrets.token_urlsafe(8),
        status=Status.CREATED,
    )


# FLASK Restful Web Service
# ========================= 
Example #17
Source File: ch13_ex3.py    From Mastering-Object-Oriented-Python-Second-Edition with MIT License 5 votes vote down vote up
def make_roll() -> Tuple[Dict[str, Any], HTTPStatus, Dict[str, str]]:
    body = request.get_json(force=True)
    if set(body.keys()) != {"dice"}:
        raise BadRequest(f"Extra fields in {body!r}")
    try:
        n_dice = int(body["dice"])
    except ValueError as ex:
        raise BadRequest(f"Bad 'dice' value in {body!r}")

    dice = make_dice(n_dice)
    SESSIONS[dice.identifier] = dice
    current_app.logger.info(f"Rolled roll={dice!r}")

    headers = {"Location": url_for("rolls.get_roll", identifier=dice.identifier)}
    return jsonify(asdict(dice)), HTTPStatus.CREATED, headers 
Example #18
Source File: rackspace.py    From cloudstorage with MIT License 5 votes vote down vote up
def enable_container_cdn(self, container: Container) -> bool:
        endpoint_url = (
            self._get_server_public_url("cloudFilesCDN") + "/" + container.name
        )
        headers = {
            "X-Auth-Token": self._token,
            "X-CDN-Enabled": str(True),
        }

        response = requests.put(endpoint_url, headers=headers)
        return response.status_code in (
            HTTPStatus.CREATED,
            HTTPStatus.ACCEPTED,
            HTTPStatus.NO_CONTENT,
        ) 
Example #19
Source File: test_apps.py    From cf-python-client with Apache License 2.0 5 votes vote down vote up
def test_stop(self):
        self.client.put.return_value = self.mock_response(
            '/v2/apps/app_id',
            HTTPStatus.CREATED,
            None,
            'v2', 'apps', 'PUT_{id}_response.json')
        self.client.get.side_effect = [InvalidStatusCode(HTTPStatus.BAD_REQUEST, dict(code=220001))]
        application = self.client.v2.apps.stop('app_id')
        self.client.put.assert_called_with(self.client.put.return_value.url,
                                           json=dict(state='STOPPED'))
        self.client.get.assert_called_with('%s/v2/apps/app_id/instances' % self.TARGET_ENDPOINT)
        self.assertIsNotNone(application) 
Example #20
Source File: test_users.py    From alembic-quickstart with MIT License 5 votes vote down vote up
def test_create(api_client):
    response = await api_client.post('/users', json=USER)
    assert response.status == HTTPStatus.CREATED

    data = await response.json()
    for key, value in USER.items():
        assert value == data[key] 
Example #21
Source File: schedule.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def post(self, schedule_name: str, token: AccessToken.Payload):
        """Update all properties of a schedule but _id and most_recent_task"""

        query = {"name": schedule_name}
        schedule = Schedules().find_one(query)
        if not schedule:
            raise ScheduleNotFound()

        request_json = CloneSchema().load(request.get_json())
        new_schedule_name = request_json["name"]

        # ensure it's not a duplicate
        if Schedules().find_one({"name": new_schedule_name}, {"name": 1}):
            raise BadRequest(
                "schedule with name `{}` already exists".format(new_schedule_name)
            )

        schedule.pop("_id", None)
        schedule.pop("most_recent_task", None)
        schedule.pop("duration", None)
        schedule["name"] = new_schedule_name
        schedule["enabled"] = False
        schedule["duration"] = {"default": get_default_duration()}

        # insert document
        schedule_id = Schedules().insert_one(schedule).inserted_id

        return make_response(jsonify({"_id": str(schedule_id)}), HTTPStatus.CREATED) 
Example #22
Source File: requested_task.py    From zimfarm with GNU General Public License v3.0 5 votes vote down vote up
def post(self, token: AccessToken.Payload):
        """ Create requested task from a list of schedule_names """

        try:
            request_json = NewRequestedTaskSchema().load(request.get_json())
        except ValidationError as e:
            raise InvalidRequestJSON(e.messages)

        schedule_names = request_json["schedule_names"]
        priority = request_json.get("priority", 0)
        worker = request_json.get("worker")

        # raise 404 if nothing to schedule
        if not Schedules().count_documents(
            {"name": {"$in": schedule_names}, "enabled": True}
        ):
            raise NotFound()

        requested_tasks = []
        for schedule_name in schedule_names:

            rq_task = request_a_schedule(
                schedule_name, token.username, worker, priority
            )
            if rq_task is None:
                continue

            requested_tasks.append(rq_task)

        if len(requested_tasks) > 1:
            BROADCASTER.broadcast_requested_tasks(requested_tasks)
        elif len(requested_tasks) == 1:
            BROADCASTER.broadcast_requested_task(requested_tasks[0])

        return make_response(
            jsonify({"requested": [rt["_id"] for rt in requested_tasks]}),
            HTTPStatus.CREATED,
        ) 
Example #23
Source File: ch12_r06_server.py    From Modern-Python-Cookbook with MIT License 5 votes vote down vote up
def make_deck():
    id = str(uuid.uuid1())
    decks[id]= Deck()
    response_json = jsonify(
        status='ok',
        id=id
    )
    response = make_response(response_json, HTTPStatus.CREATED)
    response.headers['Location'] = url_for('get_deck', id=str(id))
    return response 
Example #24
Source File: ch12_r07_server.py    From Modern-Python-Cookbook with MIT License 5 votes vote down vote up
def make_deck():
    id = str(uuid.uuid1())
    decks[id]= Deck()
    response_json = jsonify(
        status='ok',
        id=id
    )
    response = make_response(response_json, HTTPStatus.CREATED)
    response.headers['Location'] = url_for('get_deck', id=str(id))
    return response 
Example #25
Source File: ch12_r05_server.py    From Modern-Python-Cookbook with MIT License 5 votes vote down vote up
def make_deck():
    id = str(uuid.uuid1())
    decks[id]= Deck()
    response_json = jsonify(
        status='ok',
        id=id
    )
    response = make_response(response_json, HTTPStatus.CREATED)
    response.headers['Location'] = url_for('get_deck', id=str(id))
    return response 
Example #26
Source File: jobs.py    From asgard-api with MIT License 5 votes vote down vote up
def create_job(job: ScheduledJob, user: User, account: Account):

    try:
        created_job = await ScheduledJobsService.create_job(
            job, user, account, ChronosScheduledJobsBackend()
        )
    except DuplicateEntity as e:
        return json_response(
            ErrorResource(errors=[ErrorDetail(msg=str(e))]).dict(),
            status=HTTPStatus.UNPROCESSABLE_ENTITY,
        )
    return json_response(
        CreateScheduledJobResource(job=created_job).dict(),
        status=HTTPStatus.CREATED,
    ) 
Example #27
Source File: jenkins_mock.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def do_POST(self):
        if 'job' in self.path:
            if 'build' in self.path or 'description' in self.path :
                length = int(self.headers.get('content-length',0))
                fstream = self.rfile.read(length)
                self.server.rxJenkinsData((self.path , fstream))
                self.send_response(HTTPStatus.CREATED)
                self.end_headers()
                return
            if 'config.xml' in self.path:
                length = int(self.headers.get('content-length',0))
                fstream = self.rfile.read(length)
                self.server.rxJenkinsData((self.path , fstream))
                self.send_response(HTTPStatus.OK)
                self.end_headers()
                return
        if 'doDelete' in self.path:
            self.send_response(302)
            self.end_headers()
            self.server.rxJenkinsData((self.path , ''))
            return
        if 'createItem' in self.path:
            length = int(self.headers.get('content-length',0))
            fstream = self.rfile.read(length)
            self.server.rxJenkinsData((self.path , fstream))
            self.send_response(200)
            self.end_headers()
            return
        self.send_response(404)
        self.end_headers()
        return 
Example #28
Source File: host.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        source = request.data.get("source", None)
        for item in source:
            importer = HostImporter(path=os.path.join(MEDIA_DIR, item))
            importer.run()
        return JsonResponse(data={"success": True}, status=HTTPStatus.CREATED) 
Example #29
Source File: file.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        files = request.FILES.getlist('file', None)
        count = 0
        media_dir = MEDIA_DIR
        if not os.path.exists(media_dir):
            os.mkdir(media_dir)
        for file_obj in files:
            local_file = os.path.join(media_dir, file_obj.name)
            with open(local_file, "wb+") as f:
                for chunk in file_obj.chunks():
                    f.write(chunk)
            count = count + 1
        return JsonResponse(data={"success": count}, status=HTTPStatus.CREATED) 
Example #30
Source File: unittest.py    From hutils with MIT License 5 votes vote down vote up
def ok(self, response, *, is_201=False, is_204=False, **kwargs):
        """ shortcuts to response 20X """
        expected = (is_201 and HTTPStatus.CREATED) or (is_204 and HTTPStatus.NO_CONTENT) or HTTPStatus.OK
        self.assertEqual(
            expected,
            response.status_code,
            "status code should be {}: {}".format(expected, getattr(response, "data", "")),
        )
        if kwargs:
            self.assert_same(response.data, **kwargs)
        return self