AttributeError: модуль 'urllib3' не имеет атрибута 'urlopen' в Python - PullRequest
0 голосов
/ 13 января 2019

Я пытаюсь отправить данные о температуре на один из моих веб-сайтов. Этот код состоит из измерения температуры с помощью датчика (ds18b20), отправки этих данных в базу данных mysql с именем temp_pi и, в частности, в таблицу с именем TAB_CLASSROOM и, наконец, отправки этих данных на мою веб-страницу. Все в этом коде работает, кроме части sendDataToServer(). Я указываю ошибку прямо перед этой конкретной строкой. Я установил PHP на своем веб-сайте, чтобы это работало.

import os
import glob
import time
import MySQLdb
import datetime
import mysql.connector
from mysql.connector import Error

#define db and cur

db = MySQLdb.connect(host = "127.0.0.1", user = "root", passwd = "xB7O4fXmuMpF6M0u", db = "temp_pi")
cur = db.cursor()

#connection to the database
try:
    connection = mysql.connector.connect(host='127.0.0.1',
                             database='temp_pi',
                             user='root',
                             password='xB7O4fXmuMpF6M0u')

    if connection.is_connected():
       db_Info = connection.get_server_info()
       print("Connected to MySQL database... MySQL Server version on ",db_Info)
       cursor = connection.cursor()
       cursor.execute("select database();")
       record = cursor.fetchone()
       print ("Your connected to - ", record)

except Error as e :
    print ("Error while connecting to MySQL", e)

#obtaining the temperature through the ds18b20 sensor            
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c  
#Defining sendDataToServer() and trying to send this data towards my website
def sendDataToServer():
    global temperature

    threading.Timer(600,sendDataToServer).start()
    print("Mesuring...")
    read_temp()
    temperature = read_temp()
    print(temperature)
    temp= read_temp()
    urllib3.urlopen("http://francoouesttemp.tech/weather/add_data.php?temp="+temp).read()
#insertion of data into the mysql database
while True:
        print("putting temperature data into temp_pi database")
        i = datetime.datetime.now()
        year = str(i.year)
        month = str(i.month)
        day = str(i.day)
        date = day + "-" + month + "-" + year

        hour = str(i.hour)
        minute = str(i.minute)
        second = str(i.second)
        timestr = hour + ":" + minute + ":" + second

        valT = str(read_temp())

        try:
            cur.execute("""INSERT INTO TAB_CLASSROOM(temp_c,T_Date,T_Time) VALUES(%s,%s,%s)""",(valT,i,timestr))
            db.commit()
        except:
            db.rollback()

        time.sleep(5)

        #this is the part where my code tells me : NameError : name 'urllib3' is not defined ----- I want this part of the code to send the temperature, date and time over to my website.     
        sendDataToServer()

cur.close()  
db.close()

Ответы [ 2 ]

0 голосов
/ 13 января 2019
import urllib 
import requests
url = '....'
response = urllib.request.urlopen(url)
0 голосов
/ 13 января 2019

Если вы хотите отправлять запросы, используя urllib3, вам нужно] создать менеджер пула] (https://urllib3.readthedocs.io/en/latest/user-guide.html#making-requests) сначала.

Кроме того, вы можете использовать HTTP-клиент в стандартной библиотеке Python. Его функция urlopen называется urllib.request.urlopen. В зависимости от того, что вы пытаетесь сделать, пакет requests также может быть вариантом, но он имеет определенные недостатки, когда речь идет об управлении сертификатами для URL-адресов HTTPS (встроенный клиент будет автоматически использовать хранилище сертификатов системы).

...