问题
我想将一个打印作业从python脚本发送到在“Google Cloud Print”中注册的打印机。
我认为我需要这个
google account
google cloud api registration:client-id,client-secret(获取访问令牌)
访问令牌
我使用本教程获得了访问令牌:
https://github.com/burnash/gspread/wiki/How-to-get-OAuth-access-token-in-console%3F
到目前为止我尝试了什么
由于布拉德利艾尔斯为此目的写了一个名为cloudprinting(https://github.com/bradleyayers/cloudprinting)的python库,以下脚本是为了处理我的打印工作:
from cloudprinting import *
access_token = 'xyz_token_xyz' # here my personal access token is stated
auth = OAuth2(access_token, token_type="Bearer")
r = submit_job(printer="e506d12-dbe0-54d3-7392-fd69d45ff2fc", content="some_pdf_in_local_directory.pdf", auth=auth)
尽管脚本没有错误消息但它不起作用 - 这意味着最后没有打印作业。
所以我尝试将自己尝试 http发布到Google云打印 :
import requests
import json
access_token = 'xyz_acces_token_xyz' # here my personal access token is stated
printer = "e506d12-dbe0-54d3-7392-fd69d45ff2fc" # random printer_id
capabilities = [{}]
data = {"printerid": printer,
"title": "name",
"contentType": "pdf",
"capabilities": json.dumps({"capabilities": capabilities})}
post_request = requests.post('https://www.google.com/cloudprint/submit', headers={'Authorization': access_token},data=data,files='some_pdf_in_local_directory.pdf')
print (post_request.text)
显然上面的requests.post()参数不正确。我需要以哪种方式说明哪些参数? 或者更具体地说:
任何想法都表示赞赏。提前谢谢!
答案 0 :(得分:4)
如果有人仍然对使用该教程获取访问令牌感兴趣,我也可以使用print(credentials.refresh_token)获取刷新令牌,我写了一个打印的类,并在需要时刷新令牌。 我可以在我的云打印机中成功地从python打印,你也必须将范围改为“https://www.googleapis.com/auth/cloudprint”
希望有所帮助
class CloudPrint():
def __init__(self,client_id=None, client_secret=None, access_token = None, refresh_token = None):
self.client_id = client_id
self.client_secret= client_secret
self.access_token = access_token
self.refresh_token = refresh_token
self.deadline = time.time()-1
self.api_url ='https://www.google.com/cloudprint/submit'
def safe_check(self):
if time.time()>float(self.deadline):
self.refresh()
def refresh(self):
print('google refreshing')
token = requests.post(
'https://accounts.google.com/o/oauth2/token',
data={
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token,
}
)
self.access_token = token.json()['access_token']
self.deadline = self.deadline + token.json()['expires_in']
print('new deadline ', self.deadline)
def print(self, file, title, printerids):
self.safe_check()
body = {"printerid":printerids,
"title":[title],
"ticket":"{\r\n \"version\": \"1.0\",\r\n \"print\": {}\r\n}",
}
files = {'content': open(file,'rb')}
headers = {"Authorization":"Bearer "+str(self.access_token)}
print(headers)
r = requests.post(self.api_url, data=body, files=files, headers=headers)
print(r.url)
print(r.text)
if __name__ == '__main__':
gcp = CloudPrint(CLIENT_ID, CLIENT_SECRET, refresh_token=REFRESH_TOKEN)
gcp.print('prueba.txt', 'prueba', PRINTER_ID_DEB)