본문 바로가기
코딩, 개발 꾸준히 하면 볕날선생만큼 한다.

어디선가 공유받은 키

by 볕날선생 2020. 7. 2.
728x90
반응형

#!/usr/bin/env python

# -*- coding: utf-8 -*-

 

 

DEFAULT_SLEEP_TIME = 3 * 60 * 60

 

COUPANG_API_ACCESS_KEY = ''

COUPANG_API_SECRET_KEY = ''

 

TWITTER_API_CONSUMER_ACCESS_KEY = ''

TWITTER_API_CONSUMER_SECRET_KEY = ''

 

TWITTER_API_ACCESS_TOKEN = ''

TWITTER_API_ACCESS_TOKEN_SECRET = ''

 

COUPANG_CATEGORY_ID_LIST = {

    '여성패션' : 1001,

    '남성패션' : 1002,

'베이비패션' : 1003,

'여아패션' : 1004,

'남아패션' : 1005,

'스포츠패션': 1006,

'신발' : 1007,

    '가방/잡화' : 1008,

'뷰티' : 1010,

'출산/유아동' : 1011,

'식품': 1012,

'주방용품': 1013,

'생활용품' : 1014,

'홈인테리어' : 1015,

'가전디지털' : 1016,

'스포츠/레저' : 1017,

'자동차용품' : 1018,

'도서/음반/DVD' : 1019,

'완구/취미' : 1020,

'문구/오피스' : 1021,

'헬스/건강식품' : 1024,

'국내여행' : 1025,

'해외여행' : 1026,

'반려동물용품' : 1029,

}

COUPANG_TARGET_CATEGORY_ID = COUPANG_CATEGORY_ID_LIST['생활용품']

COUPANG_PER_ITEM_LIMIT = 100

 

 

import hmac

import hashlib

import binascii

import os

import time

import requests

import json

import random

from time import gmtime, strftime, sleep

import tweepy

from datetime import datetime

 

def main():

    REQUEST_METHOD = "GET"

    DOMAIN = "https://api-gateway.coupang.com"

 

 

    URL = '/v2/providers/affiliate_open_api/apis/openapi/products/bestcategories/'+ str(COUPANG_TARGET_CATEGORY_ID) + \

          '?limit=' + str(COUPANG_PER_ITEM_LIMIT)

 

    # Replace with your own ACCESS_KEY and SECRET_KEY

    ACCESS_KEY = COUPANG_API_ACCESS_KEY

    SECRET_KEY = COUPANG_API_SECRET_KEY

 

 

    def generateHmac(method, url, secretKey, accessKey):

        path, *query = url.split("?")

        os.environ["TZ"] = "GMT+0"

 

        dateGMT = strftime('%y%m%d', gmtime())

        timeGMT = strftime('%H%M%S', gmtime())

        datetime = dateGMT + 'T' + timeGMT + 'Z'

 

        message = datetime + method + path + (query[0] if query else "")

 

        signature = hmac.new(bytes(secretKey, "utf-8"),

                             message.encode("utf-8"),

                             hashlib.sha256).hexdigest()

 

        return "CEA algorithm=HmacSHA256, access-key={}, signed-date={}, signature={}"\

            .format(accessKey, datetime, signature)

 

 

    authorization = generateHmac(REQUEST_METHOD, URL, SECRET_KEY, ACCESS_KEY)

    url = "{}{}".format(DOMAIN, URL)

    resposne = requests.request(method=REQUEST_METHOD, url=url,

                                headers={

                                    "Authorization": authorization,

                                    "Content-Type": "application/json"

                                },

                                )

 

    result = resposne.json()['data']

 

    random_choice_int = random.randint(1, len(result))

 

    random_choice_item = result[random_choice_int]

 

 

    auth = tweepy.OAuthHandler(TWITTER_API_CONSUMER_ACCESS_KEY, TWITTER_API_CONSUMER_SECRET_KEY)

    auth.set_access_token(TWITTER_API_ACCESS_TOKEN, TWITTER_API_ACCESS_TOKEN_SECRET)

 

    api = tweepy.API(auth)

 

    def tweet_image(url, message):

        filename = 'temp.jpg'

        request = requests.get(url, stream=True)

        if request.status_code == 200:

            with open(filename, 'wb') as image:

                for chunk in request:

                    image.write(chunk)

 

            api.update_with_media(filename, status=message)

            os.remove(filename)

        else:

            print("Unable to download image")

 

    tweet_image(url=random_choice_item['productImage'],

                message=random_choice_item['productName'] + " " + random_choice_item['productUrl'])

 

    print(datetime.now())

    print(random_choice_item['productId'])

    print(random_choice_item['productName'])

    print(random_choice_item['productImage'])

    print(random_choice_item['productUrl'])

    print("\n")

 

 

if __name__ == '__main__':

    while True:

        main()

        sleep(DEFAULT_SLEEP_TIME)

728x90
반응형