Crash, Python and Google Calendar API - python

Ahoy !
I followed the Documentation (https://developers.google.com/google-apps/calendar/quickstart/python ) for google calendar API and this tutorial (http://www.esologic.com/?p=634 ) to create an alarm clock. The principle is quite simple. I put an event in my calendar, and if it is on the calendar "Raspberry" and that the description is "wake" when the time = the time specified, it plays me my music on the Pi.
Except that when I run my script, it will work for a variable time, and then will crash with a random error.
Traceback (most recent call last):
File "alarmclock.py", line 65, in <module>
calendar_event_query()
File "alarmclock.py", line 37, in calendar_event_query
events = service.events().list(singleEvents=True, calendarId=CALENDAR_ID).execute()
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 722, in execute
body=self.body, headers=self.headers)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 596, in new_request
redirections, connection_type)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1272, in _conn_request
conn.connect()
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1036, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "/usr/lib/python2.7/ssl.py", line 891, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 566, in __init__
self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 788, in do_handshake
self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:581)
or
Traceback (most recent call last):
File "alarmclock.py", line 80, in <module>
calendar_event_query()
File "alarmclock.py", line 52, in calendar_event_query
events = service.events().list(singleEvents=True, calendarId=CALENDAR_ID).execute()
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 140, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 722, in execute
body=self.body, headers=self.headers)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 596, in new_request
redirections, connection_type)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/local/lib/python2.7/dist-packages/httplib2/__init__.py", line 1278, in _conn_request
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
httplib2.ServerNotFoundError: Unable to find the server at www.googleapis.com
So I do not understand if it is a problem with my script, or if it is directly GoogleAPI that misfire and then crash my script?
Here is my script.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import httplib2
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from datetime import datetime
import logging
import time
import random
import os
import argparse
try:
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
CALENDAR_ID = 'MY_CALENDAR_ID#group.calendar.google.com'
CLIENT_SECRET_FILE = 'raspi-wake.json'
SCOPE = 'https://www.googleapis.com/auth/calendar.readonly'
MP3_FOLDER = 'mp3'
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir, 'raspberry-wake.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=SCOPE)
flow.user_agent = 'Raspberry Wake'
if flags:
credentials = tools.run_flow(flow, store, flags)
else:
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def calendar_event_query():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
today = datetime.today()
events = service.events().list(singleEvents=True, calendarId=CALENDAR_ID).execute()
for i, event in enumerate(events['items']):
try:
start = event['start']['dateTime'][:-9]
except KeyError:
start = ''
description = event.get('description', '')
now = today.strftime('%Y-%m-%dT%H:%M')
if start >= now and description.lower() == 'wake':
if start == now:
mp3_files = random.choice(os.listdir(MP3_FOLDER))
command = 'mpg123 \'{}/{}\''.format(MP3_FOLDER, mp3_files)
os.system(command)
time.sleep(60)
while True:
calendar_event_query()
time.sleep(5)

Related

How do i attach PDF correctly with Gmail API?

