update.py 2.26 KB
from crawler.crawler_instagram import crawler_instagram
import json
import cx_Oracle
import os
from config.key import DATABASE_ID, DATABASE_PW
from config.URLs import DATABASE_URL
from flask import Response


# data = {
#         "followers": [followers_list],
#         "insta_id": insta_id,
#         "description": desc,
#         "follower_num": len([followers_list])
#     }

def update(insta_id):
    data = {}

    try:
        data = crawler_instagram(insta_id)
    except Exception as e:
        print(e)

    connection = cx_Oracle.connect(DATABASE_ID, DATABASE_PW, DATABASE_URL)
    cursor = connection.cursor()

    user_query = """
        select * from users where user_id=\'%s\'
    """ % insta_id

    cursor.execute(user_query)  # user가 존재하는지 확인
    exist_user = cursor.fetchall()
    print(exist_user)

    ### update users table ###
    query = ""
    if len(exist_user) == 0:
        print('insert new')
        cursor.execute(f"""
            insert into 
            users (user_id, description, follower_num) 
            values (
                \'{data['user_id']}\', 
                \'{data['description'][0:254]}\', 
                \'{data['follower_num']}\'
            )
        """)
    else:
        print('update user')
        cursor.execute(f"""
            update users set 
            description = \'{data['description'][0:254]}\',
            follower_num = \'{data['follower_num']}\'
            where user_id = \'{data['user_id']}\'
        """)

    ### update followers table ###
    for follower in data['followers']:
        print(follower)
        cursor.execute("""
            select * from followers where follower_id=\'%s\'
        """ % follower)

        exist_follower = cursor.fetchall()

        if len(exist_follower) == 0:
            print('insert follower')
            cursor.execute(f"""
                insert into
                followers (follower_id, user_id, description)
                values (\'{follower}\', \'{data['user_id']}\', \'\')
            """)
    cursor.close()

    return Response(json.dumps(data), mimetype='application/json')


if __name__ == '__main__':
    os.putenv('NLS_LANG', '.UTF8')
    cx_Oracle.init_oracle_client(lib_dir="/Users/choewonseog/Downloads/instantclient_19_8")
    update('__re.mind.er__')