Desmond  Gerber

Desmond Gerber

1668514994

Docker for Beginners

Docker is a tool that developers use to simplify developing and shipping applications.

Per Stack Overflow's 2021 Developer Survey, it's one of the most popular development tools.

This article will take you through the basics of Docker, focusing specifically on:

  1. The core Docker concepts and components
  2. What a Dockerfile looks like and what its most common instructions do
  3. What images and containers are, how they're created, and how to manage them

This article can be read-only. However, if you want to follow along, I provided a basic HelloWorld application that you can use to try out all the commands on your own. Feel free to clone it down and run the commands as you move through this article.

While container and image commands are independent of your application's language, Dockerfiles generally have language specific constructs in them. That said, despite the provided example being Python-based, you'll easily be able to tailor your newly-gained knowledge to other languages.

Objectives

By the end of this article, you should be able to:

  1. Explain what Docker is and how it works
  2. Describe and differentiate between the following concepts and components: Docker Engine, Docker Desktop, Dockerfile, Docker image, and Docker container
  3. Follow more complicated tutorials that use Docker

Containers and Virtual Machines

Before jumping into Docker, it's important to understand the difference between containers and virtual machines.

Containers and virtual machines are similar in that they allow multiple apps to run on the same server with various software requirements -- e.g., different Python versions, different libraries, etc. Their main difference is in the operating system. While containers uses the host's operating system, each virtual machine has its own guest operating system on top of the host's operating system.

In a now almost famous image, you can see how Docker compares to virtual machines:

Containers and Virtual Machines

So, if you have an application that needs to run on different operating systems, a virtual machine is the way to go. But if that's not a requirement, Docker has multiple advantages over a virtual machine:

  1. Lighter-weight
  2. Faster to build
  3. Can be easily ported across different platforms
  4. Less resource intensive
  5. Scaling up and duplicating is easier

All those advantages are due to Docker containers not needing their own operating system.

Docker

Docker Engine

When people refer to Docker, they're typically referring to Docker Engine.

Docker Engine is the underlying open source containerization technology for building, managing, and running containerized applications. It's a client-server application with the following components:

  1. Docker daemon (called dockerd) is a service that runs in the background that listens for Docker Engine API requests and manages Docker objects like images and containers.
  2. Docker Engine API is a RESTful API that's used to interact with Docker daemon.
  3. Docker client (called docker) is the command line interface used for interacting with Docker daemon. So, when you use a command like docker build, you're using Docker client, which in turn leverages Docker Engine API to communicate with Docker daemon.

Docker Desktop

These days, when you try to install Docker, you'll come across Docker Desktop. While Docker Engine is included with Docker Desktop, it's important to understand that Docker Desktop is not the same as Docker Engine. Docker Desktop is an integrated development environment for Docker containers. It makes it much easier to get your operating system configured for working with Docker.

If you haven't already, go ahead and install Docker Desktop:

Docker Concepts

At the heart of Docker, there are three core concepts:

  1. Dockerfile - a text file that serves as a blueprint for your container. In it, you define a list of instructions that Docker uses to build an image.
  2. Image - a read-only embodiment of the Dockerfile. It's built out of layers -- each layer corresponds to a single line of instructions from a Dockerfile.
  3. Container - running a Docker image produces a container, which is a controlled environment for your application. If we draw parallels with object-oriented programming, a container is an instance of a Docker image.

Dockerfile vs Docker Image vs Docker Container

A Dockerfile is used to create a Docker image, which is then used to create (multiple) Docker containers.

We'll look into all three core concepts in detail in the next few sections.

It's highly recommended to read through Docker overview before moving on.

Dockerfile

Again, a Dockerfile is a text file that contains instructions for Docker on how to build an image. By default, a Dockerfile has no extension, but you can add one if you need more than one -- e.g., Dockerfile.prod.

Here's an example of a very simple Dockerfile:

FROM python:3.10-slim-buster

WORKDIR /usr/src/app

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt

COPY . .

CMD uvicorn main:app --reload --host 0.0.0.0 --port 8000

This example is as simple as can be, so you can easily understand it. It does not adhere to best practices, but you should try to follow them in your Dockerfiles.

A Dockerfile is essentially a list of commands in the following form: INSTRUCTION arguments. The majority of the most widely used commands can be seen in the above Dockerfile. Let's look at each of them in detail...

FROM

All Dockerfiles include a parent/base image on which the new image will be built. You use the FROM instruction to define the parent image:

FROM python:3.10-slim-buster

A valid Dockerfile always includes a FROM instruction.

Although parent and base image terms are sometimes used interchangeably, there's a difference between them. A parent image has its own parent image. Meanwhile, a base image has no parent; it starts with FROM scratch.

Alpine image is a base image and Python:alpine is a parent image (whose parent (base) image is actually the alpine image).

It's possible to create a base image on your own, but the probability of you needing your own image is small.

You can find parent images on Docker Hub, which is Docker's library/registry for Docker images. You can think of it as GitHub for Docker images. You'll probably want to use either official images or verified images from trusted sources since they're more likely to adhere to Docker best practices and contain the latest security fixes.

In the example above, we used the official Python parent image, specifically python:3.10-slim-buster.

Notes about python:3.10-slim-buster:

  • The number tells you which version of the technology the image uses (e.g., the python:3.11.0a5 image uses Python version 3.11.0a5 while node:18.9.0 uses Node version 18.9.0). You'll probably want to avoid any versions with rc in it (e.g., python:3.11.0rc2) since rc means release candidate.
  • Names like buster, bullseye, or alpine tell you which OS images were used for this image (buster and bullseye refer to Debian releases while alpine is a lightweight Linux distribution). Additionally, there are tags such as slim and slim-buster that use lighter versions of the full image.

Review Use Small Docker Base Images for best practices on which base image to use.

RUN

The RUN instruction executes any commands in a new layer on top of the current image and commits the result.

Examples:

RUN mkdir /home/app/web

RUN python manage.py collectstatic --noinput

ENV

You use the ENV instruction to set an environment variable. This variable will be available in all subsequent instructions.

Examples:

ENV TZ=UTC

ENV HOME=/home/app

CMD and ENTRYPOINT

Some Docker instructions are so similar it can be hard to understand why both commands are needed. One of those "couples" are CMD and ENTRYPOINT.

First, for the similarities:

  • CMD and ENTRYPOINT both specify a command / an executable that will be executed when running a container. Unlike RUN, which executes the command right away (the result is used in the image layer), the CMD/ENTRYPOINT command in the build-up specifies the command that will be used only when the container starts.
  • You can have only one CMD/ENTRYPOINT instruction in a Dockerfile, but it can point to a more complicated executable file.

There's actually only one difference between those instructions:

  • CMD can easily be overridden from Docker CLI.

You should use CMD if you want the flexibility to run different executables depending on your needs when starting the container. If you want to clearly communicate that command is not meant to be overridden and prevent accidentally changing it, use ENTRYPOINT.

You'll probably use one or the other. If you don't use one, the container will be stopped immediately since there's no reason for it to exist (the exception being if you're also using Docker Compose).

You may also use both CMD and ENTRYPOINT in the same Dockerfile, in which case CMD serves as the default argument for the ENTRYPOINT.

You can have only one CMD instruction in a Dockerfile, but it can point to a more complicated executable file. If you have more than one CMD, only the last CMD will take effect. The same goes for the ENTRYPOINT instruction.

Example of CMD instruction usage:

CMD gunicorn core.wsgi:application --bind 0.0.0.0:$PORT

There's a big chance you'll see the ENTRYPOINT argument as an executable file since commands that should be executed are often more than a one-liner.

Example of ENTRYPOINT as executable file usage:

ENTRYPOINT ["./entrypoint.sh"]

And this is what the entrypoint.sh file might look like:

#!/bin/sh

python manage.py migrate
python manage.py collectstatic --noinput

It's important to understand the difference between CMD and ENTRYPOINT. For more, check out Understand the Difference Between ENTRYPOINT and CMD as well as the official docs.

ADD and COPY

Another pair similar to one another is ADD and COPY.

Both instructions copy new files or directories from the path to the filesystem of the image at the path:

ADD <src> <dest>
COPY <src> <dest>

Additionally, ADD can copy from remote file URLs (for example, it allows adding a git repository to an image directly) and directly from a compressed archive (ADD will automatically unpack the contents to the given location).

You should prefer COPY over ADD unless you specifically need one of the two additional features of ADD -- i.e., downloading example files or unpacking a compressed file

Examples of ADD and COPY instruction usage:

# copy local files on the host to the destination
COPY /source/path  /destination/path
COPY ./requirements.txt .

# download external file and copy to the destination
ADD http://external.file/url  /destination/path
ADD --keep-git-dir=true https://github.com/moby/buildkit.git#v0.10.1 /buildkit

# copy and extract local compresses files
ADD source.file.tar.gz /destination/path

Image

An image might be the most confusing concept of the three. You create a Dockerfile and then use a container, but an image lies between those two.

So, an image is a read-only embodiment of a Dockerfile that's used to create a Docker container. It consists of layers -- each line in a Dockerfile makes one layer. You can't change an image directly; you change it by changing the Dockerfile. You don't directly use an image either; you use a container created from an image.

The most important image-related tasks are:

  1. building images from Dockerfiles
  2. listing all the built images
  3. removing images

Since 2017, Docker switched from shorter commands (i.e., docker <command>) to a more descriptive format (i.e., docker <top-level command> <command>). Despite Docker users being encouraged to use the new version, even the official tutorial uses the shorter version. As of now, the old version still works, and I have not been able to find any proof of the old commands getting deprecated. What's more, people (and even the documentation) started referring to it as a 'shorthand'.

The advantage of using the new version is that you'll better understand which of the three concepts the command is dealing with. The commands are also easier to find in the docs. The advantage of the old version is that it's shorter, and the documentation is more comprehensive.

I'll be using the descriptive form of commands in this article. At the end of the article, you can find all the commands with their shorthand version.

Here, you can find all the new-form commands that deal with images.

Building

To build an image from a Dockerfile, you use the docker image build command. This command requires one argument: either a path or URL of the context.

This image will use the current directory as a context:

$ docker image build .

There are a number of options you can provide. For example, -f is used to specify a specific Dockerfile when you have multiple Dockerfiles (e.g., Dockerfile.prod) or when the Dockerfile isn't in the current directory (e.g., docker image build . -f docker/Dockerfile.prod).

Probably the most important is the -t tag that is used to name/tag an image.

When you build an image, it gets assigned an ID. Contrary to what you might expect, the IDs are not unique. If you want to be able to easily reference your image, you should name/tag it. With -t, you can assign a name and a tag to it.

Here's an example of creating three images: one without the usage of -t, one with a name assigned, and one with a name and a tag assigned.

$ docker image build .
$ docker image build . -t hello_world
$ docker image build . -t hello_world:67d19c27b60bd782c9d3600ae914604a94bddfd4

$ docker image ls
REPOSITORY           TAG       IMAGE ID       CREATED          SIZE
REPOSITORY    TAG                                        IMAGE ID       CREATED          SIZE
hello_world   67d19c27b60bd782c9d3600ae914604a94bddfd4   e03784993f22   25 minutes ago   181MB
hello_world   latest                                     e03784993f22   26 minutes ago   181MB
<none>        <none>                                     7a615d108866   29 minutes ago   181MB

Notes:

  1. For the image that was built without a name or tag, you can only reference it via its image ID. Not only is it difficult to remember, but, again, it might not be unique (which is the case above). You should avoid this.
  2. For the image that only has a name (-t hello_world), the tag is automatically set to latest. You should avoid this as well. For more, review Version Docker Images.

Listing

The docker image ls command lists all built images.

Example:

$ docker image ls

REPOSITORY      TAG       IMAGE ID       CREATED         SIZE
hello_world     latest    c50405e84d39   9 minutes ago   245MB
<none>          <none>    2700a62cd8f1   42 hours ago    245MB
alpine/git      latest    692618a0d74d   2 weeks ago     43.4MB
todo_app        test      999740882932   3 weeks ago     1.03GB

Removing

