Python 板


LINE

# -*- coding: utf-8 -*- import pickle import os import re import logging from datetime import datetime, timedelta from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request import requests import fnmatch from xml.dom.minidom import Document import xml.etree.ElementTree as ET # os.environ["PYTHONIOENCODING"] = "utf-8" # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/photoslibrary'] mytime = datetime.now() + timedelta(hours=8) # 上傳的時間設定 basepath = os.path.dirname(__file__) # 本檔的路徑 filelog = os.path.join(basepath, 'Upload.log') # 上傳的紀錄檔 mypath = r'\\xxxxxx' # 要上傳的路徑, 會以第一層的目錄當相簿 mycreds = None # 開啟紀錄 LogTemp.log def EnableLogging(): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)-1s %(levelname)-1s %(message)s', datefmt='%m-%d %H:%M', handlers=[logging.FileHandler(filelog), ]) def Get_Token(): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_console() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) return creds def Create_Album(album): creds = mycreds service = build('photoslibrary', 'v1', credentials=creds) response_create_album = service.albums().create(body={'album': {'title': album}}).execute() print(response_create_album) return response_create_album['id'] def UploadMedia(fullname, albumid, creds): # 'latin-1' file = fullname.encode('utf-8').decode('latin-1').split('/')[-1] desc = file # step 1 upload raw bytes to google server headers = { 'Content-Type': "application/octet-stream", 'X-Goog-Upload-File-Name': file, 'X-Goog-Upload-Content-Type': "mime-type", 'X-Goog-Upload-Protocol': "raw", 'Authorization': "Bearer " + creds.token, } data = open(fullname, 'rb').read() response = requests.post('https://photoslibrary.googleapis.com/v1/uploads', headers=headers, data=data) image_token = response.text # step 2 create media items service = build('photoslibrary', 'v1', credentials=creds) # response_create_album = service.albums().create(body={'album': {'title': '我的相簿'}}).execute() myalbumid = albumid # results = service.albums().list().execute() ''' items = results.get('albums', []) if not items: print('No albums found.') else: for item in items: print(item['title']) if item['title'] == album: myalbumid = item['id'] print(myalbumid) ''' body = { 'albumId': myalbumid, 'newMediaItems': {'description': desc, 'simpleMediaItem': { 'uploadToken': image_token, 'fileName': file } } } response = service.mediaItems().batchCreate(body=body).execute() print(response) mess = response['newMediaItemResults'][0]['status'] # Success or Failed print(mess) return mess['message'] def ReadXML(file, strfile='File'): tree = ET.parse(file) root = tree.getroot() nodelist = root.findall(strfile) if strfile=='File': albumid = root.findall('AlbumID')[0].text for node in nodelist: if node.find('Upload').text == 'false': path = node.find('Fullname').text if UploadMedia(path, albumid, mycreds)=='Success': node.find('Upload').text = 'true' tree.write(file, encoding="utf-8", xml_declaration=True) else: return False else: for node in nodelist: if node.find('Upload').text == 'false': path = node.find('Fullname').text xmlpath = path.split('\\')[-1] + '.xml' xmlpath = os.path.join(basepath, xmlpath) if not os.path.isfile(xmlpath): Albumname = path.split('\\')[-1] albumid = Create_Album(Albumname) list = GetFiles(path) xmlpath = WriteXML(path, list, 'File', albumid) if ReadXML(xmlpath): node.find('Upload').text = 'true' tree.write(file, encoding="utf-8", xml_declaration=True) return True def WriteXML(path, files, strfile='File', albumid=''): xml = path.split('\\')[-1] doc = Document() base = doc.createElement('UploadFileList') doc.appendChild(base) filepath = doc.createElement('FilePath') base.appendChild(filepath) textpath = doc.createTextNode(path) filepath.appendChild(textpath) if albumid != '': albumidpath = doc.createElement('AlbumID') base.appendChild(albumidpath) alidpath = doc.createTextNode(albumid) albumidpath.appendChild(alidpath) for fi in files: file = doc.createElement(strfile) fullname = doc.createElement('Fullname') upload = doc.createElement('Upload') textfullname = doc.createTextNode(fi) isupload = doc.createTextNode('false') fullname.appendChild(textfullname) upload.appendChild(isupload) base.appendChild(file) file.appendChild(fullname) file.appendChild(upload) fname = xml + '.xml' fname = os.path.join(basepath, fname) with open(fname, 'w', encoding='utf-8') as f: doc.writexml(f, indent='\t', newl='\n', addindent='\t', encoding='utf-8') f.close return fname def GetFiles(path): includes = ['*.jpg','*.mp4'] # jpg, mp4 includes = r'|'.join([fnmatch.translate(x) for x in includes]) list = [] for dirPath, dirNames, fileNames in os.walk(path): list = [os.path.join(dirPath, f) for f in fileNames if re.match(includes, f, re.I)] return list def main(): """Shows basic usage of the People API. Prints the name of the first 10 connections. """ EnableLogging() logging.info('----------------------------------Getting Started--------------------------------------------------') path = mypath xmlpath = path.split('\\')[-1] + '.xml' xmlpath = os.path.join(basepath, xmlpath) if not os.path.isfile(xmlpath): dirs = os.listdir(path) list = [os.path.join(path, dir) for dir in dirs] fdname = WriteXML(path, list, 'Folder') print(list) if ReadXML(xmlpath, 'Folder'): LineNotifyMessage('上傳到 Google photo成功') logging.info('----------------------------------All Uploaded--------------------------------------------------') def LineNotifyMessage(msg): token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' headers = { "Authorization": "Bearer " + token # "Content-Type": "application/x-www-form-urlencoded" } # file = {'imageFile': open(picURI, 'rb')} payload = {'message': msg} r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params = payload) return r.status_code if __name__ == '__main__': mycreds = Get_Token() # Get Google Token main() : → kenduest: Google photo api 文件有說上傳的圖片都是原始格式不會 05/18 01:57 : → kenduest: 壓縮處理,所以若是你要不占用空間得自己 resize 成為 05/18 01:57 : → kenduest: 1600萬畫素,一般用 Pillow 處理一下就可以。 05/18 01:57 只要是利用Google API 上傳的都會佔用空間, 不論你是多少解析度的 我已經試用好幾次 : 推 TakiDog: 有實作給個推,可以試著改用API吧 05/18 09:28 給你試試吧,試了好幾次 : → kenduest: 影片部分,只要你影片沒有超過 1080p 記得不壓縮的 05/19 00:11 : → kenduest: 所以你用 api or web 處理最後影片結果都是一樣 05/19 00:11 : → kenduest: 若你是拍 4k 可能就是不一樣情況 05/19 00:11 : 推 TWhtml: 推 05/19 00:31 : 推 unmolk: 推 其實可以推上github 不用這麼辛苦打程式碼在這XD 05/19 11:08 --



