반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 네이버커머스API
- pywinauto 윈도우
- 파이썬 가상환경 설치
- 날짜 정규식
- 왕초보 파이썬 실행
- pywinauto 윈도우제어
- Element is not clickable at point
- Uipath 기초
- uipath 입문
- 네이버 로그인 영수증 해결
- vscode venv 설치
- 파이썬 환경설정
- 파이썬네이버부동산
- Uipath 설치방법
- UiPath
- 커머스API
- 네이버매물크롤링
- 가상환경설치
- venv 설치
- pywinauto
- Selenium 셀렉터잡기
- pycdas.exe
- 네이버 로그인 캡챠해결
- selenium
- 파이썬 가상환경 설치방법
- 파이썬 네이버 로그인
- pycdc.exe
- 네이버부동산크롤링
- Python
- 네이버 로그인 하기
Archives
- Today
- Total
콘솔워크
네이버 커머스 API 이미지 다건 등록 본문
반응형
#!/usr/bin/env python
from http import HTTPStatus
import bcrypt
import pybase64
import requests
import json
import time
import os
from mimetypes import MimeTypes
# from common.utils import get_mime_type
def get_mime_type(file_path):
mime = MimeTypes()
mime_type, encoding = mime.guess_type(file_path)
return mime_type
class CommerceAPI:
def __init__(self, client_id, client_secret):
self.main_url = f"https://api.commerce.naver.com"
self.client_id = client_id
self.client_secret = client_secret
self.initData()
def initData(self):
self.set_client_secret_sign()
self.set_token()
# 전자서명 (self.timestamp, self.client_secret_sign)
def set_client_secret_sign(self):
self.timestamp = round(time.time() * 1000)
# 밑줄로 연결하여 password 생성
password = self.client_id + "_" + str(self.timestamp)
# bcrypt 해싱
hashed = bcrypt.hashpw(password.encode("utf-8"), self.client_secret.encode("utf-8"))
# base64 인코딩 -> param으로 사용될 것
self.client_secret_sign = pybase64.standard_b64encode(hashed).decode("utf-8")
# 토큰 (self.token)
def set_token(self):
auth_url = "https://api.commerce.naver.com/external/v1/oauth2/token"
params = {
"client_id": self.client_id, # 제공된 클라이언트 ID
"timestamp": self.timestamp, # 전자서명 생성 시 사용된 밀리초(millisecond) 단위의 Unix 시간. 5분간 유효
"client_secret_sign": self.client_secret_sign, # 전자서명
"grant_type": "client_credentials", # OAuth2 인증 방식 -> client_credentials 고정
"type": "SELF",
"account_id": "", # type이 SELLER인 경우 입력해야 하는 판매자 ID
}
print(params)
res = requests.post(auth_url, params=params)
print(res.text)
if res.status_code == HTTPStatus.OK:
print("토큰가져오기 성공")
data = json.loads(str(res.text))
self.token = data["access_token"]
else:
print("토큰 가져오기 실패")
def get_headers(self):
return {"Authorization": f"Bearer {self.token}"}
def multi_image_upload(self, img_list: list):
print("multi_image_upload")
if len(img_list) > 10:
print("이미지수", len(img_list))
print("이미지는 최대 10개까지만 등록가능합니다.")
return
api_url = f"https://api.commerce.naver.com/external/v1/product-images/upload"
files = {}
for i in range(len(img_list)):
img_path = img_list[i]
img_name = os.path.basename(img_path)
img_type = get_mime_type(img_path)
img_binary = open(img_path, "rb").read()
files.update({f"imageFiles[{i}]": (f"{img_name}", img_binary, img_type)})
headers = self.get_headers()
upload_result = requests.post(api_url, headers=headers, files=files)
print(upload_result.text)
if __name__ == "__main__":
CLIENT_ID = "" # 발급받은 CLIENT_ID
CLIENT_SECRET = "" # 발급받은 CLIENT_SECRET
cmBot = CommerceAPI(CLIENT_ID, CLIENT_SECRET)
# 이미지 경로
img_list = [
r"C:\Users\bk\Downloads\img\11357-1.jpg",
r"C:\Users\bk\Downloads\img\11357-2.jpg",
]
cmBot.multi_image_upload(img_list)
python3용 이미지 다건등록 테스트 예제입니다.
문의 있으시면 댓글로 남겨주세요!
키 발급은 아래 문서 참조
[커머스API]
반응형
'프로그래밍 > python' 카테고리의 다른 글
파이썬 문자열 안의 모든 html 태그 기본 태그로 치환 (0) | 2022.12.11 |
---|---|
파이썬 html str에 원하는 태그 삭제 (ex img 태그 제거) (0) | 2022.12.10 |
네이버 커머스 API 사용해보기 (0) | 2022.12.07 |
if문 한줄로 표현하기 (0) | 2022.12.07 |
파이썬 우커머스 REST API 사용 (0) | 2022.12.06 |