Hello to everyone i hope yall good.
Im trying to create a draft with gmail api and attach some files.
I have no problems with the "JPG" files, but when i add some pdf files.
This error appears:
*client_secret.json-gmail-v1-(['https://mail.google.com/'],)
['https://mail.google.com/']
gmail service created successfully
Traceback (most recent call last):
File "F:\Python Proyectos\gmail\borrador.py", line 52, in
).execute()
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googleapiclient_helpers.py", line 131, in positional_wrapper
return wrapped(*args, *kwargs)
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googleapiclient\http.py", line 922, in execute
resp, content = _retry_request(
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googleapiclient\http.py", line 221, in _retry_request
raise exception
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\googleapiclient\http.py", line 190, in retry_request
resp, content = http.request(uri, method, *args, **kwargs)
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\google_auth_httplib2.py", line 218, in request
response, content = self.http.request(
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\httplib2_init.py", line 1701, in request
(response, content) = self.request(
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\httplib2_init.py", line 1421, in _request
(response, content) = self.conn_request(conn, request_uri, method, body, headers)
File "C:\Users\bRUNS\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\httplib2_init.py", line 1373, in _conn_request
response = conn.getresponse()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 1374, in getresponse
response.begin()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 318, in begin
version, status, reason = self._read_status()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 279, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\ssl.py", line 1273, in recv_into
return self.read(nbytes, buffer)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\ssl.py", line 1129, in read
return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out
This is my code:
from Google import Create_Service
import os
import base64
import mimetypes
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email import encoders
from sys import api_version
CLIENT_SECRET_FILE = 'client_secret.json'
API_NAME = 'gmail'
API_VERSION = 'v1'
SCOPES = ['https://mail.google.com/']
service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)
file_attachments = [r'.\Attachments\a.jpg', r'.\Attachments\b.jpg', r'.\Attachments\duoc.jpeg', r'.\Attachments\fachadatextil1.jpg', r'.\Attachments\fachadatextil2.jpg', r'.\Attachments\forum1.jpg', r'.\Attachments\forum2.jpg', r'.\Attachments\hdpedagoberto1.jpeg', r'.\Attachments\hdpedagoberto2.jpeg', r'.\Attachments\ingevec.jpeg', r'.\Attachments\pintana.jpg', r'.\Attachments\Santander.jpg', r'.\Attachments\terrazapvc.jpg', r'.\Attachments\BRO-Flexlight-Advanced-1002-S2-ES.pdf', r'.\Attachments\fichatecnicaforum.pdf', r'.\Attachments\MC_Brochure_2021.pdf', r'.\Attachments\Parasolbrochure(ingles).pdf']
mimeMessage = MIMEMultipart()
mimeMessage['from'] = 'from#mail.com' #validar dominio
mimeMessage['to'] = 'to#mail.com' #este deberia cambiar
mimeMessage['subject'] = 'Arquitectura Textil para habitar nuevos espacios'
msg_body = 'prueba' #va un txt con la plantilla
mimeMessage.attach(MIMEText(msg_body, 'plain'))
for attachment in file_attachments:
content_type, encoding = mimetypes.guess_type(attachment)
main_type, sub_type = content_type.split('/', 1)
file_name = os.path.basename(attachment)
f = open(attachment, 'rb')
myFile = MIMEBase(main_type, sub_type)
myFile.set_payload(f.read())
myFile.add_header('Content-Disposition', 'attachment', filename=file_name)
encoders.encode_base64(myFile)
f.close()
mimeMessage.attach(myFile)
raw_string = base64.urlsafe_b64encode(mimeMessage.as_bytes()).decode()
response = service.users().drafts().create(
userId='me',
body={'message' : {'raw':raw_string }}
).execute()
This error just occurs with the PDF files
New Edit: The Draft its created even with that error.

Exchangelib: Can't connect to server

so recently I tried myself with Exchangelib, but I currently can't solve the issue. Heres my code:
from exchangelib import DELEGATE, Account, Credentials, IMPERSONATION
from exchangelib.configuration import Configuration
config = Configuration(
server='https://XXX',
credentials=Credentials(username='XXX\\XXX', password='XXX')
)
account = Account(
primary_smtp_address='mail#mail.com',
config=config,
autodiscover=False,
access_type=DELEGATE,
)
for item in account.inbox.all().order_by('-datetime_received')[:20]:
print(item.subject, item.sender, item.datetime_received)
Currently I receive the following error:
File "Project/Exchange/standardoutlook2.py", line 23, in <module>
config = Configuration(server='https://XXX', credentials=credentials)
File "Projectvenv36\lib\site-packages\exchangelib\configuration.py", line 46, in __init__
version=version
File "Projectvenv36\lib\site-packages\exchangelib\protocol.py", line 176, in __call__
protocol = super(CachingProtocol, cls).__call__(*args, **kwargs)
File "Projectvenv36\lib\site-packages\exchangelib\protocol.py", line 209, in __init__
name=self.credentials.username)
File "Projectvenv36\lib\site-packages\exchangelib\transport.py", line 149, in get_service_authtype
timeout=BaseProtocol.TIMEOUT)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 559, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "Projectvenv36\lib\site-packages\requests\adapters.py", line 412, in send
self.cert_verify(conn, request.url, verify, cert)
File "Project/Exchange/standardoutlook2.py", line 13, in cert_verify
}[urlparse(url).hostname]
KeyError: 'https'
I've added the certificate to the certificate of certifi, so when I start any request to the server outside of the code above it works well.

Connecting to Google Content API via Python

I am kind of new in Google APIs and I am trying to connect to Google Content API via Python. I am using a service account for that.
My script is quite easy and straightforward:
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
credentials = ServiceAccountCredentials.from_p12_keyfile(
'xxxxx.iam.gserviceaccount.com',
'/Users/Downloads/pkey.txt',
scopes='https://www.googleapis.com/auth/content')
http = credentials.authorize(httplib2.Http())
service = build('https://www.googleapis.com/content', 'v2')
In the authorization process I get this error:
Traceback (most recent call last):
File "/Users/PycharmProjects/authorization.py", line 22, in <module>
service = build('https://www.googleapis.com/content', 'v2')
File "build/bdist.macosx-10.11-intel/egg/oauth2client/_helpers.py", line 133, in positional_wrapper
File "build/bdist.macosx-10.11-intel/egg/googleapiclient/discovery.py", line 228, in build
File "build/bdist.macosx-10.11-intel/egg/googleapiclient/discovery.py", line 275, in _retrieve_discovery_doc
File "/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg/httplib2/__init__.py", line 1659, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg/httplib2/__init__.py", line 1399, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg/httplib2/__init__.py", line 1319, in _conn_request
conn.connect()
File "/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg/httplib2/__init__.py", line 1069, in connect
self.ssl_version, self.host)
File "/Library/Python/2.7/site-packages/httplib2-0.10.3-py2.7.egg/httplib2/__init__.py", line 97, in _ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=hostname)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 352, in wrap_socket
_context=self)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 579, in __init__
self.do_handshake()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 816, in do_handshake
match_hostname(self.getpeercert(), self.server_hostname)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 271, in match_hostname
% (hostname, ', '.join(map(repr, dnsnames))))
ssl.CertificateError: hostname 'https%3a%2f%2fwww.googleapis.com%2fcontent.googleapis.com' doesn't match either of '*.googleapis.com', '*.clients6.google.com', '*.cloudendpointsapis.com', 'cloudendpointsapis.com', 'googleapis.com'
Process finished with exit code 1
Does it have to do with my authorisation? Or I am doing something wrong?
Thanks a lot for your help!
You want to provide build() with the api_name, not a URL.
service = build('content', 'v2')
Source: https://developers.google.com/api-client-library/python/apis/