There are two use cases for removing images:

  1. You want to remove one or more selected images
  2. You want to remove all the unused images (you don't care which images specifically)

For the first case, you use docker image rm; for the second, you use docker image prune.

Remove

docker image rm removes and untags the selected image(s). It requires one argument: The reference to the image(s) you want to remove. You can reference it by name or short/long ID.

If you think back to the explanation of image tagging... there can be multiple images with a different name but the same ID. If you try to remove the image by image ID and multiple images with that ID exist, you'll get an image is referenced in multiple repositories error. In that case, you'll have to remove it by referencing it by name. If you wish to remove all images with the same ID, you can use the -f flag.

Example of unsuccessful and successful image removal:

$ docker image ls

REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
test1        latest    4659ba97837b   41 seconds ago   245MB
test2        latest    4659ba97837b   41 seconds ago   245MB
test         latest    4659ba97837b   41 seconds ago   245MB


$ docker rmi 4659ba97837b

Error response from daemon: conflict: unable to delete 4659ba97837b (must be forced) - image is referenced in multiple repositories


$ docker rmi test2
Untagged: test2:latest


$ docker image ls

REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
test1        latest    4659ba97837b   4 minutes ago   245MB
test         latest    4659ba97837b   4 minutes ago   245MB

Prune

docker image prune removes dangling images. Since prune is a command that can be used for cleaning containers, images, volumes, and networks, this command doesn't have a shorter version. If you use the -a flag, all unused images are removed (i.e., docker image prune -a).

A dangling image is an image that is not tagged and is not referenced by any container.

An unused image is an image that isn't associated with at least one container.

Example:

$ docker image prune

WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N]

Deleted Images:
deleted: sha256:c9a6625eb29593463ea43aab4053090427bf29cc59bc97917b3298fda6a94e8a
deleted: sha256:284f940f39c3ef5be09440e23fdefdb00df0791344db5c340a9d11979a98039e
deleted: sha256:1934187bf17ccf4e754842a4ceeacf5c14aaa63ba7a04c0c520f53946426c902

There are a few additional commands, but you'll probably not use them very much; you can see all image-related commands in the official docs.

Container

The third concept you need to understand is a container, which is a controlled environment for your application. An image becomes a container when it's run on Docker Engine. It's the end goal: You use Docker so you can have a container for your application.

The main operations you can do with a container are

  1. running a container
  2. listing all the containers
  3. stopping a container
  4. removing a container

You can see all the commands related to a container in the official docs.

Running

You can either create a new container of an image and run it, or you can start an existing container that was previously stopped.

Run

The docker container run command actually combines two other commands, docker container create and docker container start.

So, the following essentially gives you the same result:

$ docker container run my_image

# the same as:

$ docker container create my_image
88ce9c60aeabbb970012b5f8dbae6f34581fa61ec20bd6d87c6831fbb5999263
$ docker container start 88ce9c60aeabbb970012b5f8dbae6f34581fa61ec20bd6d87c6831fbb5999263

You need to provide one argument: The image you want to use for the container.

When you run the run command, Docker creates a writable container layer over the specified image and then starts it using the specified command (CMD/ENTRYPOINT in the Dockerfile).

The changes made in the writable layer do not persist after you delete the container, unless you store it. Docker has two options for storing data.

Since you can override a number of the defaults, there are many options. You can see all of them in the official docs. The most important option is --publish/-p, which is used to publish ports to the outside world. Although it is technically possible to run a container without a port, it's not very useful since the service(s) running inside the container wouldn't be accessible outside the container. You can use --publish/-p for both the create and run commands:

Here's an example of how that looks like:

$ docker container run -p 8000:8000 my_image

You can read more on port publishing in the official docs.

You can run your container in detached mode by using --detach/-d, which lets you keep using the terminal.

If you run a container in detached mode, Docker will just return the container ID:

$ docker container run -p 8000:8000 -d my_image

0eb20b715f42bc5a053dc7878b3312c761058a25fc1efaffb7920b3b4e48df03

Your container gets a unique, quirky name by default, but you can assign your own name:

$ docker container run -p 8000:8000 --name my_great_container my_image

Start

To start a stopped or just created container, you use the docker container start command. Since with this command, you're starting an existing container, you have to specify the container instead of an image (as with docker container run).

Another difference from docker container run is that docker container start by default runs the container in the detached mode. You can attach it using --attach/-a (reverse from docker container run -d).

Example:

$ docker container start -a reverent_sammet

Listing

You can list all running containers with docker container ls.

Example:

$ docker container ls

CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                    NAMES
0f21395ec96c   9973e9c65229   "/bin/sh -c 'gunicor…"   6 minutes ago   Up 6 minutes   0.0.0.0:80->8000/tcp     shopping
73bd69d041ae   my_image       "/bin/sh -c 'uvicorn…"   2 hours ago     Up 2 hours     0.0.0.0:8000->8000/tcp   my_great_container

If you want to also see the stopped containers, you can add the -a flag:

$ docker container ls -a

CONTAINER ID   IMAGE          COMMAND                  CREATED              STATUS                     PORTS                    NAMES
0f21395ec96c   9973e9c65229   "/bin/sh -c 'gunicor…"   About a minute ago   Up About a minute          0.0.0.0:80->8000/tcp     shopping
73bd69d041ae   my_image       "/bin/sh -c 'uvicorn…"   2 hours ago          Up 2 hours                 0.0.0.0:8000->8000/tcp   my_great_container
0eb20b715f42   my_image       "/bin/sh -c 'uvicorn…"   2 hours ago          Exited (137) 2 hours ago                            agitated_gagarin
489a02b8cfac   my_image       "/bin/sh -c 'uvicorn…"   2 hours ago          Created                                             vigorous_poincare

Let's take a look at the output for:

