Python을 사용하여 Google 워크시트에서 데이터 자동 추출

26215 단어 pythonsqlgooglecloud
사진은 Daniele Levis Pelusi 에서 촬영되었다.
저희 Unsplash 에서 Python으로 전자메일을 자동화하는 것에 관한 내용처럼 오늘 우리는 자동화하기 쉬운 흔한 임무를 토론하고 싶습니다.
Google Sheets에서 데이터를 내보내고 MySQL에 삽입하는 Python 스크립트를 작성하는 방법을 설명합니다.
이거 언제 써요?
구글 폼으로 어떤 폼을 만들 때 매일 저녁 자동으로 새 데이터를 불러오고 싶은 유용한 방법이 있다.이는 구글 폼에 연결된 구글 폼에 가장 효과적이다. 이론적으로 구글 폼의 패턴이 바뀌어서는 안 되기 때문이다.
이것은 중요한 관점이다.만약 당신이 그 중에서 데이터를 추출하고 싶은 구글 폼이 끊임없이 변화하고 있다면, 당신은 더욱 복잡한 시스템을 개발해야 한다.
recent article

데이터 패턴에 큰 변화가 없다면 자동화는 매우 쉽다.도서관에 감사드립니다.이 라이브러리는 다양한 Google API와의 상호작용을 매우 간단하게 합니다.
그럼 구글 시계 추출을 자동화합시다.

구글 폼에서 데이터 추출


