2017-01-20 54 views
3

我是Python新手,根本没有编码背景。 我正在尝试使用我的Raspberry Pi向Google Analytics发送数据。问题是Google Analytics测量协议使用HTTP S - 我的代码不适用。urllib2打开HTTPS

所以我当前的代码看起来像这样

import urllib2 
import time 
import RPi.GPIO as io 
io.setmode(io.BCM) 


door_sensor = 18 
sensorTrigger = True 

io.setup(door_sensor, io.IN, pull_up_down=io.PUD_UP) 

# function for the door opening 
def door_open(): 
    print("Door Open") 
    urllib2.urlopen("https://www.google-analytics.com/collect?v=1&tid=UA- 3458xxxx-1&cid=555&t=event&ec=doors&ea=open&el=office").close 

# function for the door closing 
def door_close(): 
    print("Door Close") 

while True: 
    if io.input(door_sensor): # if door is opened 
     if (sensorTrigger): 
      door_open() # fire GA code 
      sensorTrigger = False # make sure it doesn't fire again 
    if not io.input(door_sensor): # if door is closed 
     if not (sensorTrigger): 
      door_close() # fire GA code 
      sensorTrigger = True # make sure it doesn't fire again 

而且我不断收到错误...

Traceback (most recent call last): 
File "/home/pi/Desktop/GADoorSensor.py", line 23, in <module> 
door_open() # fire GA code 
File "/home/pi/Desktop/GADoorSensor.py", line 14, in door_open 
urllib2.urlopen("https://www.google-analytics.com/collect?v=1&tid=UA-3458xxxx-1&cid=555&t=event&ec=doors&ea=open&el=office").close 
File "/usr/lib/python2.7/urllib2.py", line 154, in urlopen 
return opener.open(url, data, timeout) 
File "/usr/lib/python2.7/urllib2.py", line 431, in open 
response = self._open(req, data) 
File "/usr/lib/python2.7/urllib2.py", line 449, in _open 
'_open', req) 
File "/usr/lib/python2.7/urllib2.py", line 409, in _call_chain 
result = func(*args) 
File "/usr/lib/python2.7/urllib2.py", line 1240, in https_open 
context=self._context) 
File "/usr/lib/python2.7/urllib2.py", line 1197, in do_open 
raise URLError(err) 
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)> 

我跟着THIS指南是否有帮助。

我已经在网上阅读了很多关于如何解决这个问题的文章,但是因为我对所有这些都是陌生的,所以没有让人困惑。

如果有人能给我一只手,或者指导我如何工作的初学者指南,我将非常感激!

+0

您是否尝试将'https://'更改为'http://'。它应该绕过尝试使用urllib2创建加密(ssl)连接的障碍。 – Matt

回答

0

我已经与http.client更好的运气,正是如此...

import http.client 

myDestination = "https://www.google-analytics.com/collect?v=1&tid=UA- 3458xxxx-1&cid=555&t=event&ec=doors&ea=open&el=office" 

conn = http.client.HTTPSConnection(myDestination) 

然后用...

conn.request() 

conn.response() 

不要忘记...

conn.close()