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


Python HTTPStatus.CREATED屬性代碼示例

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


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

示例1: create_user

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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
    ) 
開發者ID:b2wdigital,項目名稱:asgard-api,代碼行數:22,代碼來源:users.py

示例2: test_create

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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) 
開發者ID:cloudfoundry-community,項目名稱:cf-python-client,代碼行數:23,代碼來源:test_service_instances.py

示例3: test_create

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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) 
開發者ID:cloudfoundry-community,項目名稱:cf-python-client,代碼行數:18,代碼來源:test_service_bindings.py

示例4: test_share_domain

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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' 
開發者ID:cloudfoundry-community,項目名稱:cf-python-client,代碼行數:22,代碼來源:test_domains.py

示例5: create_roll

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Mastering-Object-Oriented-Python-Second-Edition,代碼行數:20,代碼來源:ch13_ex5.py

示例6: test_container_generate_upload_url

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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"] 
開發者ID:scottwernervt,項目名稱:cloudstorage,代碼行數:18,代碼來源:test_drivers_rackspace.py

示例7: test_container_generate_upload_url

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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"] 
開發者ID:scottwernervt,項目名稱:cloudstorage,代碼行數:25,代碼來源:test_drivers_microsoft.py

示例8: handle_create_user

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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() 
開發者ID:alvassin,項目名稱:alembic-quickstart,代碼行數:20,代碼來源:main.py

示例9: post

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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) 
開發者ID:openzim,項目名稱:zimfarm,代碼行數:20,代碼來源:schedule.py

示例10: created

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
def created(data: dict) -> web.Response:
        return web.json_response(data, status=HTTPStatus.CREATED) 
開發者ID:maubot,項目名稱:maubot,代碼行數:4,代碼來源:responses.py

示例11: do_POST

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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 
開發者ID:BobBuildTool,項目名稱:bob,代碼行數:33,代碼來源:jenkins_mock.py

示例12: create

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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) 
開發者ID:KubeOperator,項目名稱:KubeOperator,代碼行數:8,代碼來源:host.py

示例13: create

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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) 
開發者ID:KubeOperator,項目名稱:KubeOperator,代碼行數:15,代碼來源:file.py

示例14: ok

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
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 
開發者ID:zaihui,項目名稱:hutils,代碼行數:13,代碼來源:unittest.py

示例15: send_cart

# 需要導入模塊: from http import HTTPStatus [as 別名]
# 或者: from http.HTTPStatus import CREATED [as 別名]
def send_cart(request):
    cart = ShoppingCart.objects.get(user_id=request.user.id)

    data = _prepare_order_data(cart)

    headers = {
        'Authorization': f'Token {settings.ORDER_SERVICE_AUTHTOKEN}',
        'Content-type': 'application/json'
    }

    service_url = f'{settings.ORDER_SERVICE_BASEURL}/api/order/add/'

    response = requests.post(
        service_url,
        headers=headers,
        data=data)

    if HTTPStatus(response.status_code) is HTTPStatus.CREATED:
        request_data = json.loads(response.text)
        ShoppingCart.objects.empty(cart)
        messages.add_message(
            request,
            messages.INFO,
            ('We received your order!'
             'ORDER ID: {}').format(request_data['order_id']))
    else:
        messages.add_message(
            request,
            messages.ERROR,
            ('Unfortunately, we could not receive your order.'
             ' Try again later.'))

    return HttpResponseRedirect(reverse_lazy('user-cart')) 
開發者ID:PacktPublishing,項目名稱:Python-Programming-Blueprints,代碼行數:35,代碼來源:views.py


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