우선 구글 폼에서 데이터를 직접 추출하는 함수를 구축할 것이다.
우선, 우리는 몇 가지 일을 해야 한다.
  • 서비스 계정 자격 증명을 설정해야 합니다.이를 위해서는 구글 프로젝트에 가야 한다.
  • 서비스 계정을 만들고 JSON 파일을 만들 수 있습니다.
  • Google Sheets API에 대한 액세스도 활성화해야 합니다.
  • 이것들이 있으면 이제 추출을 시작할 수 있습니다.
    이를 위해 우리는 [open_by_url](https://gspread.readthedocs.io/en/latest/user-guide.html)라는 함수를 사용할 것이다.그러면 다음 코드와 같이 정확한 스프레드시트에 액세스할 수 있습니다.
    import gspread
    import mysql.connector
    from oauth2client.service_account import ServiceAccountCredentials
    
    # This is the mysqlcredentials.py file containing your credentials.
    import mysqlcredentials as mc
    
    # The required variables for gspread:
    scope = ['https://spreadsheets.google.com/feeds', \
           'https://www.googleapis.com/auth/drive']
    
    # The credentials created for the service account in your Google project
    # is stored in a .json file after you click 'Create Key'
    # I renamed this file to sheetstodb.json.
    creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
    client = gspread.authorize(creds)
    
    def GetSpreadsheetData(sheetName, worksheetIndex):
       sheet = client.open_by_url(sheetName).get_worksheet(worksheetIndex)
       return sheet.get_all_values()[1:]
    
    우리의 GetSpreadsheetData 기능을 통해 우리는 구글 폼에서 데이터를 되돌려 받을 것이다.본질적으로 우리가 얻은 것은 하나의 수조이다.
    보아하니 이렇다.
    #Array of arrays
    x = [
    ["username1","2020-01-01","A","B","D","C"],
    ["username2","2020-01-01","A","B","D","C"],
    ["username3","2020-01-01","A","B","D","C"]]
    
    이것은 우리가 이 데이터 집합을 처리하고 MySQL에 삽입하고 있기 때문에 주의해야 한다.

    gspread 회사 ySQL 삽입 및 빈 값 유지


    이제 Google 워크시트에서 Python을 사용하여 데이터를 반환할 수 있는 함수가 생겼습니다. 이제 MySQL에 삽입할 수 있습니다.
    그 전에 Google 양식에서 '' 부터 None 까지의 모든 빈 값을 대체하는 함수를 만들었습니다.
    이것은 중요한 차이로 중대한 문제를 초래할 수 있다.우리는 상세하게 토론하지는 않겠지만, 길게 말하자면, Null 결코 '' 과 같지 않다.
    이 예에서 우리는 함수preserveNullValues를 만들었다.이것은 중첩 순환을 사용하여 모든 것을 찾습니다''.
    기술적으로도 이와 유사한 방식으로 코드를 작성할 수 있습니다.\
    [None(없음), v가 다른 v가 아닌 경우 d의 v를 나타냅니다.]
    그러나 우리는 이것이 항상 사람을 곤혹스럽게 하는 것을 발견하기 때문에 함수의 작용에 대해 명확한 이해를 확보하고자 한다.
    또한 MySQL을 삽입하는 함수WriteToMysqlTable를 만들었습니다.
    우선, 우리는 비밀번호, 호스트, 사용자 이름과 데이터베이스 이름을 포함하는 단독 파일을 가지고 있다.이것을 사용하면 연결을 만들 것입니다.
    이 연결은 insert 문을 실행하는 데 사용됩니다.
    이 경우 스크립트는 하드 인코딩된 SQL을 삽입합니다.그러나 변수로 전달하거나 동적으로 만들어야 할 설정을 사용해야 할 수도 있습니다.
    또한 주의해야 할 것은 우리가 insert 문장을 실행하면 실제 데이터가 삽입되었는지 확인하기 위해 MySQL 호출 cursor.commit() 을 사용해야 한다는 것이다.
    이로써 우리는 거의 완성되었다.지금 우리는 이 함수들을 모두 함께 두기만 하면 된다.
    
    # Replaces any empty cells with 'NULL'
    def preserveNULLValues(listName):
       print('Preserving NULL values...')
       for x in range(len(listName)):
           for y in range(len(listName[x])):
               if listName[x][y] == '':
                   listName[x][y] = None
       print('NULL values preserved.')
    
    def WriteToMySQLTable(sql_data, tableName):
       try:
    # Connection credentials for MySQL.
           connection = mysql.connector.connect(
           user = mc.user,
           password = mc.password,
           host = mc.host,
           database = mc.database
           )
    
           sql_insert_statement = """INSERT INTO {}(
               Username,
               Date_Taken,
               Time_Started,
               Time_Finished,
               Answer_Question_1,
               Answer_Question_2,
               Answer_Question_3,
               Answer_Question_4,
               Answer_Question_5,
               Answer_Question_6 )
               VALUES ( %s,%s,%s,%s,%s,%s,%s,%s,%s,%s )""".format(tableName)
    
           cursor = connection.cursor()
           for i in sql_data:
               print(i)
               #print(sql_insert_statement)
               cursor.execute(sql_insert_statement, i)
    # Now we execute the commit statement, and print to the console
    # that the table was updated successfully
           connection.commit()
           print("Table {} successfully updated.".format(tableName))
    # Errors are handled in the except block, and we will get
    # the information printed to the console if there is an error
       except mysql.connector.Error as error :
           print("Error: {}. Table {} not updated!".format(error, tableName))
           connection.rollback()
           print("Error: {}. Table {} not updated!".format(error, tableName))
    # We need to close the cursor and the connection,
    # and this needs to be done regardless of what happened above.
    

    파이썬 스크립트 통합


    자, 이제 우리는 이 함수들을 모두 가지고 있습니다. 우리는 모든 것을 함께 놓아야 합니다.
    아래의 코드를 보면 구글 폼의 URL을 제공하기 때문에 데이터를 추출하고 싶은 구글 폼에 동적으로 사용할 수 있습니다.
    
    import gspread
    import mysql.connector
    from oauth2client.service_account import ServiceAccountCredentials
    
    # This is the mysqlcredentials.py file containing your credentials.
    import mysqlcredentials as mc
    
    # The required variables for gspread:
    scope = ['https://spreadsheets.google.com/feeds', \
           'https://www.googleapis.com/auth/drive']
    
    # The credentials created for the service account in your Google project
    # is stored in a .json file after you click 'Create Key'
    # I renamed this file to sheetstodb.json.
    creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
    client = gspread.authorize(creds)
    
    # Now that that's done, pull data from the Google sheet.
    # 'sheetName' describes the Google sheet's name,
    # 'worksheetIndex' describes the index of the worksheet at the bottom.
    def GetSpreadsheetData(sheetName, worksheetIndex):
       sheet = client.open_by_url(sheetName).get_worksheet(worksheetIndex)
       return sheet.get_all_values()[1:]
    
    # Finally, write this data to MySQL:
    def WriteToMySQLTable(sql_data, tableName):
       try:
    # Connection credentials for MySQL.
           connection = mysql.connector.connect(
           user = mc.user,
           password = mc.password,
           host = mc.host,
           database = mc.database
           )
           sql_drop = " DROP TABLE IF EXISTS {} ".format(tableName)
                   sql_create_table = """CREATE TABLE {}(
               Username VARCHAR(255),
               Date_Taken VARCHAR(16),
               Time_Started VARCHAR(16),
               Time_Finished VARCHAR(16),
               Answer_Question_1 VARCHAR(100),
               Answer_Question_2 VARCHAR(100),
               Answer_Question_3 VARCHAR(100),
               Answer_Question_4 VARCHAR(100),
               Answer_Question_5 VARCHAR(100),
               Answer_Question_6 VARCHAR(10),
               PRIMARY KEY (Username)
               )""".format(tableName)
    
           sql_insert_statement = """INSERT INTO {}(
               Username,
               Date_Taken,
               Time_Started,
               Time_Finished,
               Answer_Question_1,
               Answer_Question_2,
               Answer_Question_3,
               Answer_Question_4,
               Answer_Question_5,
               Answer_Question_6 )
               VALUES ( %s,%s,%s,%s,%s,%s,%s,%s,%s,%s )""".format(tableName)
    # Here we create a cursor, which we will use to execute
    # the MySQL statements above. After each statement is executed,
    # a message will be printed to the console if the execution was successful.
           cursor = connection.cursor()
           cursor.execute(sql_drop)
           print('Table {} has been dropped'.format(tableName))
           cursor.execute(sql_create_table)
    
    
               print('Table {} has been created'.format(tableName))
    # We need to write each row of data to the table, so we use a for loop
    # that will insert each row of data one at a time
           print(sql_data)
           for i in sql_data:
               print(i)
               #print(sql_insert_statement)
               cursor.execute(sql_insert_statement, i)
    # Now we execute the commit statement, and print to the console
    # that the table was updated successfully
           connection.commit()
           print("Table {} successfully updated.".format(tableName))
    # Errors are handled in the except block, and we will get
    # the information printed to the console if there is an error
       except mysql.connector.Error as error :
           print("Error: {}. Table {} not updated!".format(error, tableName))
           connection.rollback()
           print("Error: {}. Table {} not updated!".format(error, tableName))
    # We need to close the cursor and the connection,
    # and this needs to be done regardless of what happened above.
    
    
    # Replaces any empty cells with 'NULL'
    def preserveNULLValues(listName):
       print('Preserving NULL values...')
       for x in range(len(listName)):
           for y in range(len(listName[x])):
               if listName[x][y] == '':
                   listName[x][y] = None
       print('NULL values preserved.')
    
    # Uses Google Drive's API.
    # If you get an error regarding this, go to the link and enable it.
    data = GetSpreadsheetData(mc.url, 0)
    
    # Write to the table in the database.
    preserveNULLValues(data)
    WriteToMySQLTable(data, 'MyData')
    
    데이터를 추출하면 preserveNullValues 를 실행하고 WriteToMysqlTable 를 실행할 수 있습니다.
    그렇습니다!
    실제로 대부분의 작업은 gspread 라이브러리로 이루어진다.일단 데이터가 추출되어 수조에 넣으면 데이터 주위에서 이동하기 쉽다.
    이것이 바로 파이썬의 위대함이다.네가 해야 할 많은 일들이 어느 도서관에 존재한다.

    구글 폼을 자동으로 추출할 때가 됐어요.


    우리는 이 스크립트가 당신 이 Python을 사용하고 자동화할 수 있는 다른 작업을 찾는 데 도움을 줄 수 있기를 바랍니다.
    위의 예에서, 우리는 수동으로 이 스크립트를 스케줄링한다.그러나 앞으로 이 작업을 더욱 효과적으로 자동화하기를 원한다면 .그리고 이 스크립트를 수동으로 실행하지 않고 매일 실행할 수 있습니다.
    어떤 사람들은개인적으로 말하자면, 우리는 이렇게 하는 것을 건의하지 않는다.자동화 작업을 관리하는 데 도움을 줄 수 있는 좋은 프레임워크가 많다.시스템을 구축하는 것보다 프로세스에 더 많은 시간을 들이는 것이 좋다.
    당신이 어떻게 자동화를 결정하든지 간에, 우리는 당신의 행운, 자동화 즐거움을 축원합니다.
    만약 네가 이 문장을 좋아한다면, 그 중의 일부 문장을 읽는 것도 고려할 수 있다.
    automate your Google Sheet extracts 
    you could use a framework like Airflow
    Advanced SQL For Data Analysts, Data Scientists And Engineers
    Airbnb's Airflow Vs. Spotify's Luigi
    How Algorithms Can Become Unethical and Biased
    Top 10 Business Intelligence (BI) Implementation Tips​

    좋은 웹페이지 즐겨찾기