class PinUploader:
    def __init__(self, cfg, logger):
        self.__cfg = cfg
        self.__pinterest = None
        self.__logger = logger
        self.__boards = None
        self.__create_obj()

    def __create_obj(self):
        self.__pinterest = Pinterest(email=self.__cfg['email'],
                                     password=self.__cfg['password'],
                                     username=self.__cfg['username'],
                                     cred_root=self.__cfg['cred_root'],
                                     user_agent=self.__cfg['user_agent'])
        self.__pinterest.login()
        self.__logger.info(f"{self.__cfg['username']} login")
        self.__boards = self.__pinterest.boards()

    def logout(self):
        self.__pinterest.logout()
        self.__logger.info(f"{self.__cfg['username']} logout")

    def __find_board_id(self, boardname):
        for board in self.__boards:
            if boardname == board['name']:
                return board['id']

    def get_board_id(self, boardname):
        response = None
        board_id = self.__find_board_id(boardname)
        if board_id:
            return board_id
        response = self.__pinterest.create_board(name=boardname)
        if response is not None:
            board_id = response.json()['resource_response']['data']['id']
            self.__logger.info("board {boardname} created")
            self.__boards.append({'name': boardname, 'id': board_id})
            return board_id
        else:
            self.__logger.error("can't create board '{boardname}'")
            return None

    def create_pin(self, board_id, title, price, image_path, printbar_url):
        description = '''Принт выдерживает неограниченное количество стирок.
                         Выберите тип ткани и вид печати.
                         Продукция будет готова через 48 часов.'''
        hashtag = title.replace(' ', ' #')
        try:
            self.__pinterest.upload_pin(
                board_id=board_id,
                image_file=image_path,
                description=f"Цена: {price}. {description} {hashtag}",
                link=printbar_url,
                title=title)
        except requests.exceptions.HTTPError:
            self.__logger.error("can't create '{title}' pin")
            raise
        else:
            self.__logger.info("'{title}' pin created ")
示例#2
0
def getPinterestUserPinnedSubmissions(email, username, password,
                                      cacheFileName):

    submissions = []

    lastIds = {} if not cacheFileName else loadPinterestCache(cacheFileName)
    updatedLastIds = lastIds

    pinterest = Pinterest(email=email,
                          password=password,
                          username=username,
                          cred_root='pinterest_creds')

    logger.log("Logging in to Pinterest...")
    pinterest.login()

    boards = pinterest.boards(username=username)

    for board in boards:
        # Get all pins for the board
        board_pins = []
        pin_batch = pinterest.board_feed(board_id=board['id'])

        while len(pin_batch) > 0:
            for pin in pin_batch:
                if pin['id'] not in lastIds:
                    # Only using the dict for its key lookup
                    updatedLastIds[pin['id']] = 1
                    board_pins.append(pin)

            pin_batch = pinterest.board_feed(board_id=board['id'])

        for pin in board_pins:

            # I'm not sure how important it is to support these
            if pin['type'] == 'story':
                continue

            newSubmission = Submission()
            newSubmission.source = u'Pinterest'
            # While pins do have titles, 90% of the time they seem useless
            newSubmission.title = pin['id']
            # There is probably a way to figure out who the original pinner is, but oh well
            newSubmission.author = 'N/A'
            newSubmission.subreddit = board['url']
            newSubmission.subredditTitle = board['name'] + '_Pinterest'
            if 'rich_summary' in pin and pin['rich_summary']:
                if 'display_description' in pin['rich_summary']:
                    newSubmission.body = pin['rich_summary'][
                        'display_description']
                else:
                    newSubmission.body = 'N/A'
                newSubmission.postUrl = pin['rich_summary']['url']

            # What is actually downloaded
            newSubmission.bodyUrl = pin['images']['orig']['url']
            submissions.append(newSubmission)

    if cacheFileName:
        savePinterestCache(cacheFileName, updatedLastIds)

    logger.log("Found {} new Pinterest submissions".format(len(submissions)))
    return submissions
username = '******'
password = '******'
email = 'login email'
cred_root = 'some dir'
download_dir = 'dir where images will be downloaded'

pinterest = Pinterest(email=email,
                      password=password,
                      username=username,
                      cred_root=cred_root)

# login if needed
# pinterest.login()

# your boards, pick one
boards = pinterest.boards()

# for example the first one
target_board = boards[0]

# get all pins for the board
board_pins = []
pin_batch = pinterest.board_feed(board_id=target_board['id'],
                                 board_url=target_board['url'])

while len(pin_batch) > 0:
    board_pins += pin_batch
    pin_batch = pinterest.board_feed(board_id=target_board['id'],
                                     board_url=target_board['url'])

示例#4
0
# Due to recent changes in pinterest api we can't directly search for users.
# instead we search for something else and extract pinners, owners and the relevant data
search_batch = pinterest.search(scope='pins',
                                query=query,
                                page_size=batch_size)
while len(search_batch) > 0 and len(results) < max_results:
    results += search_batch
    pinterest.search(scope='pins', query=query, page_size=batch_size)

target_users = []
for s in results:
    target_users.append(s['owner'])

# at this point target_users contains list of the user we want to invite.

boards = []
board_batch = pinterest.boards()
while len(board_batch) > 0:
    boards += board_batch
    board_batch = pinterest.boards()

board = boards[0]
# we chose the first board but you can chose any board you like

for user in target_users:
    pinterest.invite(board_id=board['id'],
                     board_url=board['url'],
                     user_id=user['id'])
    # Instead of break you need to implement some kind of pause mechanism in order not to get blocked by pinterest
    break