TIL2023.03.23 확장 Python 구문

요청

Python에서 HTTP 통신을 가능하게 하는 모듈,
Beautifulsoup으로 웹 크롤링을 하거나 API 통신이 필요할 때 사용
요청 엔진을 사용하면 웹 브라우저 없이 데이터를 코드로 가져올 수 있습니다.
요청 요청에는 네 가지 유형의 메서드가 있습니다.

– GET : 데이터 정보 조회
– POST: 데이터 생성 요청
– PUT: 데이터 변경 요청
– DELETE: 데이터 삭제 요청

get 요청 테스트코드
import requests
from pprint import pprint

# 통신 할 base url 지정
url = "https://jsonplaceholder.typicode.com/"

# 1번 사용자 정보를 받아오기 위해 users/1 경로에 get 요청
r = requests.get(f"{url}users/1")

pprint({
    "contents": r.text,
    "status_code": r.status_code,
})

# result output
"""
{'contents': '{\n'
             '  "id": 1,\n'
             '  "name": "Leanne Graham",\n'
             '  "username": "Bret",\n'
             '  "email": "[email protected]",\n'
             '  "address": {\n'
             '    "street": "Kulas Light",\n'
             '    "suite": "Apt. 556",\n'
             '    "city": "Gwenborough",\n'
             '    "zipcode": "92998-3874",\n'
             '    "geo": {\n'
             '      "lat": "-37.3159",\n'
             '      "lng": "81.1496"\n'
             '    }\n'
             '  },\n'
             '  "phone": "1-770-736-8031 x56442",\n'
             '  "website": "hildegard.org",\n'
             '  "company": {\n'
             '    "name": "Romaguera-Crona",\n'
             '    "catchPhrase": "Multi-layered client-server neural-net",\n'
             '    "bs": "harness real-time e-markets"\n'
             '  }\n'
             '}',
 'status_code': 200}
"""

post 요청 테스트코드

import requests
from pprint import pprint

# 통신 할 base url 지정
url = "https://jsonplaceholder.typicode.com/"

# 데이터 생성에 사용될 값 지정
data = {
    "name": "sparta",
    "email": "[email protected]",
    "phone": "010-0000-0000",
}


# 사용자를 생성하기 위해 users 경로에 data를 담아 post 요청
r = requests.post(f"{url}users", data=data)

pprint({
    "contents": r.text,
    "status_code": r.status_code,
})

# result output
"""
{'contents': '{\n'
             '  "name": "sparta",\n'
             '  "email": "[email protected]",\n'
             '  "phone": "010-0000-0000",\n'
             '  "id": 11\n'
             '}',
 'status_code': 201}
"""

json

데이터를 저장하기 위한 Javascript Object Notation의 약자입니다.
주로 데이터 통신에 사용됩니다. json을 파일로 작업할 때 .json 확장자를 사용하세요!!

Python에서 json 형식 처리

# json 모듈을 사용하기 위해 import !
import json
import requests

# 해당 사이트는 요청에 대한 응답을 json 형태의 문자열로 내려주기!
url = "https://jsonplaceholder.typicode.com/"

r = requests.get(f"{url}users/1")
print(type(r.text))  # <class 'str'>

# 문자열 형태의 json을 dictionary 자료형으로 변경해준다
response_content = json.loads(r.text)
print(type(response_content))  # <class 'dict'>

# dictionary 자료형이기 때문에 key를 사용해 value를 확인가능
print(f"사용자 이름은 {response_content('name')} .")

# result output
"""
사용자 이름은 Leanne Graham 입니다.
"""

csv

쉼표로 구분된 값의 약자로 텍스트에 쉼표( , )를 삽입합니다.
필드를 구분하고 .csv 확장자를 사용하려면

csv 파일 읽기

# 파이썬에서 csv 파일을 다루기 위해 모듈 import
import csv

csv_path = "sample.csv"

# csv를 list 자료형으로 읽기
csv_file = open(csv_path, "r", encoding="utf-8")
csv_data = csv.reader(csv_file)
for i in csv_data:
    print(i)

# 작업이 끝난 csv 파일을 닫아준다.
csv_file.close()

# result output
"""
('email', 'birthyear', 'name', 'Location')
('[email protected]', '1996', 'Laura Grey', 'Manchester')
('[email protected]', '1989', 'Craig Johnson', 'London')
('[email protected]', '1997', 'Mary Jenkins', 'London')
('[email protected]', '1987', 'Jamie Smith', 'Manchester')
('[email protected]', '1998', 'John', 'Manchester')
"""

csv를 dict 자료형으로 읽기

csv_file = open(csv_path, "r", encoding="utf-8")
csv_data = csv.DictReader(csv_file)

for i in csv_data:
    print(i)

csv_file.close()

# result output
"""
{'email': '[email protected]', 'birthyear': '1996', 'name': 'Laura Grey', 'Location': 'Manchester'}
{'email': '[email protected]', 'birthyear': '1989', 'name': 'Craig Johnson', 'Location': 'London'}
{'email': '[email protected]', 'birthyear': '1997', 'name': 'Mary Jenkins', 'Location': 'London'}
{'email': '[email protected]', 'birthyear': '1987', 'name': 'Jamie Smith', 'Location': 'Manchester'}
{'email': '[email protected]', 'birthyear': '1998', 'name': 'John', 'Location': 'Manchester'}
"""

csv 파일 쓰기

# 파이썬에서 csv 파일을 다루기 위해 모듈 import
import csv

csv_path = "sample.csv"

# csv 파일을 쓸 때는 newline="" 옵션을 줘서 중간에 공백 라인이 생기는 것을 방지합니다.
csv_file = open(csv_path, "a", encoding="utf-8", newline="")
csv_writer = csv.writer(csv_file)

# csv에 데이터를 추가!
csv_writer.writerow(("[email protected]", '1989', "lee", "Seoul"))

csv_file.close()

csv_file = open(csv_path, "r", encoding="utf-8")
csv_data = csv.reader(csv_file)
for i in csv_data:
    print(i)

csv_file.close()

# result output
"""
...
('[email protected]', '1989', 'lee', 'Seoul') # 추가 된 행
"""

데코레이터

그대로 Python 함수의 장식 역할을 합니다.

# 데코레이터는 호출 할 함수를 인자로 받도록 선언
def decorator(func):
    # 호출 할 함수를 감싸는 wrapper 함수를 선언
    def wrapper():
        # func.__name__에는 데코레이터를 호출 한 함수의 이름이 들어간다.
        print(f"{func.__name__} 함수에서 데코레이터 호출")
        func()
        print(f"{func.__name__} 함수에서 데코레이터 끝")

    # wrapper 함수를 리턴
    return wrapper

선언되는 함수 위에 @decorator를 추가해 데코레이터 사용

@decorator
def decorator_func():
    print("decorator_func 함수 호출")

decorator_func()

# result output
"""
decorator_func 함수에서 데코레이터 호출
decorator_func 함수 호출
decorator_func 함수에서 데코레이터 끝
"""