※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.230.44.145 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1598681103.A.C91.html







like.gif 您可能會有興趣的文章
icon.png[問題/行為] 貓晚上進房間會不會有憋尿問題
icon.pngRe: [閒聊] 選了錯誤的女孩成為魔法少女 XDDDDDDDDDD
icon.png[正妹] 瑞典 一張
icon.png[心得] EMS高領長版毛衣.墨小樓MC1002
icon.png[分享] 丹龍隔熱紙GE55+33+22
icon.png[問題] 清洗洗衣機
icon.png[尋物] 窗台下的空間
icon.png[閒聊] 双極の女神1 木魔爵
icon.png[售車] 新竹 1997 march 1297cc 白色 四門
icon.png[討論] 能從照片感受到攝影者心情嗎
icon.png[狂賀] 賀賀賀賀 賀!島村卯月!總選舉NO.1
icon.png[難過] 羨慕白皮膚的女生
icon.png閱讀文章
icon.png[黑特]
icon.png[問題] SBK S1安裝於安全帽位置
icon.png[分享] 舊woo100絕版開箱!!
icon.pngRe: [無言] 關於小包衛生紙
icon.png[開箱] E5-2683V3 RX480Strix 快睿C1 簡單測試
icon.png[心得] 蒼の海賊龍 地獄 執行者16PT
icon.png[售車] 1999年Virage iO 1.8EXi
icon.png[心得] 挑戰33 LV10 獅子座pt solo
icon.png[閒聊] 手把手教你不被桶之新手主購教學
icon.png[分享] Civic Type R 量產版官方照無預警流出
icon.png[售車] Golf 4 2.0 銀色 自排
icon.png[出售] Graco提籃汽座(有底座)2000元誠可議
icon.png[問題] 請問補牙材質掉了還能再補嗎?(台中半年內
icon.png[問題] 44th 單曲 生寫竟然都給重複的啊啊!
icon.png[心得] 華南紅卡/icash 核卡
icon.png[問題] 拔牙矯正這樣正常嗎
icon.png[贈送] 老莫高業 初業 102年版
icon.png[情報] 三大行動支付 本季掀戰火
icon.png[寶寶] 博客來Amos水蠟筆5/1特價五折
icon.pngRe: [心得] 新鮮人一些面試分享
icon.png[心得] 蒼の海賊龍 地獄 麒麟25PT
icon.pngRe: [閒聊] (君の名は。雷慎入) 君名二創漫畫翻譯
icon.pngRe: [閒聊] OGN中場影片:失蹤人口局 (英文字幕)
icon.png[問題] 台灣大哥大4G訊號差
icon.png[出售] [全國]全新千尋侘草LED燈, 水草

請輸入看板名稱,例如:Soft_Job站內搜尋

TOP