CONTAINER ID   IMAGE          COMMAND                  CREATED         STATUS         PORTS                    NAMES
73bd69d041ae   my_image       "/bin/sh -c 'uvicorn…"   2 hours ago     Up 2 hours     0.0.0.0:8000->8000/tcp   my_great_container
  1. CONTAINER ID (73bd69d041ae) and its NAMES (my_great_container) are both unique, so you can use them to access the container.
  2. IMAGE (my_image) tells you which image was used to run the container.
  3. CREATED is pretty self-explanatory: when the container was created (2 hours ago).
  4. We already discussed the need for specifying a command for starting a container... COMMAND tells you which command was used ("/bin/sh -c 'uvicorn…").
  5. STATUS is useful when you don't know why your container isn't working (Up 2 hours means your container is running, Exited or Created means it's not)

Some of the information is truncated. If you want the untruncated version, add --no-trunc.

Stopping

To stop a container, use docker container stop. The name or ID of the stopped container is then returned.

Example:

$ docker container stop my_great_container
my_great_container

$ docker container stop 73bd69d041ae
73bd69d041ae

A container can be started again with docker container start.

Removing

Similar to images, to remove a container, you can either:

  1. remove one or more selected containers via docker container rm.
  2. remove all stopped containers via docker container prune

Example of docker container rm:

$ docker container rm festive_euclid
festive_euclid

Example of docker container prune:

$ docker container prune

WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
0f21395ec96c28b443bad8aac40197fe0468d24e0eed49e5f56011de1c81b589
80c693693f3d99999925eae5f4bbfc03236cde670db509797d83f50e732fcf31
0eb20b715f42bc5a053dc7878b3312c761058a25fc1efaffb7920b3b4e48df03
1273cf44c551f8ab9302e6d090e3c4e135ca6f7e1ab3d90a62bcbf5e83ba9342

Commands

We went through quite a few commands in this article. To help you navigate through what you read, I prepared a table with all the commands we came across. The table includes the descriptive command as well as the shorthand alias.

CommandAliasUsage
docker image builddocker buildBuild an image from a Dockerfile
docker image lsdocker imagesList images
docker image rmdocker rmiRemove selected images
docker image pruneN/ARemove unused images
docker container rundocker runCreate the container and start it
docker container startdocker startStart an existing container
docker container lsdocker psList all containers
docker container stopdocker stopStop a container
docker container rmdocker rmRemove a container
docker container pruneN/ARemove all stopped containers

Conclusion

To summarize, the most essential concepts in Docker are Dockerfile, image, and container.

Using a Dockerfile as a blueprint, you build an image. Images can then be used to build other images and can be found on Docker Hub. Running an image produces a controlled environment for your application, called a container.

The aim of this article was to explain to you the basics of Docker. If you want to read some more hands-on tutorials, you can check our extensive list of articles related to Docker. If you're a Python developer, be sure to check out Docker Best Practices for Python Developers.

What's next?

Docker is a complex system. This article just scratched the surface. There are still plenty of concepts, features, and tools that you'll need to learn as you use Docker. Here are a few that you'll probably encounter sooner rather than later:

  1. Like git, Docker has an ignore file called .dockerignore where you can define which files and folders you don't want to add to the image (due to security, size, etc.).
  2. As I mentioned in the article, the data from the container's writable layers don't persist if the container is removed. You can use volumes or bind mounts to store files on the host machine.
  3. If your application needs multiple containers (for example, if your Django app uses Postgres), you can use Docker Compose to simplify their lifecycle.

Original article source at: https://testdriven.io

#docker #Beginners 

Docker for Beginners
Nat  Grady

Nat Grady

1668507492

Pytest for Beginners

Automated testing is an essential part of your development process.

Although writing tests at first may look like it prolongs the development process, it saves you a lot of time in the long run.

Well-written tests decrease the possibility of something breaking in a production environment by ensuring your code is doing what you expected. Tests also help you cover marginal cases and make refactoring easier.

In this article, we'll look at how to use pytest, so you'll be able to use it on your own to improve your development process and follow more advanced pytest tutorials.

Objectives

By the end of this article, you'll be able to:

  1. Explain what pytest is and how you can use it
  2. Write a test with pytest on your own
  3. Follow more complicated tutorials that use pytest
  4. Prepare data and/or files that you need for a test
  5. Parametrize a test
  6. Mock functionality you need for a test

Why pytest

Although often overlooked, testing is so vital that Python comes with its own built-in testing framework called unittest. Writing tests in unittest can be complicated, though, so in recent years, the pytest framework has become the standard.

Some significant advantages of pytest are:

  1. requires less boilerplate code, making your test suites more readable
  2. uses plain assert statement rather than unittest's assertSomething methods (e.g., assertEquals, assertTrue)
  3. fixture system simplifies setting up and tearing down test state
  4. functional approach
  5. large, community-maintained plugin ecosystem

Getting Started

Since this is a guide rather than a tutorial, we've prepared a simple FastAPI application that you can refer to as you're going through this article. You can clone it from GitHub.

On the basic branch, our API has 4 endpoints (defined in main.py) that use functions from calculations.py to return a result from performing a certain basic arithmetic operation (+/-/*//) on two integers. On the advanced_topics branch, there are two more functionalities added:

  1. CalculationsStoreJSON (inside store_calculations.py) class - allows you to store and retrieve calculations to/from a JSON file.
  2. get_number_fact (inside number_facts.py) - makes a call to a remote API to retrieve a fact about a certain number.

No knowledge of FastAPI is required to understand this article.

We'll use the basics branch for the first part of this article.

Create and activate the virtual environment and install the requirements:

$ python3.10 -m venv venv
$ source venv/bin/activate
(venv)$ pip install -r requirements.txt

Organizing and Naming

To organize your tests, you can use three possibilities, all of which are used in the example project:

Organized inExample
Python package (folder including an __init__.py file)"test_calculations"
Moduletest_commutative_operations.py
ClassTestCalculationEndpoints

When it comes to best practices for organizing tests, each programmer has their own preferences.

The purpose of this article is not to show best practices but, instead, to show you all possibilities.

pytest will discover tests on its own if you abide by the following conventions:

  • you add your tests to a file that starts with test_ or ends with _test.py (e.g., test_foo.py or foo_test.py)
  • you prefix test functions with test_ (e.g., def test_foo())
  • if you're using classes, you add your tests as methods to a class prefixed with Test (e.g., class TestFoo)

The tests not following the naming convention will not be found, so be careful with your naming.

It's worth noting that the naming convention can be changed on the command line or a configuration file).

Test Anatomy

Let's see what the test_return_sum (in the test_calculation_endpoints.py file) test function looks like:

# tests/test_endpoints/test_calculation_endpoints.py


def test_return_sum(self):
   # Arrange
   test_data = {
      "first_val": 10,
      "second_val": 8
   }
   client = TestClient(app)

   # Act
   response = client.post("/sum/", json=test_data)

   # Assert
   assert response.status_code == 200
   assert response.json() == 18

Each test function, according to the pytest documentation, consists of four steps:

  1. Arrange - where you prepare everything for your test (test_data = {"first_val": 10, "second_val": 8})
  2. Act - singular, state-changing action that kicks off the behavior you want to test (client.post("/sum/", json=test_data))
  3. Assert - compares the result of the Act with the desired result (assert response.json() == 18)
  4. Cleanup - where the test-specific data gets cleaned up (usually in tests that test more complicated features, you can see an example in our tips)

Running Tests

pytest gives you a lot of control as to which tests you want to run:

  1. all the tests
  2. specific package
  3. specific module
  4. specific class
  5. specific test
  6. tests corresponding to a specific keyword

Let's see how this works...

If you're following along with our sample application, pytest is already installed if you installed the requirements.

For your own projects, pytest can be installed as any other package with pip:

(venv)$ pip install pytest

Running All the Tests

Running the pytest command will simply run all the tests that pytest can find:

(venv)$ python -m pytest

=============================== test session starts ===============================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/pytest_for_beginners_test_project
plugins: anyio-3.6.1
collected 8 items

tests/test_calculations/test_anticommutative_operations.py ..               [ 25%]
tests/test_calculations/test_commutative_operations.py ..                   [ 50%]
tests/test_endpoints/test_calculation_endpoints.py ....                     [100%]

================================ 8 passed in 5.19s ================================

pytest will inform you how many tests are found and which modules the tests were found in. In our example app, pytest found 8 tests, and they all passed.

At the bottom of the message, you can see how many tests passed/failed.

Incorrect Naming Pattern

As already discussed, tests that don't abide by the proper naming convention will simply not be found. Wrongly named tests don't produce any error, so you need to be mindful of that.

For example, if you rename the TestCalculationEndpoints class to CalculationEndpointsTest, all the tests inside it simply won't run:

=============================== test session starts ===============================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/pytest_for_beginners_test_project
plugins: anyio-3.6.1
collected 4 items

tests/test_calculations/test_anticommutative_operations.py ..               [ 50%]
tests/test_calculations/test_commutative_operations.py ..                   [100%]

================================ 4 passed in 0.15s ================================

Change the name back to TestCalculationEndpoints before moving on.

Failing Test

Your test won't always pass on the first try.

Corrupt the predicted output in the assert statement in test_calculate_sum to see what the output for a failing test looks like:

# tests/test_calculations/test_commutative_operations.py


def test_calculate_sum():

    calculation = calculate_sum(5, 3)

    assert calculation == 7 # whops, a mistake

Run the test. You should see something similar to:

=============================== test session starts ===============================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/pytest_for_beginners_test_project
plugins: anyio-3.6.1
collected 8 items

tests/test_calculations/test_anticommutative_operations.py ..               [ 25%]
tests/test_calculations/test_commutative_operations.py F.                   [ 50%]
tests/test_endpoints/test_calculation_endpoints.py ....                     [100%]

==================================== FAILURES =====================================
_______________________________ test_calculate_sum ________________________________

    def test_calculate_sum():

        calculation = calculate_sum(5, 3)

>       assert calculation == 7
E       assert 8 == 7

tests/test_calculations/test_commutative_operations.py:8: AssertionError
============================= short test summary info =============================
FAILED tests/test_calculations/test_commutative_operations.py::test_calculate_sum
=========================== 1 failed, 7 passed in 0.26s ===========================

At the bottom of the message, you can see a short test summary info section. This tells you which test failed and where. In this case, the actual output -- 8 -- doesn't match the expected one -- 7.

If you scroll a little higher, the failing test is displayed in detail, so it's easier to pinpoint what went wrong (helpful with more complex tests).

Fix this test before moving on.

Running Tests in a Specific Package or Module

To run a specific package or module, you just need to add a full relative path to the specific test set to the pytest command.

For a package:

(venv)$ python -m pytest tests/test_calculations

This command will run all the tests inside the "tests/test_calculations" package.

For a module:

(venv)$ python -m pytest tests/test_calculations/test_commutative_operations.py

This command will run all the tests inside the tests/test_calculations/test_commutative_operations.py module.

The output of both will be similar to the previous one, except the number of executed tests will be smaller.

Running Tests in a Specific Class

To access a specific class in pytest, you need to write a relative path to its module and then add the class after :::

(venv)$ python -m pytest tests/test_endpoints/test_calculation_endpoints.py::TestCalculationEndpoints

This command will execute all tests inside the TestCalculationEndpoints class.

Running a Specific Test

You can access a specific test the same way as the class, with two colons after the relative path, followed by the test name:

(venv)$ python -m pytest tests/test_calculations/test_commutative_operations.py::test_calculate_sum

If the function you wish to run is inside a class, a single test needs to be run in the following form:

relative_path_to_module::TestClass::test_method

For example:

(venv)$ python -m pytest tests/test_endpoints/test_calculation_endpoints.py::TestCalculationEndpoints::test_return_sum

Running Tests by Keyword

Now, let's say you only want to run tests dealing with division. Since we included the word "divided" in the test name for tests that deal with division, you can run just those tests like so:

(venv)$ python -m pytest -k "dividend"

So, 2 out of 8 tests will run:

=============================== test session starts ===============================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/pytest_for_beginners_test_project
plugins: anyio-3.6.1
collected 8 items / 6 deselected / 2 selected

tests/test_calculations/test_anticommutative_operations.py .                [ 50%]
tests/test_endpoints/test_calculation_endpoints.py .                        [100%]

========================= 2 passed, 6 deselected in 0.18s =========================

Those are not the only ways to select a specific subset of tests. Refer to the official documentation for more info.

pytest Flags Worth Remembering

pytest includes many flags; you can list all of them with the pytest --help command.

Among the most useful are:

  1. pytest -v increases verbosity for one level, and pytest -vv increases it for two levels. For example, when using parametrization (running the same test multiple times with different inputs/outputs), running just pytest informs you how many test versions passed and how many failed while adding -v also outputs which parameters were used. If you add -vv, you'll see each test version with the input parameters. You can see a much more detailed example on the pytest docs.
  2. pytest -lf re-runs only the tests that failed during the last run. If there are no failures, all the tests will run.
  3. Adding the -x flag causes pytest to exit instantly on the first error or failed test.

Parameterizing

We covered the basics and are now moving to more advanced topics.

If you're following along with the repo, switch the branch from basics to advanced_topics (git checkout advanced_topics).

Sometimes, a single example input for your test will suffice, but there are also many occasions that you'll want to test multiple inputs -- e.g., emails, passwords, etc.

You can add multiple inputs and their respective outputs with parameterizing via the @pytest.mark.parametrize decorator.

For example, with anti-commutative operations, the order of the numbers passed matters. It would be smart to cover more cases to ensure that the function works correctly for all the cases:

# tests/test_calculations/test_anticommutative_operations.py


import pytest

from calculations import calculate_difference


@pytest.mark.parametrize(
    "first_value, second_value, expected_output",
    [
        (10, 8, 2),
        (8, 10, -2),
        (-10, -8, -2),
        (-8, -10, 2),
    ]
)
def test_calculate_difference(first_value, second_value, expected_output):

    calculation = calculate_difference(first_value, second_value)

    assert calculation == expected_output

@pytest.mark.parametrize has a strictly structured form:

  1. You pass two arguments to the decorator:
    1. A string with comma-separated parameter names
    2. A list of parameter values where their position corresponds to the position of parameter names
  2. You pass the parameter names to the test function (they're not dependent on the position)

If you run that test, it will run 4 times, each time with different inputs and output:

(venv)$ python -m pytest -v  tests/test_calculations/test_anticommutative_operations.py::test_calculate_difference

=============================== test session starts ===============================
platform darwin -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/michael/repos/testdriven/pytest_for_beginners_test_project
plugins: anyio-3.6.1
collected 4 items

tests/test_calculations/test_anticommutative_operations.py::test_calculate_difference[10-8-2] PASSED [ 25%]
tests/test_calculations/test_anticommutative_operations.py::test_calculate_difference[8-10--2] PASSED [ 50%]
tests/test_calculations/test_anticommutative_operations.py::test_calculate_difference[-10--8--2] PASSED [ 75%]
tests/test_calculations/test_anticommutative_operations.py::test_calculate_difference[-8--10-2] PASSED [100%]

================================ 4 passed in 0.01s ================================

Fixtures

It's a good idea to move the Arrange (and consequently Cleanup) step to a separate fixture function when the Arrange step is exactly the same in multiple tests or if it's so complicated that it hurts tests' readability.

Creation

A function is marked as a fixture with a @pytest.fixture decorator.

The old version of TestCalculationEndpoints had a step for creating a TestClient in each method.

For example:

# tests/test_endpoints/test_calculation_endpoints.py


def test_return_sum(self):
    test_data = {
        "first_val": 10,
        "second_val": 8
    }
    client = TestClient(app)

    response = client.post("/sum/", json=test_data)

    assert response.status_code == 200
    assert response.json() == 18

In the advanced_topics branch, you'll see that the method now looks much cleaner:

# tests/test_endpoints/test_calculation_endpoints.py


def test_return_sum(self, test_app):
    test_data = {
        "first_val": 10,
        "second_val": 8
    }

    response = test_app.post("/sum/", json=test_data)

    assert response.status_code == 200
    assert response.json() == 18

The second two were left as they were, so you can compare them (don't do that in real-life; it makes no sense).

test_return_sum now uses a fixture called test_app that you can see in the conftest.py file:

# tests/conftest.py


import pytest
from starlette.testclient import TestClient

from main import app


@pytest.fixture(scope="module")
def test_app():
    client = TestClient(app)

    return client

What's going on?

  1. The @pytest.fixture() decorator marks the function test_app as a fixture. When pytest reads that module, it adds that function to a list of fixtures. Test functions can then use any fixture in that list.
  2. This fixture is a simple function that returns a TestClient, so test API calls can be performed.
  3. Test function arguments are compared with a list of fixtures. If the argument's value matches a fixture's name, the fixture will be resolved and its return value is written as an argument in the test function.
  4. The test function uses the result of the fixture to do its testing, using it in the same way as any other variable value.

Another important thing to notice is that the function is not passed the fixture itself but a fixture value.

Scope

Fixtures are created when first requested by a test, but they are destroyed based on their scope. After the fixture is destroyed, it needs to be evoked again, if required by another test; so, you need to be mindful of the scope with time-expensive fixtures (e.g., API calls).

There are five possible scopes, from the narrowest to the broadest:

ScopeDescription
function (default)The fixture is destroyed at the end of the test.
classThe fixture is destroyed during the teardown of the last test in the class.
moduleThe fixture is destroyed during the teardown of the last test in the module.
packageThe fixture is destroyed during the teardown of the last test in the package.
sessionThe fixture is destroyed at the end of the test session.

To change the scope in the previous example, you just need to set the scope parameter:

# tests/conftest.py


import pytest
from starlette.testclient import TestClient

from main import app


@pytest.fixture(scope="function") # scope changed
def test_app():
    client = TestClient(app)

    return client

How important it is to define the smallest possible scope depends on how time-consuming the fixture is. Creating a TestClient isn't very time-consuming, so changing the scope doesn't shorten the test run. But, for example, running 10 tests using a fixture that calls an external API can be very time-consuming, so it's probably best to use the module scope.

Temporary Files

When your production code has to deal with files, your tests will as well.

To avoid interference between multiple test files or even with the rest of the app and the additional cleaning process, it's best to use a unique temporary directory.

In the sample app, we stored all the operations performed on a JSON file for future analysis. Now, since you definitely don't want to alter a production file during test runs, you need to create a separate, temporary JSON file.

The code to be tested can be found in store_calculations.py:

# store_calculations.py


import json


class CalculationsStoreJSON:
    def __init__(self, json_file_path):
        self.json_file_path = json_file_path
        with open(self.json_file_path / "calculations.json", "w") as file:
            json.dump([], file)

    def add(self, calculation):
        with open(self.json_file_path/"calculations.json", "r+") as file:
            calculations = json.load(file)
            calculations.append(calculation)
            file.seek(0)
            json.dump(calculations, file)

    def list_operation_usages(self, operation):
        with open(self.json_file_path / "calculations.json", "r") as file:
            calculations = json.load(file)

        return [calculation for calculation in calculations if calculation['operation'] == operation]

Notice that upon initializing CalculationsStoreJSON, you have to provide a json_file_path, where your JSON file will be stored. This can be any valid path on disk; you pass the path the same way for production code and the tests.

Fortunately, pytest provides a number of built-in fixtures, one of which we can use in this case called tmppath:

# tests/test_advanced/test_calculations_storage.py


from store_calculations import CalculationsStoreJSON

def test_correct_calculations_listed_from_json(tmp_path):
    store = CalculationsStoreJSON(tmp_path)
    calculation_with_multiplication = {"value_1": 2, "value_2": 4, "operation": "multiplication"}

    store.add(calculation_with_multiplication)

    assert store.list_operation_usages("multiplication") == [{"value_1": 2, "value_2": 4, "operation": "multiplication"}]

This test checks if upon saving the calculation to a JSON file using the CalculationsStoreJSON.add() method, we can retrieve a list of certain operations using UserStoreJSON.list_operation_usages().

We passed the tmp_path fixture to this test, which returns a path (pathlib.Path) object, that points to a temporary directory inside the base directory.

When using tmp_path, pytest creates a:

  1. base temporary directory
  2. temporary directory (inside the base directory) that's unique to each test function invocation

It's worth noting that, to help with debugging, pytest creates a new base temporary directory during each test session, while old base directories are removed after 3 sessions.

Monkeypatching

With monkeypatching, you dynamically modify the behavior of a piece of code at runtime without actually changing the source code.

Although it's not necessarily limited just to testing, in pytest, it's used to modify the behavior of the code part inside the tested unit. It's usually used to replace expensive function calls, like HTTP call to APIs, with some pre-defined dummy behavior that's fast and easy to control.

For example, instead of making a call to a real API to get a response, you return some hardcoded response that's used inside tests.

Let's take a deeper look. In our app, there's a function that returns a fact about some number that's retrieved from a public API:

# number_facts.py


import requests

def get_number_fact(number):
    url = f"http://numbersapi.com/{number}?json"
    response = requests.get(url)
    json_resp = response.json()

    if json_resp["found"]:
        return json_resp["text"]

    return "No fact about this number."

You don't want to call the API during your tests because:

  • it's slow
  • it's error-prone (the API can be down, you may have a poor internet connection, ...)

In this case, you want to mock the response, so it returns the part we're interested in without actually making the HTTP request:

# tests/test_advanced/test_number_facts.py


import requests

from number_facts import get_number_fact


class MockedResponse:

    def __init__(self, json_body):
        self.json_body = json_body

    def json(self):
        return self.json_body


def mock_get(*args, **kwargs):
    return MockedResponse({
        "text": "7 is the number of days in a week.",
        "found": "true",
    })


def test_get_number_fact(monkeypatch):
    monkeypatch.setattr(requests, 'get', mock_get)

    number = 7
    fact = '7 is the number of days in a week.'

    assert get_number_fact(number) == fact

A lot is happening here:

  1. pytest's built-in monkeypatch fixture is used in the test function.
  2. Using monkeypatch.setattr, we overrode the get function of the requests package with our own function, mock_get. All the calls inside the app code to requests.get will now actually call mock_get during the execution of this test.
  3. The mock_get function returns a MockedResponse instance that replaces json_body with the value we assigned inside the mock_get function ({'"text": "7 is the number of days in a week.", "found": "true",}).
  4. Each time that test is evoked, instead of executing requests.get("http://numbersapi.com/7?json") as in the production code (get_number_fact), a MockedResponse with a hardcoded fact will be returned.

This way, you can still verify the behavior of your function (getting a fact about a number from an API response) without really calling the API.

Conclusion

There's a number of reasons why pytest became a standard in the past few years, most notably:

  1. It simplifies the writing of the tests.
  2. Due to its comprehensive outputs, it can be easy to pinpoint which tests failed and why.
  3. It provides solutions for repetitive or complicated test preparation, creating files for testing purposes, and test isolation.

pytest offers much more than what we covered in this article.

Their documentation includes helpful how-to guides that cover in-depth most of what we skimmed here. They also provide a number of examples.

pytest also comes with an extensive list of plugins, which you can use to extend pytest functionalities.

Here are a few you might find useful:

  • pytest-cov adds support for checking code coverage.
  • pytest-django adds a set of valuable tools for testing Django applications.
  • pytest-xdist allows you to run tests in parallel, thus shortening the time tests need to run.
  • pytest-randomly runs tests in random order, preventing them from accidentally being dependent on each other.
  • pytest-asincio makes it easier to test asynchronous programs.
  • pytest-mock provides a mocker fixture that's a wrapper around the standard unittest mock package along with additional utilities.

This article should have helped you understand how the pytest library works and what it's possible to accomplish with it. However, understanding just how pytest works and how testing works are not the same. Learning to write meaningful tests takes practice and understanding of what you expect your code to do.

Original article source at: https://testdriven.io/blog/pytest-for-beginners/ 

#python #pytest #Beginners 

Pytest for Beginners
Dipesh Malvia

Dipesh Malvia

1663246784

Node JS Package Manager | Basics & Built-Ins | Node.js Tutorial for Beginners #2

Node JS Package Manager | Basics & Built-Ins | Node.js Tutorial for Beginners #2

In this video we will deep dive into node.js package manager and some useful javascript basics and built-ins. 

⭐️ Support my channel⭐️ https://www.buymeacoffee.com/dipeshmalvia 

⭐️ GitHub link for Reference ⭐️ https://github.com/dmalvia/NodeJs_Course 

⭐️ Node.js for beginners Playlist ⭐️ https://youtube.com/playlist?list=PLTP3E5bPW796_icZanMqhdg7i0Cl7Y51F 

⭐️ JavaScript ⭐️ 

🔗 Social Medias 🔗 

⭐️ Tags ⭐️ - Node.js Package Manager Tutorial - Introduction to Node.js - NPM Tutorial - Node.Js Crash Course 

⭐️ Hashtags ⭐️ #nodejs  #Beginners  #tutorials 

Disclaimer: It doesn't feel good to have a disclaimer in every video but this is how the world is right now. All videos are for educational purpose and use them wisely. Any video may have a slight mistake, please take decisions based on your research. This video is not forcing anything on you.

 

https://youtu.be/v_rB6ZKXcv4

Node JS Package Manager | Basics & Built-Ins | Node.js Tutorial for Beginners #2

Diferentes Tipos De Serviços Baseados Em Nuvem

A computação em nuvem é uma das tecnologias de TI que mais crescem atualmente. Até 2025, 83% das cargas de trabalho corporativas estarão na nuvem. De acordo com o relatório da IDC, o mundo gastará US$ 160 bilhões em serviços e infraestrutura em nuvem em 2018. A nuvem abrange uma variedade de serviços online. É importante para as empresas que consideram os serviços em nuvem entender as diferenças entre IaaS, PaaS e SaaS. Você deve escolher o modelo certo, dependendo de seus requisitos de negócios e do número de tarefas que deseja delegar ou gerenciar. Selecionar o serviço de nuvem ideal é, sem dúvida, difícil, e você deve pesar vários fatores antes de decidir. Aqui, abordamos todos os benefícios e desvantagens de SaaS, PaaS e IaaS para ajudá-lo a decidir qual modelo é melhor para sua empresa.

serviço baseado em nuvemhttps://litslink.com/blog/iaas-paas-saas

IaaS

Essencialmente, esta é uma versão virtual de um data center físico. Os provedores de infraestrutura em nuvem usam a tecnologia de virtualização para fornecer recursos de computação escaláveis ​​a seus clientes, incluindo servidores, redes e armazenamento. Os clientes se beneficiam disso, pois não podem comprar hardware pessoal e gerenciar seus componentes. Em vez de implantar seus aplicativos e plataformas em data centers físicos, eles podem usar as máquinas virtuais do provedor. O provedor de IaaS gerencia toda a infraestrutura, mas os usuários a controlam totalmente. Aplicativos e sistemas operacionais são instalados e mantidos pelos usuários, assim como segurança, tempo de execução, middleware e dados.

Vantagens do IaaS:

1. Modelo com maior flexibilidade e potencial dinâmico.

2. Devido ao preço de pagamento conforme o uso, é econômico.

3. A implantação automatizada de hardware facilita o uso.

4. Os funcionários têm mais tempo para outras tarefas porque as tarefas de gerenciamento são virtualizadas.

Desvantagens do IaaS:

1. A arquitetura multilocatário apresenta riscos de segurança.

2. Os clientes não podem acessar seus dados por algum tempo devido a interrupções do fornecedor.

3. Aprender a gerenciar uma nova infraestrutura requer treinamento de equipe.

PaaS

PaaS, ou Platform as a Service, é uma estrutura baseada na Internet para a criação de software. Essa plataforma contém componentes de software e ferramentas que os desenvolvedores podem usar para criar, personalizar, testar e iniciar aplicativos. Os fornecedores de PaaS gerenciam servidores, atualizações do sistema operacional, patches de segurança e backups. Desenvolvedores de aplicativos e gerentes de dados não precisam se preocupar com a manutenção de infraestrutura, middleware e sistemas operacionais. IaaS e PaaS diferem principalmente em quanto controle os usuários recebem.

Vantagens do PaaS:

1. Como o software desenvolvido para PaaS é baseado em nuvem, ele é altamente escalável, disponível e multilocatário.

2. Agilizar e acelerar o processo de desenvolvimento.

3. O custo de criação, teste e lançamento de aplicativos é reduzido.

4. Automação de políticas.

5. Uma redução na quantidade de codificação necessária.

Desvantagens do PaaS:

1. Questões relacionadas à segurança de dados.

2. Não é possível habilitar para nuvem todos os elementos da infraestrutura existente.

3. Velocidade, confiabilidade e suporte dependendo do fornecedor.

SaaS

O fornecedor fornece software baseado em nuvem com esta oferta. Aplicativos SaaS não precisam ser baixados e instalados em dispositivos locais, mas plugins podem ser necessários ocasionalmente. O software SaaS pode ser acessado pela web por meio de APIs e está localizado em uma rede de nuvem distante. Os clientes podem trabalhar juntos em projetos, armazenar dados e analisá-los com esses aplicativos.

O tipo mais popular de computação em nuvem é o SaaS. Tudo, desde a estabilidade do hardware até a funcionalidade do aplicativo, é gerenciado pelo provedor de SaaS. Nesse arranjo, os clientes são exclusivamente responsáveis ​​pelo uso de programas para realizar seus trabalhos. Nesse caso, o provedor controla a experiência de software do cliente.

Vantagens do SaaS:

1. Não há custos de hardware e os custos de configuração inicial não são incorridos.

2. As atualizações são realizadas automaticamente.

3. Adaptabilidade a vários dispositivos.

4. Facilmente acessível de qualquer lugar, Um modelo de pagamento por uso.

5. Adaptabilidade, a personalização é fácil.

Desvantagens do SaaS:

1. A falta de controle.

2. As soluções são limitadas.

3. A necessidade de conectividade não pode ser exagerada.

Diferença entre IaaS, PaaS e SaaS

serviços baseados em nuvem

https://www.quora.com/What-is-the-difference-between-IaaS-SaaS-and-Paas

 IaaSPaaSSaaS
primeiro.   IaaS significa Infraestrutura como Serviço
 
PaaS significa Plataforma como serviço.
 
SaaS significa software como serviço.
 
2.   Como parte da IaaS, o provedor de nuvem gerencia a
infraestrutura.
 
Como parte do PaaS, o provedor de nuvem gerencia
a infraestrutura e a plataforma. 
 
Como parte do SaaS, o provedor de nuvem gerencia toda a
infraestrutura, plataformas e software.
 
3.   Na IaaS, você precisa gerenciar a plataforma e o software.No PaaS, você precisa gerenciar o software. Como usuário de SaaS, você não precisa gerenciar
nada.
 
4.   A infraestrutura como serviço (IaaS) pode ser usada para recuperação de dados, armazenamento, teste de software e desenvolvimento.A plataforma como serviço pode ser usada para
desenvolvimento e gerenciamento de estruturas, bem como inteligência de negócios.
 
 O software como serviço (SaaS) permite que os usuários usem aplicativos para fins pessoais ou comerciais.
5.   As plataformas IaaS são altamente escaláveis.
 
As plataformas PaaS permitem que os clientes dimensionem os recursos de computação de acordo com o tamanho do negócio.O modelo SaaS é escalável com diferentes níveis de preços para cada nível de negócios.
6.   Os provedores controlam totalmente a infraestrutura.Devido aos recursos limitados das plataformas PaaS, os usuários podem não conseguir personalizar as operações na nuvem. Uma conexão com a Internet e um navegador são necessários para que os usuários usem aplicativos SaaS.
 
    

Conclusão

Depois de ler todo o material acima, você entenderá o valor dos serviços em nuvem e por que eles são tão apreciados pelas empresas. As vantagens das soluções em nuvem são enormes. Assim, não é surpreendente que esse setor econômico esteja passando por uma expansão tão acentuada. A escolha de qualquer modelo da lista acima depende inteiramente das necessidades do seu negócio e do tipo de tarefa que deseja realizar.

Principais conclusões:

  • Várias palavras técnicas estão relacionadas à computação em nuvem, mas IaaS, PaaS e SaaS são as mais cruciais.
  • Eles são considerados os três principais pilares que fornecem estabilidade para a computação em nuvem.
  • Suas metas de negócios determinarão qual desses três tipos você selecionará.
  • Os três modelos de nuvem têm características e recursos exclusivos.
  • É crucial compreender suas principais distinções entre si.
  • Se você deseja usar a nuvem para armazenamento, precisa de uma plataforma poderosa para criar aplicativos personalizados ou deseja controle total sobre sua infraestrutura, deve escolher o provedor de nuvem correto.
  • A migração para os serviços em nuvem é necessária para manter a força organizacional de sua empresa, independentemente de sua opção.
  • Você pode optar por usar apenas um modelo de computação em nuvem ou os serviços dos três modelos.
  • O tamanho e a complexidade de sua organização determinarão isso.

Fonte: https://www.analyticsvidhya.com/blog/2022/07/different-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

Diferentes Tipos De Serviços Baseados Em Nuvem
顾 静

顾 静

1659466800

不同类型的基于云的服务

云计算是当今发展最快的 IT 技术之一。到 2025 年,83% 的企业工作负载将在云端。根据 IDC 报告,2018 年全球将在云服务和基础设施上花费 1600 亿美元。云包括各种在线服务。对于考虑云服务的企业来说,了解 IaaS、PaaS 和 SaaS 之间的区别非常重要。您应该根据您的业务需求以及您想要委派或自己处理的任务数量来选择正确的模型。选择理想的云服务无疑是困难的,在决定之前必须权衡几个因素。在这里,我们介绍了 SaaS、PaaS 和 IaaS 的所有优点和缺点,以帮助您确定哪种模型最适合您的公司。

基于云的服务https://litslink.com/blog/iaas-paas-saas

即服务即服务

本质上,这是物理数据中心的虚拟版本。云基础设施提供商使用虚拟化技术为其客户提供可扩展的计算资源,包括服务器、网络和存储。客户从中受益,因为他们无法购买个人硬件并管理其组件。他们可以使用提供商的虚拟机,而不是在物理数据中心部署他们的应用程序和平台。IaaS 提供商管理整个基础架构,但用户完全控制它。应用程序和操作系统以及安全性、运行时、中间件和数据都由用户安装和维护。

IaaS 的优势:

1. 具有最大灵活性和动态潜力的模型。

2、按量付费,性价比高。

3. 自动化硬件部署,使用方便。

4. 由于管理任务是虚拟化的,员工有更多的时间来处理其他任务。

IaaS 的缺点:

1. 多租户架构带来安全风险。

2. 由于供应商中断,客户在一段时间内无法访问他们的数据。

3.学习如何管理新的基础设施需要团队培训。

即服务

PaaS,即平台即服务,是一种基于互联网的软件创建框架。该平台包含开发人员可以用来创建、定制、测试和启动应用程序的软件组件和工具。PaaS 供应商管理服务器、操作系统更新、安全补丁和备份。应用程序开发人员和数据管理员不必担心维护基础设施、中间件和操作系统。IaaS 和 PaaS 的主要区别在于给予用户多少控制权。

PaaS 的优势:

1. 由于 PaaS 构建的软件是基于云的,因此它具有高度可扩展性、可用性和多租户。

2. 简化和加快开发过程。

3. 降低了创建、测试和启动应用程序的成本。

4. 政策自动化。

5. 所需编码量的减少。

PaaS 的缺点:

1. 与数据安全相关的问题。

2. 不可能对现有基础设施的每个元素都启用云。

3. 速度、可靠性和支持取决于供应商。

软件即服务

供应商通过此产品提供基于云的软件。SaaS 应用程序无需下载并安装在本地设备上,但有时可能需要插件。SaaS 软件可以通过 API 通过 Web 访问,并且位于远程云网络上。客户可以使用这些应用程序一起处理项目、存储数据和分析数据。

最流行的云计算类型是 SaaS。从硬件稳定性到应用程序功能,一切都由 SaaS 提供商管理。在这种安排下,客户全权负责使用程序来完成他们的工作。在这种情况下,提供商控制客户的软件体验。

SaaS的优势:

1.没有硬件成本,不产生初始设置成本。

2. 升级是自动执行的。

3.对多种设备的适应性。

4. 随时随地轻松访问,按使用付费模式。

5.适应性强,定制容易。

SaaS的缺点:

1. 缺乏控制。

2. 解决方案有限。

3. 对连接的需求怎么强调都不为过。

IaaS、PaaS 和 SaaS 之间的区别

基于云的服务

https://www.quora.com/What-is-the-difference-between-IaaS-SaaS-and-Paas

 即服务即服务即服务软件即服务
第一的。   IaaS 代表基础设施即服务
 
PaaS 代表平台即服务。
 
SaaS代表软件即服务。
 
2.   作为 IaaS 的一部分,云提供商管理
基础架构。
 
作为 PaaS 的一部分,云提供商管理
基础架构和平台。 
 
作为 SaaS 的一部分,云提供商管理所有
基础架构、平台和软件。
 
3.   在 IaaS 中,您需要管理平台和软件。在 PaaS 中,您需要管理软件。 作为 SaaS 用户,您无需管理
任何内容。
 
4.   基础设施即服务 (IaaS) 可用于数据恢复、存储、软件测试和开发。平台即服务可用于框架
开发和管理,以及商业智能。
 
 软件即服务 (SaaS) 使用户能够将应用程序用于个人或商业目的。
5.   IaaS 平台具有高度可扩展性。
 
PaaS 平台允许客户根据其业务规模扩展计算资源。SaaS 模型可扩展,每个业务级别都有不同的定价层。
6.   提供商完全控制基础设施。由于 PaaS 平台的能力有限,用户可能无法自定义云操作。 用户使用 SaaS 应用程序都需要互联网连接和浏览器。
 
    

结论

阅读完以上所有材料后,您将了解云服务的价值以及为什么它们如此受公司欢迎。云解决方案的优势是巨大的。因此,这一经济部门正在经历如此急剧的扩张也就不足为奇了。从上面的列表中选择任何模型完全取决于您的业务需求和您想要执行的任务类型。

关键要点:

  • 几个技术词汇与云计算相关,但 IaaS、PaaS 和 SaaS 是最关键的。
  • 它们被认为是为云计算提供稳定性的三大关键支柱。
  • 您的业​​务目标将决定您​​最终选择这三种类型中的哪一种。
  • 这三个云模型各自具有独特的特征和功能。
  • 理解它们之间的主要区别是至关重要的。
  • 无论您是想使用云进行存储、需要强大的平台来创建自定义应用程序,还是想完全控制您的基础架构,您都必须选择正确的云提供商。
  • 无论您的选择如何,迁移到云服务对于保持公司的组织实力都是必要的。
  • 您可以选择仅使用一种云计算模型或所有三种模型的服务。
  • 您的组织的规模和复杂性将决定这一点。

资料来源:https ://www.analyticsvidhya.com/blog/2022/07/different-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

不同类型的基于云的服务
坂本  健一

坂本 健一

1659466800

さまざまな種類のクラウドベースのサービス

クラウド コンピューティングは、今日最も急速に成長している IT テクノロジの 1 つです。2025 年までに、エンタープライズ ワークロードの 83% がクラウドになります。IDC のレポートによると、世界は 2018 年にクラウド サービスとインフラストラクチャに 1,600 億ドルを費やすと予測されています。クラウドには、さまざまなオンライン サービスが含まれます。クラウド サービスを検討している企業は、IaaS、PaaS、SaaS の違いを理解することが重要です。ビジネス要件と、委任または自分で処理するタスクの数に応じて、適切なモデルを選択する必要があります。理想的なクラウド サービスを選択することは間違いなく困難であり、決定する前にいくつかの要因を検討する必要があります。ここでは、SaaS、PaaS、および IaaS のすべての利点と欠点を取り上げ、どのモデルが会社に最適かを判断するのに役立てました。

クラウドベースのサービスhttps://litslink.com/blog/iaas-paas-saas

IaaS

基本的に、これは物理データ センターの仮想バージョンです。クラウド インフラストラクチャ プロバイダーは、仮想化テクノロジを使用して、サーバー、ネットワーク、ストレージなどのスケーラブルなコンピューティング リソースをクライアントに提供します。クライアントは、個人のハードウェアを購入してそのコンポーネントを管理することができないため、このメリットを享受できます。アプリケーションとプラットフォームを物理データ センターに展開する代わりに、プロバイダーの仮想マシンを使用できます。IaaS プロバイダーはインフラストラクチャ全体を管理しますが、ユーザーはそれを完全に制御します。アプリとオペレーティング システムは、セキュリティ、ランタイム、ミドルウェア、およびデータと同様に、ユーザーによってインストールおよび維持されます。

IaaS の利点:

1. 最大限の柔軟性とダイナミックな可能性を備えたモデル。

2. 従量課金制のため、コストパフォーマンスに優れています。

3. 自動化されたハードウェア展開により、使いやすくなります。

4. 管理タスクが仮想化されるため、従業員は他のタスクにより多くの時間を割くことができます。

IaaS の欠点:

1. マルチテナント アーキテクチャはセキュリティ リスクをもたらします。

2. ベンダーの停止により、顧客はしばらくデータにアクセスできません。

3. 新しいインフラストラクチャを管理する方法を学ぶには、チームのトレーニングが必要です。

PaaS

PaaS (Platform as a Service) は、ソフトウェアを作成するためのインターネット ベースのフレームワークです。このプラットフォームには、開発者がアプリケーションの作成、カスタマイズ、テスト、起動に使用できるソフトウェア コンポーネントとツールが含まれています。PaaS のベンダーは、サーバー、オペレーティング システムの更新プログラム、セキュリティ パッチ、およびバックアップを管理します。アプリ開発者とデータ管理者は、インフラストラクチャ、ミドルウェア、およびオペレーティング システムの維持について心配する必要はありません。IaaS と PaaS の主な違いは、ユーザーに与えられる制御の範囲です。

PaaS の利点:

1. PaaS で構築されたソフトウェアはクラウドベースであるため、拡張性、可用性、マルチテナント性に優れています。

2. 開発プロセスの合理化とスピードアップ。

3. アプリの作成、テスト、および起動のコストが削減されます。

4. ポリシーの自動化。

5. 必要なコーディング量の削減。

PaaS の欠点:

1. データのセキュリティに関する問題。

2. 既存のインフラストラクチャのすべての要素をクラウド対応にすることはできません。

3. 速度、信頼性、サポートはベンダーによって異なります。

SaaS

ベンダーは、このオファリングでクラウドベースのソフトウェアを提供します。SaaS アプリケーションをダウンロードしてローカル デバイスにインストールする必要はありませんが、プラグインが必要になる場合があります。SaaS ソフトウェアは、Web 経由で API を介してアクセスでき、離れたクラウド ネットワーク上に配置されます。顧客はこれらのアプリを使用して、プロジェクトで共同作業し、データを保存し、分析することができます。

クラウド コンピューティングの最も一般的なタイプは SaaS です。ハードウェアの安定性からアプリの機能まで、すべてが SaaS プロバイダーによって管理されます。この取り決めでは、クライアントは、プログラムを使用して自分の仕事を実行する責任を独占的に負います。この場合、プロバイダーはクライアントのソフトウェア エクスペリエンスを制御します。

SaaS の利点:

1. ハードウェアの費用がかからず、初期設定費用も発生しません。

2. アップグレードは自動的に実行されます。

3. 複数のデバイスへの適応性。

4. どこからでも簡単にアクセスできる従量制モデル。

5. 適応性、カスタマイズは容易です。

SaaS の欠点:

1. コントロールの欠如。

2. ソリューションは限られています。

3. コネクティビティの必要性はいくら強調してもしすぎることはありません。

IaaS、PaaS、SaaS の違い

クラウドベースのサービス

https://www.quora.com/What-is-the-difference-between-IaaS-SaaS-and-Paas

 IaaSPaaSSaaS
1.   IaaS は Infrastructure as a Service の略です
 
PaaS は Platform as a Service の略です。
 
SaaSはサービスとしてのソフトウェアの略です。
 
2.   IaaS の一部として、クラウド プロバイダーが
インフラストラクチャを管理します。
 
PaaS の一部として、クラウド プロバイダーは
インフラストラクチャとプラットフォームの両方を管理します。 
 
SaaS の一部として、クラウド プロバイダーはすべての
インフラストラクチャ、プラットフォーム、およびソフトウェアを管理します。
 
3.   IaaS では、プラットフォームとソフトウェアを管理する必要があります。PaaS では、ソフトウェアを管理する必要があります。 SaaS ユーザーとして、何も管理する必要はありません

 
4.   サービスとしてのインフラストラクチャ (IaaS) は、データの回復、ストレージ、ソフトウェアのテスト、および開発に使用できます。Platform as a Service は、フレームワークの
開発と管理、およびビジネス インテリジェンスに使用できます。
 
 サービスとしてのソフトウェア (SaaS) を使用すると、ユーザーは個人またはビジネス目的でアプリケーションを使用できます。
5.   IaaS プラットフォームは非常にスケーラブルです。
 
PaaS プラットフォームを使用すると、顧客はビジネスの規模に応じてコンピューティング リソースをスケーリングできます。SaaS モデルは、ビジネス レベルごとに異なる価格レベルでスケーラブルです。
6.   プロバイダーはインフラストラクチャを完全に制御します。PaaS プラットフォームの機能が制限されているため、ユーザーはクラウド操作をカスタマイズできない場合があります。 ユーザーが SaaS アプリを使用するには、インターネット接続とブラウザーがすべて必要です。
 
    

結論

上記の資料をすべて読むと、クラウド サービスの価値と、クラウド サービスが企業に好まれる理由が理解できます。クラウド ソリューションの利点は計り知れません。したがって、この経済部門がこれほど急激な拡大を遂げていることは驚くべきことではありません。上記のリストからどのモデルを選択するかは、ビジネス ニーズと実行するタスクの種類に完全に依存します。

重要ポイント:

  • クラウド コンピューティングに関連する専門用語はいくつかありますが、IaaS、PaaS、および SaaS が最も重要です。
  • これらは、クラウド コンピューティングの安定性を提供する 3 つの重要な柱と見なされます。
  • ビジネス目標によって、これら 3 つのタイプのどれを最終的に選択するかが決まります。
  • 3 つのクラウド モデルには、それぞれ独自の特性と機能があります。
  • それらの主な違いを互いに理解することが重要です。
  • ストレージにクラウドを使用する場合でも、カスタム アプリを作成するために強力なプラットフォームが必要な場合でも、インフラストラクチャを完全に制御したい場合でも、適切なクラウド プロバイダーを選択する必要があります。
  • クラウドサービスへの移行は、選択肢に関係なく、企業の組織力を維持するために必要です。
  • クラウド コンピューティング モデルを 1 つだけ使用するか、3 つのモデルのサービスすべてを使用するかを選択できます。
  • これは、組織の規模と複雑さによって決まります。

出典: https://www.analyticsvidhya.com/blog/2022/07/different-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

さまざまな種類のクラウドベースのサービス
Anne  de Morel

Anne de Morel

1659463200

Différents Types De Services Basés Sur Le Cloud

Le cloud computing est l'une des technologies informatiques à la croissance la plus rapide aujourd'hui. D'ici 2025, 83 % des charges de travail des entreprises seront dans le cloud. Selon le rapport d'IDC, le monde dépensera 160 milliards de dollars en services et infrastructures cloud en 2018. Le cloud englobe une variété de services en ligne. Il est important pour les entreprises qui envisagent des services cloud de comprendre les différences entre IaaS, PaaS et SaaS. Vous devez choisir le bon modèle en fonction des besoins de votre entreprise et du nombre de tâches que vous souhaitez déléguer ou gérer vous-même. La sélection du service cloud idéal est sans aucun doute difficile, et vous devez peser plusieurs facteurs avant de vous décider. Ici, nous avons couvert tous les avantages et les inconvénients de SaaS, PaaS et IaaS pour vous aider à décider quel modèle convient le mieux à votre entreprise.

service basé sur le cloudhttps://litslink.com/blog/iaas-paas-saas

IaaS

Il s'agit essentiellement d'une version virtuelle d'un centre de données physique. Les fournisseurs d'infrastructure cloud utilisent la technologie de virtualisation pour fournir des ressources informatiques évolutives à leurs clients, notamment des serveurs, des réseaux et du stockage. Les clients en bénéficient car ils ne peuvent pas acheter de matériel personnel et gérer ses composants. Au lieu de déployer leurs applications et plates-formes dans des centres de données physiques, ils peuvent utiliser les machines virtuelles du fournisseur. Le fournisseur IaaS gère l'ensemble de l'infrastructure, mais les utilisateurs la contrôlent entièrement. Les applications et les systèmes d'exploitation sont installés et maintenus par les utilisateurs, ainsi que la sécurité, l'exécution, le middleware et les données.

Avantages du IaaS :

1. Modèle avec la plus grande flexibilité et potentiel dynamique.

2. En raison de la tarification à l'utilisation, il est rentable.

3. Le déploiement automatisé du matériel facilite son utilisation.

4. Les employés ont plus de temps pour d'autres tâches car les tâches de gestion sont virtualisées.

Inconvénients du IaaS :

1. L'architecture mutualisée présente des risques de sécurité.

2. Les clients ne peuvent pas accéder à leurs données pendant un certain temps en raison de pannes de fournisseurs.

3. Apprendre à gérer une nouvelle infrastructure nécessite une formation d'équipe.

PaaS

PaaS, ou Platform as a Service, est un cadre basé sur Internet pour la création de logiciels. Cette plate-forme contient des composants logiciels et des outils que les développeurs peuvent utiliser pour créer, personnaliser, tester et lancer des applications. Les fournisseurs de PaaS gèrent les serveurs, les mises à jour du système d'exploitation, les correctifs de sécurité et les sauvegardes. Les développeurs d'applications et les gestionnaires de données n'ont pas à se soucier de la maintenance de l'infrastructure, du middleware et des systèmes d'exploitation. IaaS et PaaS diffèrent principalement par le degré de contrôle accordé aux utilisateurs.

Avantages du PaaS :

1. Étant donné que le logiciel PaaS est basé sur le cloud, il est hautement évolutif, disponible et multi-locataire.

2. Rationalisation et accélération du processus de développement.

3. Le coût de création, de test et de lancement des applications est réduit.

4. Automatisation des politiques.

5. Une réduction de la quantité de codage nécessaire.

Inconvénients du PaaS :

1. Problèmes liés à la sécurité des données.

2. Il n'est pas possible d'activer le cloud pour chaque élément de l'infrastructure existante.

3. Vitesse, fiabilité et assistance selon le fournisseur.

SaaS

Le fournisseur fournit un logiciel basé sur le cloud avec cette offre. Les applications SaaS n'ont pas besoin d'être téléchargées et installées sur des appareils locaux, mais des plug-ins peuvent parfois être nécessaires. Le logiciel SaaS est accessible via le Web via des API et est situé sur un réseau cloud distant. Les clients peuvent travailler ensemble sur des projets, stocker des données et les analyser avec ces applications.

Le type de cloud computing le plus populaire est le SaaS. Tout, de la stabilité du matériel à la fonctionnalité de l'application, est géré par le fournisseur SaaS. Dans cet arrangement, les clients sont exclusivement responsables de l'utilisation des programmes pour effectuer leur travail. Dans ce cas, le fournisseur contrôle l'expérience logicielle du client.

Avantages du SaaS :

1. Il n'y a pas de frais de matériel et les frais d'installation initiaux ne sont pas encourus.

2. Les mises à niveau sont effectuées automatiquement.

3. Adaptabilité à plusieurs appareils.

4. Facilement accessible de n'importe où, un modèle de paiement à l'utilisation.

5. Adaptabilité, la personnalisation est facile.

Inconvénients du SaaS :

1. Un manque de contrôle.

2. Les solutions sont limitées.

3. Le besoin de connectivité ne peut être surestimé.

Différence entre IaaS, PaaS et SaaS

services basés sur le cloud

https://www.quora.com/Quelle-est-la-différence-entre-IaaS-SaaS-et-Paas

 IaaSPaaSSaaS
première.   IaaS signifie Infrastructure en tant que service
 
PaaS signifie Plate-forme en tant que service.
 
SaaS signifie logiciel en tant que service.
 
2.   Dans le cadre d'IaaS, le fournisseur de cloud gère l'
infrastructure.
 
Dans le cadre de PaaS, le fournisseur de cloud gère
à la fois l'infrastructure et la plate-forme. 
 
Dans le cadre du SaaS, le fournisseur de cloud gère l'ensemble
de l'infrastructure, des plates-formes et des logiciels.
 
3.   Dans IaaS, vous devez gérer la plate-forme et les logiciels.Dans PaaS, vous devez gérer le logiciel. En tant qu'utilisateur SaaS, vous n'avez rien à gérer
.
 
4.   L'infrastructure en tant que service (IaaS) peut être utilisée pour la récupération de données, le stockage, les tests de logiciels et le développement.La plate-forme en tant que service peut être utilisée pour le développement et la gestion de frameworks
, ainsi que pour l'informatique décisionnelle.
 
 Le logiciel en tant que service (SaaS) permet aux utilisateurs d'utiliser des applications à des fins personnelles ou professionnelles.
5.   Les plates-formes IaaS sont hautement évolutives.
 
Les plates-formes PaaS permettent aux clients de faire évoluer les ressources informatiques en fonction de la taille de leur entreprise.Le modèle SaaS est évolutif avec différents niveaux de tarification pour chaque niveau d'activité.
6.   Les fournisseurs contrôlent entièrement l'infrastructure.En raison des capacités limitées des plates-formes PaaS, les utilisateurs peuvent ne pas être en mesure de personnaliser les opérations cloud. Une connexion Internet et un navigateur sont tous nécessaires pour que les utilisateurs puissent utiliser les applications SaaS.
 
    

Conclusion

Après avoir lu tous les documents ci-dessus, vous comprendrez la valeur des services cloud et pourquoi ils sont si appréciés des entreprises. Les avantages des solutions cloud sont énormes. Il n'est donc pas surprenant que ce secteur économique connaisse une aussi forte expansion. Le choix d'un modèle dans la liste ci-dessus dépend entièrement des besoins de votre entreprise et du type de tâche que vous souhaitez effectuer.

Points clés à retenir:

  • Plusieurs mots techniques sont liés au cloud computing, mais IaaS, PaaS et SaaS sont les plus cruciaux.
  • Ils sont considérés comme les trois piliers clés qui assurent la stabilité du cloud computing.
  • Vos objectifs commerciaux détermineront lequel de ces trois types vous sélectionnerez en fin de compte.
  • Les trois modèles de cloud ont chacun des caractéristiques et des capacités uniques.
  • Il est crucial de comprendre leurs principales distinctions les unes des autres.
  • Que vous souhaitiez utiliser le cloud pour le stockage, que vous ayez besoin d'une plate-forme puissante pour créer des applications personnalisées ou que vous souhaitiez un contrôle total sur votre infrastructure, vous devez choisir le bon fournisseur de cloud.
  • Le passage aux services cloud est nécessaire pour maintenir la force organisationnelle de votre entreprise, quelle que soit votre option.
  • Vous pouvez choisir d'utiliser un seul modèle de cloud computing ou les services des trois modèles.
  • La taille et la complexité de votre organisation détermineront cela.

Source : https://www.analyticsvidhya.com/blog/2022/07/different-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

Différents Types De Services Basés Sur Le Cloud
Hoang  Kim

Hoang Kim

1659461160

Các Loại Dịch Vụ của Cloud-based Services

Điện toán đám mây là một trong những công nghệ CNTT phát triển nhanh nhất hiện nay. Đến năm 2025, 83% khối lượng công việc của doanh nghiệp sẽ là trên đám mây. Theo báo cáo của IDC, thế giới sẽ chi 160 tỷ USD cho các dịch vụ và cơ sở hạ tầng đám mây vào năm 2018. Đám mây bao gồm nhiều loại dịch vụ trực tuyến. Điều quan trọng đối với các doanh nghiệp đang xem xét dịch vụ đám mây là phải hiểu sự khác biệt giữa IaaS, PaaS và SaaS. Bạn nên chọn mô hình phù hợp tùy thuộc vào yêu cầu kinh doanh của bạn và số lượng nhiệm vụ bạn muốn ủy thác hoặc tự xử lý. Việc lựa chọn dịch vụ đám mây lý tưởng chắc chắn là rất khó và bạn phải cân nhắc một số yếu tố trước khi quyết định. Ở đây, chúng tôi đã đề cập đến tất cả những lợi ích và hạn chế của SaaS, PaaS và IaaS để giúp bạn quyết định mô hình nào phù hợp nhất cho công ty của bạn.

dịch vụ dựa trên đám mâyhttps://litslink.com/blog/iaas-paas-saas

IaaS

Về cơ bản, đây là một phiên bản ảo của một trung tâm dữ liệu vật lý. Các nhà cung cấp cơ sở hạ tầng đám mây sử dụng công nghệ ảo hóa để cung cấp các tài nguyên máy tính có thể mở rộng cho khách hàng của họ, bao gồm máy chủ, mạng và bộ nhớ. Khách hàng được hưởng lợi từ điều này vì họ không thể mua phần cứng cá nhân và quản lý các thành phần của nó. Thay vì triển khai các ứng dụng và nền tảng của họ trong các trung tâm dữ liệu vật lý, họ có thể sử dụng các máy ảo của nhà cung cấp. Nhà cung cấp IaaS quản lý toàn bộ cơ sở hạ tầng, nhưng người dùng hoàn toàn kiểm soát nó. Các ứng dụng và hệ điều hành được cài đặt và duy trì bởi người dùng, cũng như bảo mật, thời gian chạy, phần mềm trung gian và dữ liệu.

Ưu điểm của IaaS:

1. Mô hình có tính linh hoạt và tiềm năng động lớn nhất.

2. Do giá cả phải trả khi bạn di chuyển, nó là hiệu quả về chi phí.

3. Triển khai phần cứng tự động giúp bạn dễ dàng sử dụng.

4. Nhân viên có nhiều thời gian hơn cho các nhiệm vụ khác vì các nhiệm vụ quản lý được ảo hóa.

Nhược điểm của IaaS:

1. Kiến trúc đa đối tượng gây ra rủi ro bảo mật.

2. Khách hàng không thể truy cập dữ liệu của họ trong một thời gian do nhà cung cấp ngừng hoạt động.

3. Học cách quản lý cơ sở hạ tầng mới yêu cầu đào tạo nhóm.

PaaS

PaaS, hoặc Nền tảng dưới dạng Dịch vụ, là một khuôn khổ dựa trên internet để tạo phần mềm. Nền tảng này chứa các thành phần phần mềm và công cụ mà nhà phát triển có thể sử dụng để tạo, tùy chỉnh, kiểm tra và khởi chạy ứng dụng. Nhà cung cấp PaaS quản lý máy chủ, cập nhật hệ điều hành, bản vá bảo mật và bản sao lưu. Các nhà phát triển ứng dụng và quản lý dữ liệu không phải lo lắng về việc duy trì cơ sở hạ tầng, phần mềm trung gian và hệ điều hành. IaaS và PaaS chủ yếu khác nhau về mức độ kiểm soát của người dùng.

Ưu điểm của PaaS:

1. Vì phần mềm do PaaS xây dựng dựa trên nền tảng đám mây nên nó có khả năng mở rộng cao, khả dụng và nhiều người thuê.

2. Hợp lý hóa và đẩy nhanh quá trình phát triển.

3. Giảm chi phí tạo, thử nghiệm và khởi chạy ứng dụng.

4. Tự động hóa chính sách.

5. Giảm số lượng mã hóa cần thiết.

Nhược điểm của PaaS:

1. Các vấn đề liên quan đến bảo mật dữ liệu.

2. Không thể kích hoạt đám mây mọi yếu tố của cơ sở hạ tầng hiện có.

3. Tốc độ, độ tin cậy và hỗ trợ tùy thuộc vào nhà cung cấp.

SaaS

Nhà cung cấp cung cấp phần mềm dựa trên đám mây với dịch vụ này. Các ứng dụng SaaS không cần được tải xuống và cài đặt trên các thiết bị cục bộ, nhưng thỉnh thoảng có thể cần các plugin. Phần mềm SaaS có thể được truy cập qua web thông qua các API và được đặt trên một mạng đám mây ở xa. Khách hàng có thể làm việc cùng nhau trong các dự án, lưu trữ và phân tích dữ liệu bằng các ứng dụng này.

Loại điện toán đám mây phổ biến nhất là SaaS. Mọi thứ, từ độ ổn định của phần cứng đến chức năng của ứng dụng, đều do nhà cung cấp SaaS quản lý. Trong thỏa thuận này, khách hàng chịu trách nhiệm độc quyền về việc sử dụng các chương trình để thực hiện công việc của họ. Trong trường hợp này, nhà cung cấp kiểm soát trải nghiệm phần mềm của khách hàng.

Ưu điểm của SaaS:

1. Không có chi phí phần cứng và không phát sinh chi phí thiết lập ban đầu.

2. Nâng cấp được thực hiện tự động.

3. Khả năng thích ứng với nhiều thiết bị.

4. Dễ dàng truy cập từ mọi nơi, Mô hình trả tiền cho mỗi lần sử dụng.

5. Khả năng thích ứng, Tùy chỉnh rất dễ dàng.

Nhược điểm của SaaS:

1. Sự thiếu kiểm soát.

2. Các giải pháp còn hạn chế.

3. Nhu cầu kết nối không thể được phóng đại.

Sự khác biệt giữa IaaS, PaaS và SaaS

dịch vụ dựa trên đám mây

https://www.quora.com/What-is-the-difference-between-IaaS-SaaS-and-Paas

 IaaSPaaSSaaS
1.   IaaS là ​​viết tắt của Cơ sở hạ tầng như một dịch vụ
 
PaaS là ​​viết tắt của Platform as a service.
 
SaaS là ​​viết tắt của phần mềm như một dịch vụ.
 
2.   Là một phần của IaaS, nhà cung cấp đám mây quản lý
cơ sở hạ tầng.
 
Là một phần của PaaS, nhà cung cấp đám mây quản lý
cả cơ sở hạ tầng và nền tảng. 
 
Là một phần của SaaS, nhà cung cấp đám mây quản lý tất cả
cơ sở hạ tầng, nền tảng và phần mềm.
 
3.   Trong IaaS, bạn cần quản lý nền tảng và phần mềm.Trong PaaS, bạn cần quản lý phần mềm. Là người dùng SaaS, bạn không cần quản lý
bất cứ thứ gì.
 
4.   Cơ sở hạ tầng như một Dịch vụ (IaaS) có thể được sử dụng để khôi phục, lưu trữ, kiểm tra và phát triển phần mềm.Nền tảng như một dịch vụ có thể được sử dụng để
phát triển và quản lý khuôn khổ, cũng như thông tin kinh doanh.
 
 Phần mềm như một dịch vụ (SaaS) cho phép người dùng sử dụng các ứng dụng cho mục đích cá nhân hoặc kinh doanh.
5.   Nền tảng IaaS có khả năng mở rộng cao.
 
Nền tảng PaaS cho phép khách hàng mở rộng tài nguyên máy tính theo quy mô doanh nghiệp của họ.Mô hình SaaS có thể mở rộng với các mức giá khác nhau cho mọi cấp độ kinh doanh.
6.   Các nhà cung cấp hoàn toàn kiểm soát cơ sở hạ tầng.Do khả năng hạn chế của nền tảng PaaS, người dùng có thể không tùy chỉnh được các hoạt động trên đám mây. Tất cả đều cần có kết nối Internet và trình duyệt để người dùng sử dụng ứng dụng SaaS.
 
    

Sự kết luận

Sau khi đọc qua tất cả các tài liệu ở trên, bạn sẽ hiểu giá trị của các dịch vụ đám mây và tại sao chúng lại được các công ty ưa chuộng đến vậy. Ưu điểm của các giải pháp đám mây là rất lớn. Vì vậy, không có gì ngạc nhiên khi khu vực kinh tế này đang có sự mở rộng mạnh mẽ như vậy. Việc chọn bất kỳ mô hình nào từ danh sách trên hoàn toàn phụ thuộc vào nhu cầu kinh doanh của bạn và loại nhiệm vụ bạn muốn thực hiện.

Bài học chính:

  • Một số từ kỹ thuật có liên quan đến điện toán đám mây, nhưng IaaS, PaaS và SaaS là ​​quan trọng nhất.
  • Chúng được coi là ba trụ cột chính mang lại sự ổn định cho điện toán đám mây.
  • Mục tiêu kinh doanh của bạn sẽ xác định bạn chọn loại nào trong ba loại này.
  • Ba mô hình đám mây đều có những đặc điểm và khả năng riêng biệt.
  • Điều quan trọng là phải hiểu được sự khác biệt chính của chúng với nhau.
  • Cho dù bạn muốn sử dụng đám mây để lưu trữ, yêu cầu một nền tảng mạnh mẽ để tạo các ứng dụng tùy chỉnh hoặc muốn kiểm soát hoàn toàn cơ sở hạ tầng của mình, bạn phải chọn đúng nhà cung cấp đám mây.
  • Chuyển sang các dịch vụ đám mây là cần thiết để duy trì sức mạnh tổ chức của công ty bạn bất kể lựa chọn của bạn là gì.
  • Bạn có thể chọn chỉ sử dụng một mô hình điện toán đám mây hoặc cả ba dịch vụ của mô hình.
  • Quy mô và độ phức tạp của tổ chức của bạn sẽ quyết định điều này.

Nguồn: https://www.analyticsvidhya.com/blog/2022/07/dierence-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

Các Loại Dịch Vụ của Cloud-based Services

Diferentes Tipos De Servicios Basados ​​en La Nube

La computación en la nube es una de las tecnologías de TI de más rápido crecimiento en la actualidad. Para 2025, el 83 % de las cargas de trabajo empresariales estarán en la nube. Según el informe de IDC, el mundo gastará $160 mil millones en servicios e infraestructura en la nube en 2018. La nube abarca una variedad de servicios en línea. Es importante que las empresas que están considerando los servicios en la nube comprendan las diferencias entre IaaS, PaaS y SaaS. Debe elegir el modelo correcto según los requisitos de su negocio y la cantidad de tareas que desea delegar o manejar usted mismo. Sin duda, seleccionar el servicio en la nube ideal es difícil y debe sopesar varios factores antes de decidir. Aquí, hemos cubierto todos los beneficios y desventajas de SaaS, PaaS e IaaS para ayudarlo a decidir qué modelo es mejor para su empresa.

servicio basado en la nubehttps://litslink.com/blog/iaas-paas-saas

IaaS

Esencialmente, esta es una versión virtual de un centro de datos físico. Los proveedores de infraestructura en la nube utilizan la tecnología de virtualización para ofrecer recursos informáticos escalables a sus clientes, incluidos servidores, redes y almacenamiento. Los clientes se benefician de esto ya que no pueden comprar hardware personal y administrar sus componentes. En lugar de implementar sus aplicaciones y plataformas en centros de datos físicos, pueden usar las máquinas virtuales del proveedor. El proveedor de IaaS gestiona toda la infraestructura, pero los usuarios la controlan por completo. Los usuarios instalan y mantienen las aplicaciones y los sistemas operativos, así como la seguridad, el tiempo de ejecución, el middleware y los datos.

Ventajas de IaaS:

1. Modelo con mayor flexibilidad y potencial dinámico.

2. Debido a los precios de pago por uso, es rentable.

3. La implementación de hardware automatizada facilita su uso.

4. Los empleados tienen más tiempo para otras tareas porque las tareas de gestión están virtualizadas.

Desventajas de IaaS:

1. La arquitectura multiusuario plantea riesgos de seguridad.

2. Los clientes no pueden acceder a sus datos durante algún tiempo debido a interrupciones del proveedor.

3. Aprender a administrar una nueva infraestructura requiere capacitación en equipo.

PaaS

PaaS, o plataforma como servicio, es un marco basado en Internet para crear software. Esta plataforma contiene componentes de software y herramientas que los desarrolladores pueden usar para crear, personalizar, probar y ejecutar aplicaciones. Los proveedores de PaaS administran servidores, actualizaciones del sistema operativo, parches de seguridad y copias de seguridad. Los desarrolladores de aplicaciones y los administradores de datos no tienen que preocuparse por mantener la infraestructura, el middleware y los sistemas operativos. IaaS y PaaS difieren principalmente en la cantidad de control que se otorga a los usuarios.

Ventajas de PaaS:

1. Dado que el software creado por PaaS está basado en la nube, es altamente escalable, disponible y multiusuario.

2. Agilizar y acelerar el proceso de desarrollo.

3. Se reduce el costo de crear, probar y lanzar aplicaciones.

4. Automatización de políticas.

5. Una reducción en la cantidad de codificación requerida.

Desventajas de PaaS:

1. Cuestiones relacionadas con la seguridad de los datos.

2. No es posible habilitar en la nube todos los elementos de la infraestructura existente.

3. Velocidad, confiabilidad y soporte según el proveedor.

SaaS

El proveedor proporciona software basado en la nube con esta oferta. Las aplicaciones SaaS no necesitan descargarse e instalarse en dispositivos locales, pero los complementos pueden ser necesarios ocasionalmente. Se puede acceder al software SaaS a través de la web a través de API y se encuentra en una red de nube distante. Los clientes pueden trabajar juntos en proyectos, almacenar datos y analizarlos con estas aplicaciones.

El tipo más popular de computación en la nube es SaaS. Todo, desde la estabilidad del hardware hasta la funcionalidad de la aplicación, es administrado por el proveedor de SaaS. En este arreglo, los clientes son los únicos responsables de utilizar los programas para realizar sus trabajos. En este caso, el proveedor controla la experiencia de software del cliente.

Ventajas de SaaS:

1. No hay costos de hardware y no se incurre en costos de configuración inicial.

2. Las actualizaciones se realizan automáticamente.

3. Adaptabilidad a múltiples dispositivos.

4. Fácilmente accesible desde cualquier lugar, Un modelo de pago por uso.

5. Adaptabilidad, la personalización es fácil.

Desventajas de SaaS:

1. Falta de control.

2. Las soluciones son limitadas.

3. No se puede exagerar la necesidad de conectividad.

Diferencia entre IaaS, PaaS y SaaS

servicios basados ​​en la nube

https://www.quora.com/Cuál-es-la-diferencia-entre-IaaS-SaaS-y-Paas

 IaaSPaaSSaaS
primero.   IaaS significa Infraestructura como Servicio
 
PaaS significa Plataforma como servicio.
 
SaaS significa software como servicio.
 
2.   Como parte de IaaS, el proveedor de la nube administra la
infraestructura.
 
Como parte de PaaS, el proveedor de la nube administra
tanto la infraestructura como la plataforma. 
 
Como parte de SaaS, el proveedor de la nube administra toda
la infraestructura, las plataformas y el software.
 
3.   En IaaS, debe administrar la plataforma y el software.En PaaS, debe administrar el software. Como usuario de SaaS, no necesita administrar
nada.
 
4.   La infraestructura como servicio (IaaS) se puede utilizar para la recuperación de datos, el almacenamiento, las pruebas de software y el desarrollo.La plataforma como servicio se puede utilizar para
el desarrollo y la gestión de marcos, así como para la inteligencia empresarial.
 
 El software como servicio (SaaS) permite a los usuarios utilizar aplicaciones para fines personales o comerciales.
5.   Las plataformas IaaS son altamente escalables.
 
Las plataformas PaaS permiten a los clientes escalar los recursos informáticos de acuerdo con el tamaño de su empresa.El modelo SaaS es escalable con diferentes niveles de precios para cada nivel de negocio.
6.   Los proveedores controlan completamente la infraestructura.Debido a las capacidades limitadas de las plataformas PaaS, es posible que los usuarios no puedan personalizar las operaciones en la nube. Se requiere una conexión a Internet y un navegador para que los usuarios utilicen aplicaciones SaaS.
 
    

Conclusión

Después de leer todo el material anterior, comprenderá el valor de los servicios en la nube y por qué son tan apreciados por las empresas. Las ventajas de las soluciones en la nube son enormes. Por lo tanto, no sorprende que este sector económico esté experimentando una expansión tan fuerte. La elección de cualquier modelo de la lista anterior depende completamente de las necesidades de su negocio y del tipo de tarea que desee realizar.

Conclusiones clave:

  • Varias palabras técnicas están relacionadas con la computación en la nube, pero IaaS, PaaS y SaaS son las más importantes.
  • Se consideran los tres pilares clave que brindan estabilidad a la computación en la nube.
  • Sus objetivos comerciales determinarán cuál de estos tres tipos seleccionará en última instancia.
  • Cada uno de los tres modelos de nube tiene características y capacidades únicas.
  • Es crucial comprender sus principales diferencias entre sí.
  • Ya sea que desee utilizar la nube para el almacenamiento, necesite una plataforma poderosa para crear aplicaciones personalizadas o desee un control total sobre su infraestructura, debe elegir el proveedor de nube correcto.
  • Pasar a los servicios en la nube es necesario para mantener la solidez organizativa de su empresa, independientemente de su opción.
  • Puede elegir usar solo un modelo de computación en la nube o los servicios de los tres modelos.
  • El tamaño y la complejidad de su organización determinarán esto.

Fuente: https://www.analyticsvidhya.com/blog/2022/07/diferentes-tipos-de-servicios-basados-en-la-nube/

#cloud #based #bigdata #Beginners 

Diferentes Tipos De Servicios Basados ​​en La Nube

Different Types of Cloud-based Services

Cloud computing is one of the fastest-growing IT technologies today. By 2025, 83% of enterprise workloads will be in the cloud. According to the IDC report, the world will spend $160 billion on cloud services and infrastructure in 2018. The cloud encompasses a variety of online services. It is important for businesses considering cloud services to understand the differences between IaaS, PaaS, and SaaS. You should choose the right model depending on your business requirements and the number of tasks you want to delegate or handle yourself. Selecting the ideal cloud service is undoubtedly difficult, and you must weigh several factors before deciding. Here, we have covered all of the benefits and drawbacks of SaaS, PaaS, and IaaS to help you decide which model is best for your company.

See more at: https://www.analyticsvidhya.com/blog/2022/07/different-types-of-cloud-based-services/

#cloud #based #bigdata #Beginners 

Different Types of Cloud-based Services
黎 飞

黎 飞

1650638640

【程式語言入門須知】上集 | 新手該學哪個程式語言?工程師都用什麼程式語言?最強程式語言是?

關於程式語言 -入門該學哪個程式語言?工程師都用什麼程式語言?最強程式語言是?| Programming Languages for Beginners
-
學習程式設計,新手要學什麼程式語言?Python, Java, C++, JavaScript ... 程式語言種類那麼多,哪個程式語言最適合初學入門者?哪個程式語言最受歡迎最厲害最強大?工程師又都用什麼程式語言呢?對啊我是工程師是寫什麼程式語言的工程師?

對啊我是工程師很常被問到這類問題,所以,這次會分享我對程式語言的介紹與看法,以及初學者如何選擇並學習程式語言,並分享學習程式設計前,要有的程式語言基本概念。釐清一些大家對程式語言常有的誤會,或許能讓你在學習的路上少一點困惑。

【下集】
程式語言入門須知-上集 | 新手該學哪個程式語言?工程師都用什麼程式語言?最強程式語言是?

Untyped - There are so many data types in the world of computer science, so are the people who write the code. We aim to UNTYPE the stereotype of engineers and of how coding is only for a certain type of people.
對啊我是工程師:一個喜歡電腦科學邏輯推理,在科技圈努力為性別平等奮鬥的女工程師。

#programminglanguage #code #Beginners 

【程式語言入門須知】上集 | 新手該學哪個程式語言?工程師都用什麼程式語言?最強程式語言是?

プログラミング初心者が1つ目に勉強すべき言語は?

プログラミング初心者の方から質問を頂いたので回答しました!
プログラミング言語ってたくさんあってどれ勉強するのがいいのか迷いますよね。

 #programming #Beginners 

プログラミング初心者が1つ目に勉強すべき言語は?
山本  洋介

山本 洋介

1649944815

20分で分かる!無料で作る方法やHTMLなど初心者向けに解説

ホームページの作り方を初心者むけに解説。「無料で作るにはどうしたら良いの?」「ドメインやHTMLとは?」などホームページ作成の基本はこの動画でバッチリ!
【20分で分かる!ホームページ作成 完全ガイド】

✅ホームページ作り方のコツ
ホームページは無料で作ることも出来ますが、目的を見失わないようにしましょう!
「ホームページを無料で作成すること」が目的ではなく、
「ホームページを作成して集客したい」
「勉強目的でホームページを作成してみたい」
など、ホームページを作る目的を達成することが大事になります。

この動画では、そんなホームページの作成方法について
初心者向けにわかりやすく解説していますので、ぜひ最後まで動画をご覧ください

✅目次
00:00 ホームページの作り方〜イントロ
01:16 ホームページの作り方
01:45 ホームページが動く仕組み(ドメイン、サーバー、HTML)
04:25 有料ホームページと無料ホームページの違い
08:26 無料ホームページ作成サービス比較(WIX, Jimdo)
10:40 WordPressとは
11:25 ホームページは自作と外注どっちがいい?
16:48 ホームページの作り方〜まとめ

✅お仕事依頼はこちら
 

#html #Beginners #wordpress 

 20分で分かる!無料で作る方法やHTMLなど初心者向けに解説
Dipesh Malvia

Dipesh Malvia

1649943545

React Testing Library With Jest Tutorial For Beginners | How To Test React Components ?

React Testing Library With Jest Tutorial For Beginners | How To Test React Components ?

In this video we will learn about unit testing in React application using React testing library for testing React components and Jest as test runner. This will be a beginner friendly tutorial and we will first understand what is React Testing Library, some rules and how jest is associated with it and after that we will write the unit test cases for our React Login application. 

⭐️ GitHub link for Reference - https://github.com/dmalvia/React-testing-Library-Tutorial

⭐️ React Testing Library - https://testing-library.com/

⭐️ Support my channel - https://www.buymeacoffee.com/dipeshmalvia

🔗 React Roadmap for Developers in 2021

🔗 Social Medias 🔗 

⭐️ Tags ⭐️ - React Testing Library Crash Course - React Testing Library Tutorial - How to Test React Components - Learn React Testing Library With Login Form - Start Testing In ReactJs 

⭐️ Hashtags ⭐️ #React #Testing #Library #Beginners #Tutorials 

Disclaimer: It doesn't feel good to have a disclaimer in every video but this is how the world is right now. All videos are for educational purpose and use them wisely. Any video may have a slight mistake, please take decisions based on your research. This video is not forcing anything on you.

https://youtu.be/v6LK5alOofs

 

React Testing Library With Jest Tutorial For Beginners | How To Test React Components ?