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/cn.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灯, 水草

请输入看板名称,例如:Tech_Job站内搜寻

TOP