1656906900
이 Python 자습서에서는 Python의 분해 연산자(`*` 및 `**`)와 함수, 목록 및 사전과 함께 사용하는 방법을 배웁니다.
대부분의 개발자는 Python에서 별표( *
) 문자를 곱셈 연산자로 알고 있습니다.
product = 4 * 2 # 8
그러나 별표는 목록 또는 사전 데이터 구조에 대해 몇 가지 특별한 의미를 갖습니다.
*args
그리고**kwargs
*args
함수 정의에서구조화 연산자라고도 하는 Python에서 별표 연산자의 가장 널리 알려진 사용법은 함수에서의 사용법입니다.
값을 더하고 이 값의 합계를 반환하는 함수가 있다고 가정해 보겠습니다.
def add(number_1, number_2):
return number_1 + number_2
print(add(1,2)) # 3
임의의 수의 값을 합산하려면 어떻게 해야 합니까? 다음과 같이 인수 이름 앞에 별표를 추가할 수 있습니다.
def add(*numbers):
sum = 0
for number in numbers:
sum += number
return sum
함수의 본문에서 이미 눈치채셨겠지만, 우리 numbers
는 iterable이 될 것으로 예상합니다. 실제로 유형을 확인하면 numbers
입니다 tuple
. 그리고 실제로 이제 임의의 수의 인수를 사용하여 함수를 호출할 수 있습니다.
add(1, 2, 3, 4) # 10
*
함수 호출에서지금까지 매개변수 목록을 취하도록 함수를 정의할 수 있음을 보았습니다. 그러나 고정된 인수 집합이 있는 함수가 있고 값 목록을 전달하려는 경우에는 어떻게 될까요? 다음 기능을 고려하십시오.
def add(number_1, number_2, number_3):
return number_1 + number_2 + number_3
이 함수는 정확히 3개의 매개변수를 사용합니다. 정확히 세 개의 요소가 있는 목록이 있다고 가정해 보겠습니다. 물론 다음과 같이 함수를 호출할 수 있습니다.
my_list = [1, 2, 3]
add(my_list[0], my_list[1], my_list[2])
운 좋게도 구조 분해 연산자( *
)는 두 가지 방식으로 작동합니다. 우리는 이미 함수 정의에서 사용법을 보았지만 함수를 호출하는 데 사용할 수도 있습니다.
my_list = [1, 2, 3]
add(*my_list)
**kwargs
함수 정의에서별표( ) 연산자로 목록을 구조화할 수 있는 것과 같은 방식으로 , 파이썬 함수에서 사전을 구조화 *
하기 위해 이중 별표( ) 연산자를 사용할 수 있습니다 .**
다음과 같은 함수를 고려하십시오.
def change_user_details(username, email, phone, date_of_birth, street_address):
user = get_user(username)
user.email = email
user.phone = phone
...
키워드 인수( kwargs
)로 호출하면 함수 호출은 다음과 같을 수 있습니다.
change_user_details('bascodes', email='blog@bascodes.example.com', phone='...', ...)
그 경우에 우리는 다음과 같은 사전으로 표현되는 임의의 수의 키워드 인자를 받아들이도록 우리의 함수를 다음과 같이 다시 작성할 수 있습니다 kwargs
:
def change_user_details(username, **kwargs):
user = get_user(username)
user.email = kwargs['email']
user.phone = kwargs['phone']
...
물론 kwargs
Python의 다른 사전처럼 사전을 사용할 수 있으므로 실제로 다음과 같이 사전 데이터 구조를 활용하면 함수가 좀 더 깔끔해질 수 있습니다.
def change_user_details(username, **kwargs):
user = get_user(username)
for attribute, value in kwargs.items():
setattr(user, attribute, value)
...
**
함수 호출에서물론 **
연산자는 함수 호출에도 사용됩니다.
details = {
'email': 'blog@bascodes.example.com',
...
}
change_user_detail('bascodes', **details)
함수 정의에서 별표의 가장 놀라운 기능 중 하나는 독립 실행형, 즉 변수(매개변수) 이름 없이 사용할 수 있다는 것입니다. 즉, 이것은 Python에서 완벽하게 유효한 함수 정의입니다.
def my_function(*, keyword_arg_1):
...
그러나 이 경우 독립형 별표는 무엇을 합니까? 별표는 위에서 본 것처럼 목록의 모든 (키워드가 아닌) 인수를 포착합니다. 우리의 경우 목록을 만드는 변수 이름이 없습니다. 다음 *
에 라는 변수가 keyword_arg_1
있습니다. 이미 *
모든 위치 인수와 일치했으므로 keyword_arg_1
키워드 인수로 사용해야 하는 가 남습니다.
위의 함수를 호출하면 my_function(1)
오류가 발생합니다.
TypeError: my_function() takes 0 positional arguments but 1 was given
마지막 예제의 키워드 인수 가 아닌 위치 인수만 사용하도록 함수 사용자를 강제하려면 어떻게 해야 할까요?
글쎄요, 아주 파이썬적인 방법이 있습니다. /
우리 는 트릭을 수행하기 위해 부호(곱셈의 반대)를 해석합니다 .
def only_positional_arguments(arg1, arg2, /):
...
놀랍게도 PEP 570 을 통해 Python 3.8에 도입된 이 트릭에 대해 아는 Python 개발자는 거의 없습니다 .
로 마지막 함수를 호출하면 only_positional_arguments(arg1=1, arg2=2)
TypeError가 발생합니다.
TypeError: only_positional_arguments() got some positional-only arguments passed as keyword arguments: 'arg1, arg2'
*
및 사용**
별표( *
) 및 이중 별표( **
) 연산자는 함수 정의 및 호출에 대해 작동할 뿐만 아니라 목록 및 사전을 구성하는 데 사용할 수도 있습니다.
두 개의 목록이 있고 병합하려고 한다고 가정해 보겠습니다.
my_list_1 = [1, 2, 3]
my_list_2 = [10, 20, 30]
물론 이러한 목록을 +
연산자와 병합할 수 있습니다.
merged_list = my_list_1 + my_list_2
그러나 *
연산자는 우리에게 약간의 유연성을 제공합니다. 예를 들어 중간에 스칼라 값을 포함하려면 다음을 사용할 수 있습니다.
some_value = 42
merged_list = [*my_list_1, some_value, *my_list_2]
# [1, 2, 3, 42, 10, 20, 30]
다시 말하지만, 목록과 별표( *
) 연산자에 대해 참인 것은 사전과 이중 별표 연산자( **
)에 대해 참입니다.
social_media_details = {
'twitter': 'bascodes'
}
contact_details = {
'email': 'blog@bascodes.example.com'
}
user_dict = {'username': 'bas', **social_media_details, **contact_details}
# {'email': 'blog@bascodes.example.com', 'twitter': 'bascodes', 'username': 'bas'}
다음과 같이 목록의 요소를 여러 변수로 분할할 수 있다는 것을 이미 알고 있을 것입니다.
my_list = [1, 2, 3]
a, b, c = my_list
# a -> 1
# b -> 2
# c -> 3
*
그러나 임의의 길이 목록이 있을 때 별표( )를 사용하여 변수에 할당할 수 있다는 것을 알고 계 셨습니까?
특정 변수에 있는 목록의 첫 번째 요소와 마지막 요소를 원한다고 가정해 보겠습니다.
다음과 같이 별표를 사용하여 이 작업을 수행할 수 있습니다.
my_list = [1, 2, 3]
a, *b, c = my_list
이 예에서는 a
이제 첫 번째 요소가 c
포함되고 의 마지막 요소가 포함 my_list
됩니다. 그러나 에는 무엇이 b
있습니까?
에는 b
첫 번째와 마지막 요소, 즉 를 제외한 전체 목록이 [2]
있습니다. 이제 b
목록입니다.
이 아이디어는 더 큰 목록을 볼 때 조금 더 명확해질 수 있습니다.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a, *b, c = my_list
# a -> 1
# b -> [2, 3, 4, 5, 6, 7, 8, 9]
# c -> 10
https://bas.codes 의 원본 기사 출처
#python
1656906900
이 Python 자습서에서는 Python의 분해 연산자(`*` 및 `**`)와 함수, 목록 및 사전과 함께 사용하는 방법을 배웁니다.
대부분의 개발자는 Python에서 별표( *
) 문자를 곱셈 연산자로 알고 있습니다.
product = 4 * 2 # 8
그러나 별표는 목록 또는 사전 데이터 구조에 대해 몇 가지 특별한 의미를 갖습니다.
*args
그리고**kwargs
*args
함수 정의에서구조화 연산자라고도 하는 Python에서 별표 연산자의 가장 널리 알려진 사용법은 함수에서의 사용법입니다.
값을 더하고 이 값의 합계를 반환하는 함수가 있다고 가정해 보겠습니다.
def add(number_1, number_2):
return number_1 + number_2
print(add(1,2)) # 3
임의의 수의 값을 합산하려면 어떻게 해야 합니까? 다음과 같이 인수 이름 앞에 별표를 추가할 수 있습니다.
def add(*numbers):
sum = 0
for number in numbers:
sum += number
return sum
함수의 본문에서 이미 눈치채셨겠지만, 우리 numbers
는 iterable이 될 것으로 예상합니다. 실제로 유형을 확인하면 numbers
입니다 tuple
. 그리고 실제로 이제 임의의 수의 인수를 사용하여 함수를 호출할 수 있습니다.
add(1, 2, 3, 4) # 10
*
함수 호출에서지금까지 매개변수 목록을 취하도록 함수를 정의할 수 있음을 보았습니다. 그러나 고정된 인수 집합이 있는 함수가 있고 값 목록을 전달하려는 경우에는 어떻게 될까요? 다음 기능을 고려하십시오.
def add(number_1, number_2, number_3):
return number_1 + number_2 + number_3
이 함수는 정확히 3개의 매개변수를 사용합니다. 정확히 세 개의 요소가 있는 목록이 있다고 가정해 보겠습니다. 물론 다음과 같이 함수를 호출할 수 있습니다.
my_list = [1, 2, 3]
add(my_list[0], my_list[1], my_list[2])
운 좋게도 구조 분해 연산자( *
)는 두 가지 방식으로 작동합니다. 우리는 이미 함수 정의에서 사용법을 보았지만 함수를 호출하는 데 사용할 수도 있습니다.
my_list = [1, 2, 3]
add(*my_list)
**kwargs
함수 정의에서별표( ) 연산자로 목록을 구조화할 수 있는 것과 같은 방식으로 , 파이썬 함수에서 사전을 구조화 *
하기 위해 이중 별표( ) 연산자를 사용할 수 있습니다 .**
다음과 같은 함수를 고려하십시오.
def change_user_details(username, email, phone, date_of_birth, street_address):
user = get_user(username)
user.email = email
user.phone = phone
...
키워드 인수( kwargs
)로 호출하면 함수 호출은 다음과 같을 수 있습니다.
change_user_details('bascodes', email='blog@bascodes.example.com', phone='...', ...)
그 경우에 우리는 다음과 같은 사전으로 표현되는 임의의 수의 키워드 인자를 받아들이도록 우리의 함수를 다음과 같이 다시 작성할 수 있습니다 kwargs
:
def change_user_details(username, **kwargs):
user = get_user(username)
user.email = kwargs['email']
user.phone = kwargs['phone']
...
물론 kwargs
Python의 다른 사전처럼 사전을 사용할 수 있으므로 실제로 다음과 같이 사전 데이터 구조를 활용하면 함수가 좀 더 깔끔해질 수 있습니다.
def change_user_details(username, **kwargs):
user = get_user(username)
for attribute, value in kwargs.items():
setattr(user, attribute, value)
...
**
함수 호출에서물론 **
연산자는 함수 호출에도 사용됩니다.
details = {
'email': 'blog@bascodes.example.com',
...
}
change_user_detail('bascodes', **details)
함수 정의에서 별표의 가장 놀라운 기능 중 하나는 독립 실행형, 즉 변수(매개변수) 이름 없이 사용할 수 있다는 것입니다. 즉, 이것은 Python에서 완벽하게 유효한 함수 정의입니다.
def my_function(*, keyword_arg_1):
...
그러나 이 경우 독립형 별표는 무엇을 합니까? 별표는 위에서 본 것처럼 목록의 모든 (키워드가 아닌) 인수를 포착합니다. 우리의 경우 목록을 만드는 변수 이름이 없습니다. 다음 *
에 라는 변수가 keyword_arg_1
있습니다. 이미 *
모든 위치 인수와 일치했으므로 keyword_arg_1
키워드 인수로 사용해야 하는 가 남습니다.
위의 함수를 호출하면 my_function(1)
오류가 발생합니다.
TypeError: my_function() takes 0 positional arguments but 1 was given
마지막 예제의 키워드 인수 가 아닌 위치 인수만 사용하도록 함수 사용자를 강제하려면 어떻게 해야 할까요?
글쎄요, 아주 파이썬적인 방법이 있습니다. /
우리 는 트릭을 수행하기 위해 부호(곱셈의 반대)를 해석합니다 .
def only_positional_arguments(arg1, arg2, /):
...
놀랍게도 PEP 570 을 통해 Python 3.8에 도입된 이 트릭에 대해 아는 Python 개발자는 거의 없습니다 .
로 마지막 함수를 호출하면 only_positional_arguments(arg1=1, arg2=2)
TypeError가 발생합니다.
TypeError: only_positional_arguments() got some positional-only arguments passed as keyword arguments: 'arg1, arg2'
*
및 사용**
별표( *
) 및 이중 별표( **
) 연산자는 함수 정의 및 호출에 대해 작동할 뿐만 아니라 목록 및 사전을 구성하는 데 사용할 수도 있습니다.
두 개의 목록이 있고 병합하려고 한다고 가정해 보겠습니다.
my_list_1 = [1, 2, 3]
my_list_2 = [10, 20, 30]
물론 이러한 목록을 +
연산자와 병합할 수 있습니다.
merged_list = my_list_1 + my_list_2
그러나 *
연산자는 우리에게 약간의 유연성을 제공합니다. 예를 들어 중간에 스칼라 값을 포함하려면 다음을 사용할 수 있습니다.
some_value = 42
merged_list = [*my_list_1, some_value, *my_list_2]
# [1, 2, 3, 42, 10, 20, 30]
다시 말하지만, 목록과 별표( *
) 연산자에 대해 참인 것은 사전과 이중 별표 연산자( **
)에 대해 참입니다.
social_media_details = {
'twitter': 'bascodes'
}
contact_details = {
'email': 'blog@bascodes.example.com'
}
user_dict = {'username': 'bas', **social_media_details, **contact_details}
# {'email': 'blog@bascodes.example.com', 'twitter': 'bascodes', 'username': 'bas'}
다음과 같이 목록의 요소를 여러 변수로 분할할 수 있다는 것을 이미 알고 있을 것입니다.
my_list = [1, 2, 3]
a, b, c = my_list
# a -> 1
# b -> 2
# c -> 3
*
그러나 임의의 길이 목록이 있을 때 별표( )를 사용하여 변수에 할당할 수 있다는 것을 알고 계 셨습니까?
특정 변수에 있는 목록의 첫 번째 요소와 마지막 요소를 원한다고 가정해 보겠습니다.
다음과 같이 별표를 사용하여 이 작업을 수행할 수 있습니다.
my_list = [1, 2, 3]
a, *b, c = my_list
이 예에서는 a
이제 첫 번째 요소가 c
포함되고 의 마지막 요소가 포함 my_list
됩니다. 그러나 에는 무엇이 b
있습니까?
에는 b
첫 번째와 마지막 요소, 즉 를 제외한 전체 목록이 [2]
있습니다. 이제 b
목록입니다.
이 아이디어는 더 큰 목록을 볼 때 조금 더 명확해질 수 있습니다.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a, *b, c = my_list
# a -> 1
# b -> [2, 3, 4, 5, 6, 7, 8, 9]
# c -> 10
https://bas.codes 의 원본 기사 출처
#python
1679991844
Git 및 GitHub 리포지토리를 만들고 동기화하는 방법을 알아보세요. 이 자습서에서는 다음을 배웁니다. Git, GitHub 및 리포지토리는 무엇을 의미합니까? 힘내와 GitHub를 설치하는 방법? 로컬 리포지토리를 만드는 방법은 무엇입니까? 로컬 및 원격 리포지토리를 동기화하는 방법은 무엇입니까? 리포지토리를 복제하는 방법? 원격 GitHub 리포지토리를 만드는 방법은 무엇입니까? 그리고 더
Git 및 GitHub 작업은 종종 일상적인 프로그래밍 작업의 필수 부분입니다. 대부분의 경우 프로젝트에 대한 로컬 Git 리포지토리와 원격 GitHub 리포지토리가 모두 필요합니다.
이 자습서에서는 두 가지 시나리오를 살펴봅니다.
이 튜토리얼에서 다룰 내용은 다음과 같습니다.
Let's start with a brief introduction to the terms we're using, then jump into our two scenarios.
What Do Git, GitHub, and Repository Mean?
A repository, or "repo" for short, stores and tracks the versions of your project files. As you make changes to those files, you commit (or copy) those files into the repository for safekeeping. The repository keeps a list of all your committed changes, called a commit history.
Git is a popular and widely used version control system for creating and working with repositories. It runs locally on your computer. You can download, install, and use Git on any platform without any cost or fees. With Git, you create a local repository in your project's working folder and Git stores the commit history for the files in that folder.
If you are new to Git, consider watching this video for an introduction:
GitHub is a website that hosts remote repositories on the internet. A basic GitHub account is also free. Use GitHub to create a remote repository for your project. With a remote repository, you can store your code offsite, collaborate with others, work on company or open-source projects, and show off your portfolio to potential employers.
If you are new to GitHub, consider watching this video for an introduction:
Before jumping into our scenarios, we need to install Git and create a GitHub account.
How to Install Git and GitHub
If you'd like to work through the examples presented in this tutorial, there are a few preparatory steps. But feel free to skip to the next section if you already have these tools installed or prefer to read this article without coding along.
First, install Git on your computer if you don't already have it. For step-by-step instructions on installing Git, see the second part of this video:
Next, create a GitHub account, if you don't already have one. This video provides step-by-step instructions on creating a GitHub account:
Lastly, create a working folder on your computer (I named mine recipes in my documents folder). Then create two simple text files in that folder: file1.txt and file2.txt. Even though we are using text files, the synchronization process covered in this article is the same with any type of code files.
Now we are ready to walk through our two scenarios: local first and remote first.
Scenario 1: Local First
Say that you want to build a recipes website (or maybe an app) for collecting and managing recipes. You create a local repository so you can easily track your changes to the project files.
You later decide that you also want a remote repository to keep a copy of your files offsite and to share the project with others. Once you have the remote repository, you want to keep your local repository in sync with that remote repository.
This scenario is shown in Figure 1:
Figure 1. Creating a local repository first.
By the numbers on Figure 1:
Let's walk through these steps in detail.
We've already prepared a working folder and created two files that are the start of our project.
To create a local repository for that project, open your terminal or command prompt and navigate to that working folder.
Then initialize a new Git repository using the following command:
git init
This command initializes a new Git repository in the current folder. The initialization process creates a .git folder within the project folder that stores the files and data for the repository.
This .git folder may be hidden by default. In Mac's Finder, use Command + Shift + . (period) to make hidden folders and files appear. On Windows, use the File Explorer View tab and check Hidden items to display hidden folders and files.
We now have a local repository! Let's commit our two project files to that repository.
Whenever we create new files, change existing files, or delete files, we commit those changes to our local repository. This ensures that the repository tracks the current status of our project.
Committing files to a local repository requires two steps:
First, add the files to the Git staging area:
git add .
We tell Git which files we want to include in that commit by adding them to a staging area. Staging allows us to selectively choose which changes to include in a commit.
(마침표) 를 사용하면 .작업 폴더(및 해당 하위 폴더)의 모든 파일이 준비 영역에 추가됩니다. 특정 파일만 추가하려는 경우 대신 나열할 수 있습니다.
다음으로 준비된 파일을 로컬 리포지토리에 커밋합니다.
git commit -m "Initial commit"
이 명령은 Git 스테이징 영역의 파일을 로컬 리포지토리에 커밋합니다.
옵션 은 -m커밋 메시지용입니다. -m메시지를 따옴표로 묶습니다 . 커밋하려는 변경 사항을 설명하는 명확한 메시지를 정의해야 합니다.
훌륭한 커밋 메시지를 정의하는 방법에 대한 자세한 내용은 다음 비디오를 참조하십시오.
이 단계 후에 터미널은 아래와 같이 나타납니다.
그림 2. 로컬 리포지토리를 만든 다음 프로젝트 파일을 준비하고 커밋합니다.
이 init명령은 빈 Git 리포지토리를 생성했음을 알리는 상태 메시지를 표시합니다.
이 add명령은 출력을 제공하지 않습니다.
이 commit명령은 우리가 있는 분기( main이 예에서는), 커밋 ID의 처음 몇 문자 및 커밋 메시지를 표시합니다. 그런 다음 변경된 파일을 나열합니다. 이 예에서는 2개의 파일이 변경되었으며 둘 다 삽입(새 파일)이었습니다.
뒤의 숫자는 create mode파일 형식과 권한을 나타냅니다. 100644소유자 읽기 및 쓰기 권한이 있는 폴더가 아닌 일반 파일임을 의미합니다.
로컬 리포지토리가 준비되었으면 이제 원격 리포지토리를 만들 차례입니다.
이제 GitHub를 사용하여 GitHub에 원격 저장소를 생성합니다. GitHub 웹 사이트 (www.github.com) 로 이동하여 로그인합니다. GitHub 계정이 없는 경우 이 자습서 앞부분의 "Git 및 GitHub 설치 방법" 섹션에서 계정 생성 단계를 참조하십시오.
GitHub 리포지토리를 만드는 과정을 보려면 이 비디오를 확인하세요.
GitHub에 로그인하면 개인 대시보드로 이동됩니다. GitHub 개인 대시보드는 리포지토리 및 프로젝트에 대한 정보를 제공합니다.
GitHub에서 리포지토리를 처음 만드는 경우 Create Repository시작하는 데 도움이 되는 버튼이 제공됩니다. 이미 GitHub를 사용하고 있다면 New대신 버튼이 표시됩니다.
두 경우 모두 버튼을 클릭하면 Create a new repository그림 3과 같은 페이지로 이동합니다.
Figure 3. Create a new remote repository with GitHub.
Start by entering the repository name. A repository name should be short, but descriptive of your project. It must be unique within your GitHub account. GitHub checks that for you.
General conventions for repository names suggest using lower case. If there are multiple words, use dashes between the words, such as recipe-book.
I called my repository recipes. And the green arrow next to the name means that it's unique within this GitHub account.
Optionally, you can provide a description. This is where you can put more information about the repository, if desired.
Next, you have the option of creating a public or private repository. If you create a public repository, anyone on the internet can see it. But only collaborators that you pick can commit to it. So you don't have to worry about strangers changing your files. If you create a private repository, it's private except for your chosen collaborators.
Consider making your repos public to share your code with others, unless your code is proprietary.
You then have the option to create a readme file. A readme file gives those looking at a repository an idea of what that repository is for and instructions on using it. Check the box to add a readme file.
A .gitignore template helps you identify which files in your working folder you do not want to include in Git's version tracking. For an application, you don't want to include intermediate build files, for example, as they are often large and can easily be rebuilt from source files. For this simple project, we don't need a .gitignore template.
Choosing a license is next. A license lets other developers know what they can do with the code in your repo. For example, whether they could freely use the code for their own projects.
GitHub provides a website to help you make your decision. Click learn more under the Choose a license option to go to the GitHub documentation. On the documentation page, you'll find a choosealicense.com link for help in selecting which license makes sense for your project.
For my recipes repository, I'll make the license simple and permissive and pick an MIT license.
Close the documentation browser tab, go back to the GitHub tab, and select the desired license from the list.
Just above the Create repository button, GitHub provides a summary so you can double check the action you are about to perform. Then click Create repository.
It creates the repo as shown in Figure 4. Nice!
Figure 4. Our GitHub remote repository.
As you can see in Figure 4, GitHub automatically performed our first commit! That commit is a snapshot of the two files we told it to add to the repository: our license file and readme. It set a commit message of "Initial commit". And by default, GitHub displays the content of our readme file.
At this point, our local repository contains our two text files. And our remote repository contains our license and readme files. We want the two repositories to match.
Before you can synchronize the local and remote repositories, you need to establish a connection between them. Basically, you need to tell your local repository where to find the remote repository.
We identify a remote repository by its URL. In Figure 4 above, notice the green Code button. Click that button to view details about the repository (Figure 5).
Figure 5. Finding the URL to the GitHub repository.
Ensure that the HTTPS tab is selected, and click the copy icon to copy the URL for this GitHub repository.
Back in the command window on your local machine, add the remote repository to the local repository. Then list the remotes to confirm that the remote was created.
git remote add recipes-gh https://github.com/DeborahK/recipes.git
git remote
The remote add command adds the remote repository at the provided URL. And it lets you assign a nickname for that repository so you don't have to type the URL when referring to the remote repository.
A common nickname for the remote repository is origin, but some find that name a bit confusing, especially if the remote repository was not the origin of the project. In that case, I sometimes use the name of the local repository with a -gh (for GitHub) as the remote repository nickname, so I can easily remember it. But feel free to use any name.
The remote command by itself displays the list of remotes that your local repository knows about. Here's what that looks like:
Figure 6. Establishing a connection to the remote repository.
Our local Git repository now knows where to find its associated remote repository. The next step is to synchronize the repositories so their commit history matches.
To synchronize our local and remote repositories, we first fetch the change history from the remote repository and merge it into our local repository using the pull command. Then we push our local change history to the remote repository using the push command.
If you would prefer to sync repositories using VS Code, check out this video:
To pull from the remote repository and merge to our local repository using a Git command:
git pull recipes-gh main --allow-unrelated-histories
dir // On windows
OR
ls // On a mac
The pull command requires the nickname of the remote repository (recipes-gh) and the name of the branch. Since we haven't created any additional branches, we specify the primary branch (main).
The --allow-unrelated-histories flag is required the first time we pull because we want to merge two repositories that were created separately and don't currently share a related history.
After the first time, the git pull command doesn't require that flag:
git pull recipes-gh main
In either case, the pull command looks up the appropriate URL for the remote repository using the provided nickname ( recipes-gh ).
Then it fetches the commit history and other data from the specified branch ( main ) of the remote repository that is not in that branch of the local repository.
It merges that data into the local repository. If there are any conflicts, you'll need to manually resolve them before Git will merge the changes.
Lastly, it updates the local working folder with all files from the most recent commit.
Using the dir command on Windows, or the ls command on a Mac, we see that our local repository now has our original files plus the license and readme files from our remote repository as shown in Figure 7.
Figure 7. Pulling the change history from the remote repository.
Now our local repository contains all of the commit history from the remote repository.
Next, we push the change history from our local repository to our remote repository using the push command.
git push recipes-gh main
The push command requires the name of the remote repository (recipes-gh) and the name of the branch. Since we haven't created any additional branches, we specify the primary branch (main).
This command merges the local change history to the remote repository. If there are any conflicts, you'll need to manually resolve them before Git will merge the changes. See Figure 8 for the result:
Figure 8. Pushing the local change history to the remote repository.
To confirm that our remote repository includes all of our files, view the remote repository on GitHub. In Figure 9, we see the files from our local repository are now in our remote repository and our repositories are in sync!
Figure 9. Our remote repository with the files from our local repository.
In summary, syncing your local and remote repositories involves pulling any changes from the remote repository to your local repository, resolving conflicts, and then pushing your local changes back to the remote repository.
That's it for the first scenario. We created a local repository from our existing files. Then we created a remote repository, set up a connection to that remote repository, and synchronized our files. Repeat the pull and push commands to sync the repositories as you work on your project.
Scenario 2: Remote First
For our second scenario, the remote repository already exists. This will be the case if you join a team that has existing code in GitHub. Or if you want to work on an open source project. Or if you found some code on GitHub that you'd like to use as a starting point for your project.
You want to create your local repository from an existing remote repository. There are three basic ways to get code from a remote repository, as shown in Figure 10.
Figure 10. Getting code from a remote repository.
On the left side of Figure 10, we have one scenario: if you own or have access rights to modify the remote repository, you can clone the remote repository to create your local repository. You can then directly synchronize changes between the two repositories.
The second scenario is shown in the middle of Figure 10: if you don't own the remote repository or have access rights to modify it, use GitHub to fork the repository first. This creates a copy of the remote repository in your GitHub account. Then clone your copy to create your local repository.
This will be the case if you are working on an open source project or you want to use the code in someone else's repository as a starting point for your project.
The third scenario is shown on the right of Figure 10 – there is also the option to download a zip file of the code in the repository. This does not create a local repository. Use this option if you want to look at code from a GitHub repository, but don't plan on tracking changes to it.
To get set up for this scenario's example, you need a remote repository that does not currently have an associated local repository. You can use the recipes remote repository that you already created in the first scenario. If you'd rather use someone else's repository for this example, be sure to fork it first.
Once you have a remote repository, ensure there is no local repository associated with it. If you are using the recipes remote repository, delete the recipes folder from your local system. That deletes your local repository.
Now you are ready to create a new local repository from your remote repository on GitHub.
To create a local repository from a remote repository on GitHub, use the clone command.
If you'd rather clone a repository using the GitHub Desktop application, see this video:
To clone using a Git command, we first need the URL to the remote repository.
Navigate to GitHub, log in, and you'll see your personal dashboard. Locate the repository that you want to clone. Click the green Code button to view the details about the repository as shown earlier in Figure 5. Click the copy button next to the URL to copy it.
Next, open your terminal or command prompt on your computer. Navigate to the folder where you want to create the project's working folder. I'll navigate to my documents folder.
Then we are ready to clone that repository:
git clone https://github.com/DeborahK/recipes.git
The clone command requires the URL of the remote repository. We just copied that URL from GitHub, so paste it in as part of this command.
When the command is executed, it first creates the working folder for the repository using the remote repository name from the URL, which is recipes in this example. It then copies the commit history from the remote repository at the provided URL.
The cloning process also automatically links up the new local repository with the its remote repository. And it assigns the remote repository a nickname of origin. We can then reference the remote repository using that nickname instead of its URL.
Lastly, the cloning process copies all files from the most recent commit to the local working folder. You can then add, edit, or delete files in that working folder as you work locally on the project.
새 recipes폴더로 이동합니다. 그런 다음 remote명령을 사용하여 연결된 원격 저장소를 봅니다. 그리고 그림 11에 실제로 별명이 있음을 보여줍니다 origin.
그림 11. 저장소 복제.
그림 11에서 복제 작업의 출력을 확인하십시오. Git은 10개의 객체를 열거(또는 찾습니다)합니다. 원격 저장소 에는 4개의 파일만 있습니다 recipes. 그렇다면 왜 10개의 객체를 찾는 것일까요? 복제 프로세스가 파일뿐만 아니라 전체 커밋 기록을 복사하기 때문입니다.
개체 목록을 보려면 및 플래그 rev-list와 함께 명령을 사용합니다 .--objects--all
git rev-list --objects --all
그림 12는 해당 명령의 출력을 보여줍니다.
그림 12. 리포지토리의 개체 목록.
위의 각 개체는 SHA 또는 보안 해시 알고리즘 식별자로 표시됩니다. SHA는 리포지토리의 개체를 고유하게 식별하는 ID로 사용됩니다.
이 목록의 처음 세 개체(개체 1-3)는 이 리포지토리에 대한 세 커밋입니다. GitHub의 커밋 목록(그림 13)을 보면 각 커밋은 SHA의 처음 몇 글자를 표시합니다. 이들은 처음 세 개체와 일치합니다.
그림 12에 표시된 목록의 중간 개체(개체 5-8)는 커밋된 4개의 파일입니다.
나머지 세 개체(개체 4, 9, 10)는 트리 개체입니다. 트리 개체는 해당 폴더의 파일 및 하위 폴더를 포함하여 폴더의 상태를 나타냅니다. 폴더의 계층 구조를 유지합니다.
그림 13. 각각 SHA의 처음 몇 개 값으로 식별되는 커밋 기록.
dirWindows에서 명령을 사용하거나 lsMac에서 명령을 사용하면 이제 작업 폴더에 원격 저장소의 모든 파일이 포함되어 있음을 알 수 있습니다.
그림 14. 작업 폴더에 있는 파일의 디렉토리.
이제 리포지토리를 복제했으므로 로컬 및 원격 리포지토리가 일치합니다. 동기화 상태를 유지하기 위해 이 문서 앞부분의 "로컬 및 원격 리포지토리를 동기화하는 방법" 섹션에서 본 것처럼 pull및를 사용합니다 .push
Note that if you are working with a remote repository that you don't own, you may not have access to push your changes directly to the repository. Instead, you'll need to issue a pull request.
A pull request, or PR, tells the owners or other contributors that you've pushed changes and you're requesting that those changes be reviewed and pulled, or merged, into the remote repository.
See this video for more information on pull requests:
Wrapping Up
In the first scenario, we had existing code and created a local repository from that code. We then created a remote repository to keep a copy of the files offsite and share the project with others.
In the second scenario, we had an existing remote repository created in GitHub by our team or by an open source contributor. We then cloned that repository to create our local repository. That way we can work on our own copy of the project, and make and test changes independently before pushing those changes to the remote repository for others to review and merge.
Whether you create your local repository first, or your remote GitHub repository first, once you have both repositories in place you can keep them in sync with Git pull and push commands. Or by submitting pull requests, or PRs.
For more details on learning Git and GitHub, check out this course:
로컬 및 원격 리포지토리에 대한 확고한 이해와 동기화 유지 방법은 자신의 코드로 작업할 때 필수적입니다. 팀이나 오픈 소스 프로젝트에서 작업할 때는 더욱 중요합니다.
#git #github
1658987100
이 가이드에서는 HTML CSS 및 JavaScript를 사용하여 토글을 클릭하여 입력 필드에서 암호를 표시하고 숨기는 방법을 배웁니다. HTML, CSS 및 JavaScript를 사용하여 스위치 암호를 표시하거나 숨깁니다. 두 개의 파일 HTML, CSS를 만들어야 합니다.
1: 먼저 HTML 파일을 만듭니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!----==== CSS ====-->
<link rel="stylesheet" href="style.css">
<!----==== Icounscout Link ====-->
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
<!--<title>Password Show & Hide</title-->>
</head>
<body>
<div class="container">
<div class="input-box">
<input type="password" spellcheck="false" required>
<label for="">Password</label>
<i class="uil uil-eye-slash toggle"></i>
</div>
</div>
<script>
const toggle = document.querySelector(".toggle"),
input = document.querySelector("input");
toggle.addEventListener("click", () =>{
if(input.type ==="password"){
input.type = "text";
toggle.classList.replace("uil-eye-slash", "uil-eye");
}else{
input.type = "password";
}
})
</script>
</body>
</html>
/* Google Font Import - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
body{
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: #4070f4;
}
.container{
position: relative;
max-width: 340px;
width: 100%;
padding: 20px;
border-radius: 6px;
background-color: #fff;
}
.container .input-box{
position: relative;
height: 50px;
}
.input-box input{
position: absolute;
height: 100%;
width: 100%;
outline: none;
border: 2px solid #ccc;
border-radius: 6px;
padding: 0 35px 0 15px;
transition: all 0.2s linear;
}
input:is(:focus, :valid){
border-color: #4070f4;
}
.input-box :is(label, i){
position: absolute;
top: 50%;
transform: translateY(-50%);
color: #999;
transition: all 0.2s linear;
}
.input-box label{
left: 15px;
pointer-events: none;
font-size: 16px;
font-weight: 400;
}
input:is(:focus, :valid) ~ label{
color: #4070f4;
top: 0;
font-size: 12px;
font-weight: 500;
background-color: #fff;
}
.input-box i{
right: 15px;
cursor: pointer;
font-size: 20px;
}
input:is(:focus, :valid) ~ i{
color: #4070f4;
}
1678867589
Mac 및 Windows 컴퓨터에서 Python 및 Pip를 업데이트하는 방법을 알아보세요. Homebrew로 Python 및 Pip를 업데이트합니다. 설치 패키지를 다운로드하고 명령줄을 사용하여 Python 및 Pip를 업데이트합니다.
Python은 상대적으로 배우기 쉽고 널리 사용되는 강력한 프로그래밍 언어입니다.
Python은 몇 달마다 패치 업데이트를 릴리스하고 주요 업데이트는 1년에 한 번 정도 릴리스합니다. 이 때문에 항상 컴퓨터에 있는 Python 버전을 업데이트하는 것이 좋습니다.
또한 주요 업데이트 후에 추가되는 흥미로운 기능에 액세스할 수 있도록 Python을 업데이트해야 합니다. 예를 들어 Python 3.11은 3.10보다 속도가 상당히 향상되었습니다.
가끔 업데이트해야 하는 Pip이라는 Python 패키지 관리자도 있습니다. Python에서 NPM은 JavaScript와 같습니다.
Python 3.4부터 Pip은 표준 Python 배포판과 함께 제공됩니다. 그러나 어떤 이유로 Python을 설치한 후 얻지 못하면 수동으로 설치해야 합니다.
이 기사에서는 Mac 및 Windows 컴퓨터에서 Python을 업데이트하는 방법을 보여줍니다. 또한 두 운영 체제에서 Pip을 업데이트하는 방법도 보여드리겠습니다.
Mac에서 Python 및 Pip을 업데이트하는 가장 쉬운 방법 중 하나는 Python 공식 웹 사이트에서 패키지를 다운로드하는 것입니다.
Python을 업데이트하면 함께 제공되는 Pip 버전도 업데이트됩니다.
python3 --version먼저 다음을 실행하여 가지고 있는 Python 및 Pip의 버전을 확인합니다 pip3 --version.
https://www.python.org/downloads/macos/ 로 이동하여 원하는 릴리스를 선택합니다.
저에게는 3.11이제 안정적이기 때문에 선택했습니다.
아래로 스크롤하여 OS(Windows 또는 Mac)에 맞게 다운로드하십시오. Mac을 사용하기 때문에 Mac을 선택했습니다.
설치 프로그램을 실행하고 표시되는 모든 프롬프트를 따릅니다.
python3 --version다음을 실행하여 설치를 확인합니다 pip3 --version.
Mac을 사용하는 경우 Homebrew로 Python 및 Pip를 업데이트할 수도 있습니다.
pyenv를 실행하여 설치합니다 brew install pyenv. pyenvPython 버전 관리 도구입니다. NVM(노드 버전 관리자)이 JavaScript에 있는 것은 Python에 있습니다.
원하는 Python 버전(예: 3.9 또는 2.7)을 설치합니다.
를 실행하여 Python을 업데이트할 수도 있습니다 pyenv latest-version-number. 예를 들어, python 3.11. 해당 Python 버전을 설치하면 Pip도 설치됩니다.
Pip만 업데이트하려는 경우 터미널을 열고 pip3 install --upgrade pip. 그런 다음 다음을 실행하여 업데이트를 확인할 수 있습니다 pip3 --version.
이 문서에서는 설치 패키지를 다운로드하고 명령줄을 사용하여 Python 및 Pip를 업데이트하는 방법을 설명했습니다. 또한 원하는 경우에만 Pip을 업데이트하는 방법도 살펴보았습니다.
Windows를 사용 중이고 Python 및 Pip를 업데이트하려는 경우 최신 설치 프로그램을 다운로드하고 설치 마법사가 설치 과정을 안내하도록 할 수도 있습니다.
읽어 주셔서 감사합니다!
#python
1658917442
마이크로서비스 아키텍처의 개념을 배웁니다. Docker 컨테이너를 사용하여 .NET 및 C#에서 마이크로서비스 아키텍처를 구축, 배포 및 테스트하는 방법을 알아보세요.
마이크로서비스라는 용어는 대규모 소프트웨어 솔루션을 개발하고 관리하는 속도와 효율성을 높이기 위한 관행을 설정하기 위해 현대적인 경향에서 성장한 소프트웨어 개발 스타일을 나타냅니다. 마이크로서비스는 특정 수의 원칙과 아키텍처 패턴을 아키텍처로 적용하는 것에 관한 것입니다. 각 마이크로 서비스는 독립적으로 작동하지만 다른 한편으로는 모두 서로 의존합니다. 프로젝트의 모든 마이크로서비스는 자체 속도로 프로덕션 환경에 배포되고 클라우드의 온프레미스에 독립적으로 나란히 배치됩니다.
이 기사에서는 마이크로서비스의 개념, 아키텍처, .NET 및 C#에서 마이크로서비스를 만드는 방법을 배웁니다. 또한 도커 컨테이너를 사용하여 .NET에서 마이크로서비스를 빌드, 배포 및 테스트하는 단계를 배우게 됩니다.
Microsoft Docs의 다음 그림은 마이크로서비스 아키텍처 스타일을 보여줍니다.
마이크로 서비스 자체 외에도 마이크로 서비스 아키텍처에는 다양한 구성 요소가 있습니다.
관리 . 서비스에 대한 노드를 유지 관리합니다.
ID 제공자 . 분산 네트워크 내에서 신원 정보를 관리하고 인증 서비스를 제공합니다.
서비스 검색 . 서비스, 서비스 주소 및 끝점을 추적합니다.
API 게이트웨이 . 클라이언트의 진입점 역할을 합니다. 클라이언트의 단일 접점은 기본 마이크로 서비스의 응답과 때로는 여러 기본 마이크로 서비스의 집계 응답을 반환합니다.
CDN . 분산 네트워크에서 페이지 및 웹 콘텐츠와 같은 정적 리소스를 제공하는 콘텐츠 전달 네트워크
정적 콘텐츠 페이지 및 웹 콘텐츠와 같은 정적 리소스
마이크로 서비스는 서비스별로 자체 데이터베이스와 함께 독립적으로 배포되므로 기본 마이크로 서비스는 다음 그림과 같이 표시됩니다.
모놀리식 애플리케이션은 관련된 모든 필수 구성 요소와 서비스가 하나의 패키지에 캡슐화된 하나의 완전한 패키지에 가깝습니다.
다음은 완전히 패키지되거나 서비스 기반인 모놀리식 아키텍처의 다이어그램 표현입니다.
마이크로서비스는 각각의 공간에서 실행되고 메시징을 통해 통신할 수 있는 작은 서비스를 만드는 접근 방식입니다. 이들은 자체 데이터베이스를 직접 호출하는 독립 서비스입니다.
다음은 마이크로서비스 아키텍처를 도식적으로 나타낸 것입니다.
모놀리식 아키텍처에서 데이터베이스는 서비스 지향 아키텍처의 접근 방식을 따르더라도 모든 기능에 대해 동일하게 유지되는 반면 마이크로 서비스에서는 각 서비스에 자체 데이터베이스가 있습니다.
Docker 및 기타 컨테이너는 네트워크 스택, 프로세스 네임스페이스, 파일 시스템 계층 및 스토리지 스택과 같은 운영 체제 리소스를 분할합니다. Docker는 운영 체제를 가상화하는 것과 비슷합니다. 여기에서 도커에 대해 자세히 알아보세요 . 이 URL을 열고 Docker 허브에서 다운로드를 클릭합니다. 다운로드가 완료되면 Docker에 로그인하고 지침에 따라 Windows용 Docker를 설치합니다.
이 섹션에서는 그림을 참조하여 ASP.NET Core를 사용하여 제품 마이크로서비스를 단계별로 만드는 방법을 보여줍니다. 서비스는 ASP.NET Core 2.1 및 Visual Studio 2017을 사용하여 빌드됩니다. Asp.NET Core는 VS 2017과 통합됩니다. 이 서비스에는 자체 DBcontext 및 격리된 리포지토리가 있는 데이터베이스가 있으므로 서비스를 독립적으로 배포할 수 있습니다.
.NET Core API 프로젝트에는 EF Core에 대한 내장 지원이 있지만 아래와 같이 프로젝트의 SDK 섹션에서 찾을 수 있는 프로젝트 생성 및 컴파일 시 모든 관련 종속성이 다운로드됩니다.
Microsoft.EntityFrameworkCore.SqlServer(2.1.1)는 다운로드한 SDK 내의 패키지여야 합니다. 없는 경우 Nuget 패키지를 통해 프로젝트에 명시적으로 추가할 수 있습니다.
모델이 데이터베이스와 상호 작용할 수 있도록 데이터베이스 컨텍스트가 필요합니다.
using Microsoft.EntityFrameworkCore;
using ProductMicroservice.Models;
namespace ProductMicroservice.DBContexts
{
public class ProductContext : DbContext
{
public ProductContext(DbContextOptions<ProductContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>().HasData(
new Category
{
Id = 1,
Name = "Electronics",
Description = "Electronic Items",
},
new Category
{
Id = 2,
Name = "Clothes",
Description = "Dresses",
},
new Category
{
Id = 3,
Name = "Grocery",
Description = "Grocery Items",
}
);
}
}
}
Startup.cs 파일을 열어 EF Core용 SQL Server db 공급자를 추가합니다. 코드 추가 services.AddDbContext<ProductContext>(o => o.UseSqlServer(Configuration.GetConnectionString("ProductDB"))); ConfigureServices 메서드에서. GetConnectionString 메서드에서는 appsettings 파일에 추가된 연결 문자열의 키 이름이 전달됩니다.
리포지토리는 데이터 액세스 계층을 캡슐화하고 데이터 지속성 및 테스트 가능성에도 도움이 되는 마이크로 서비스의 마이크로 구성 요소로 작동합니다.
using Microsoft.EntityFrameworkCore;
using ProductMicroservice.DBContexts;
using ProductMicroservice.Models;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ProductMicroservice.Repository
{
public class ProductRepository: IProductRepository
{
private readonly ProductContext _dbContext;
public ProductRepository(ProductContext dbContext)
{
_dbContext = dbContext;
}
public void DeleteProduct(int productId)
{
var product = _dbContext.Products.Find(productId);
_dbContext.Products.Remove(product);
Save();
}
public Product GetProductByID(int productId)
{
return _dbContext.Products.Find(productId);
}
public IEnumerable<Product> GetProducts()
{
return _dbContext.Products.ToList();
}
public void InsertProduct(Product product)
{
_dbContext.Add(product);
Save(); }
public void Save()
{
_dbContext.SaveChanges();
}
public void UpdateProduct(Product product)
{
_dbContext.Entry(product).State = EntityState.Modified;
Save();
}
}
}
마이크로 서비스에는 HTTP 메서드를 서비스 메서드의 끝점으로 클라이언트에 노출하는 컨트롤러가 필요한 끝점이 있어야 합니다.
using Microsoft.AspNetCore.Mvc;
using ProductMicroservice.Models;
using ProductMicroservice.Repository;
using System;
using System.Collections.Generic;
using System.Transactions;
namespace ProductMicroservice.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
[HttpGet]
public IActionResult Get()
{
var products = _productRepository.GetProducts();
return new OkObjectResult(products);
}
[HttpGet("{id}", Name = "Get")]
public IActionResult Get(int id)
{
var product = _productRepository.GetProductByID(id);
return new OkObjectResult(product);
}
[HttpPost]
public IActionResult Post([FromBody] Product product)
{
using (var scope = new TransactionScope())
{
_productRepository.InsertProduct(product);
scope.Complete();
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
}
[HttpPut]
public IActionResult Put([FromBody] Product product)
{
if (product != null)
{
using (var scope = new TransactionScope())
{
_productRepository.UpdateProduct(product);
scope.Complete();
return new OkResult();
}
}
return new NoContentResult();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_productRepository.DeleteProduct(id);
return new OkResult();
}
}
}
마이그레이션을 통해 데이터베이스를 한 버전에서 다른 버전으로 변경하는 코드를 제공할 수 있습니다.
서비스는 IIS Express(예: Visual Studio 기본) 또는 Docker 컨테이너를 통해 실행할 수도 있습니다.
아래와 같이 Visual Studio에서 IIS Express를 선택하고 F5 키를 누르거나 해당 IIS Express 버튼 자체를 클릭합니다.
브라우저 페이지가 실행되면 응용 프로그램이 실행됩니다. 표시할 항목이 없으므로 비어 있지만 API 테스트 클라이언트를 통해 서비스를 테스트할 수 있습니다. 여기서 Postman은 서비스 엔드포인트를 테스트하는 데 사용됩니다. 열린 상태로 유지하고 응용 프로그램을 실행하십시오.
Postman이 컴퓨터에 없으면 설치하고 실행하십시오.
게시하다
POST 방법을 테스트하려면; 즉, 새 리소스를 만들고 postman에서 메서드를 POST로 선택하고 끝점(예: https://localhost:44312/api/product)을 제공하고 Body 섹션에서 아래와 같이 Product 모델의 속성을 갖는 것과 유사한 JSON을 추가하고 보내기를 클릭합니다.
응답은 제품의 ID와 함께 반환됩니다.
컨트롤러의 "Post" 메소드는 데이터베이스에 리소스를 생성하고 응답을 보내는 역할을 합니다.
라인 return CreatedAtAction(nameof(Get), new { id=product.Id }, product); 헤더 탭 아래 응답의 Location 속성에서 확인할 수 있는 생성된 리소스의 위치를 반환합니다.
제품 테이블에 대해 선택 쿼리를 수행하면 새로 생성된 제품에 대해 추가된 행이 표시됩니다.
비슷한 방법으로 제품을 하나 더 만듭니다.
가져 오기
지금 동일한 주소로 GET 요청을 수행하면 두 개의 레코드가 JSON 결과 응답으로 표시됩니다.
삭제
DELETE를 동사로 선택하고 id를 1로 추가하여 삭제 요청을 수행하고(id가 1인 제품을 삭제해야 하는 경우) 보내기를 누릅니다.
데이터베이스에서 ID가 1인 레코드 하나가 삭제됩니다.
놓다
PUT 동사는 리소스 업데이트를 담당합니다. PUT 동사를 선택하고 API 주소를 제공하고 본문 섹션에 JSON 형식으로 업데이트해야 하는 제품에 대한 세부 정보를 제공합니다. 예를 들어 ID 2로 제품을 업데이트하고 이름, 설명 및 가격을 Samsung에서 iPhone 전용으로 업데이트합니다. 보내기를 누릅니다.
업데이트된 제품을 보려면 데이터베이스를 확인하십시오.
서비스 실행은 docker 명령 프롬프트에서 실행할 docker 명령과 Visual Studio를 사용하여 수행할 수도 있습니다. 도커 지원을 추가했기 때문에 Visual Studio를 사용하여 도커 컨테이너에서 서비스를 쉽게 실행할 수 있습니다.
이는 마이크로 서비스가 두 개의 엔드포인트와 로컬로 배포된 두 개의 운영 체제에서 실행되고 있음을 증명합니다.
마이크로서비스는 특정 비즈니스 기능을 중심으로 구축된 서비스로, 독립적으로 배포할 수 있으며 이를 경계 컨텍스트라고 합니다. 마이크로 서비스에 대한 이 문서는 마이크로서비스가 무엇이며 모놀리식 서비스 아키텍처에 비해 이점에 초점을 맞췄습니다. 이 문서에서는 ASP.NET Core를 사용하여 마이크로서비스를 개발하고 IIS 및 Docker 컨테이너를 통해 실행하는 방법에 대해 자세히 설명합니다. 마찬가지로 서비스는 여러 이미지를 가질 수 있으며 동일한 시점에 여러 컨테이너에서 실행할 수 있습니다.
https://www.c-sharpcorner.com 의 원본 기사 출처
#microservice #aspdotnet #dotnet #csharp #docker