Google API and cx_Freeze not working properly

I have made a Python program that is capable of uploading files into Google Drive. The .py file works perfectly and does not give any errors.
But as I'm going to distribute it for people who do not have Python installed, I must turn the program and the resources into a .exe. I have done this with cx_Freeze. I have used it before and it has always worked.
But now, the Google Drive API seems to be causing errors when the .exe is run. Here are the errors it gives:
Traceback (most recent call last):
File "C:\Python27\lib\runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "C:\Python27\lib\runpy.py", line 72, in _run_code
exec code in run_globals
File "Test.py", line 41, in <module>
File "C:\Python27\lib\oauth2client\util.py", line 128, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\oauth2client\client.py", line 1283, in step2_exchange
headers=headers)
File "C:\Python27\lib\site-packages\httplib2-0.8-py2.7.egg\httplib2\__init__.p
y", line 1570, in request
(response, content) = self._request(conn, authority, uri, request_uri, metho
d, body, headers, redirections, cachekey)
File "C:\Python27\lib\site-packages\httplib2-0.8-py2.7.egg\httplib2\__init__.p
y", line 1317, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, he
aders)
File "C:\Python27\lib\site-packages\httplib2-0.8-py2.7.egg\httplib2\__init__.p
y", line 1252, in _conn_request
conn.connect()
File "C:\Python27\lib\site-packages\httplib2-0.8-py2.7.egg\httplib2\__init__.p
y", line 1021, in connect
self.disable_ssl_certificate_validation, self.ca_certs)
File "C:\Python27\lib\site-packages\httplib2-0.8-py2.7.egg\httplib2\__init__.p
y", line 80, in _ssl_wrap_socket
cert_reqs=cert_reqs, ca_certs=ca_certs)
File "C:\Python27\lib\ssl.py", line 383, in wrap_socket
ciphers=ciphers)
File "C:\Python27\lib\ssl.py", line 141, in __init__
ciphers)
ssl.SSLError: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate rout
ines:X509_load_cert_crl_file:system lib
It gives this error after the user has typed in the authorization code.
After some debugging, I found out that the line causing this problem was
credentials = flow.step2_exchange(code)
Here is a snippet of the code:
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
webbrowser.open(authorize_url)
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
The CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE and REDIRECT_URI are all configured correctly.
So, what could be the problem here?
If you need to see more code, ask and I will update this question.
Looks like it can't find your SSL certificates. This is kind of understandable because httplib2 loads them from the file system, and nothing tells cx_Freeze to put them in the bundled package.
Read this, it will help: https://github.com/kennethreitz/requests/issues/557#issuecomment-6420819

SSL Error with Python Google Drive API

i wrote a simple code, basically the same as the one on https://developers.google.com/drive/quickstart-python and every time after the first attempt i've the same error :
# Traceback (most recent call last):
# File "C:/plug-ins/googleDrive.py", line 35, in <lambda>
# self.authAction = self.menu.addAction( 'Authentication', lambda: self.runAuthentication() )
# File "C:/plug-ins/googleDrive.py", line 46, in runAuthentication
# credentials = self.flow.step2_exchange( unicode(text) )
# File "D:/Python\oauth2client\util.py", line 120, in positional_wrapper
# return wrapped(*args, **kwargs)
# File "D:/Python\oauth2client\client.py", line 1131, in step2_exchange
# headers=headers)
# File "D:/Python\httplib2\__init__.py", line 1597, in request
# (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
# File "D:/Python\httplib2\__init__.py", line 1345, in _request
# (response, content) = self._conn_request(conn, request_uri, method, body, headers)
# File "D:/Python\httplib2\__init__.py", line 1281, in _conn_request
# conn.connect()
# File "D:/Python\httplib2\__init__.py", line 1013, in connect
# self.disable_ssl_certificate_validation, self.ca_certs)
# File "D:/Python\httplib2\__init__.py", line 80, in _ssl_wrap_socket
# cert_reqs=cert_reqs, ca_certs=ca_certs)
# File "C:\python26\ssl.py", line 350, in wrap_socket
# File "C:\python26\ssl.py", line 118, in __init__
# File "C:\python26\ssl.py", line 293, in do_handshake
# ssl.SSLError: [Errno 8] _ssl.c:480: EOF occurred in violation of protocol
I run this under Python 2.6.4, httplib2 v0.7.7 and google-api-python-client v1.0b9. If someone have an idea...I will be very grateful.
That version of the google-api-python-client (v1.0b9) is beta 9 of the client library, you should upgrade to the release version, which is simply v1.0.
As for the "EOF occurred in violation of protocol", I have only seen that occur on a flaky network connection, is that the case here?

Categories