AttributeError: module 'urllib3' has no attribute 'urlopen' in python

10,828

Solution 1

If you want to send requests using urllib3, you need to create a pool manager first.

Alternatively, you could use the HTTP client in the Python standard library. Its urlopen function is called urllib.request.urlopen. Depending on what you are trying to do, the requests package might also be an option, but it has certain disadvantages when it comes to certificate management for HTTPS URLs (the built-in client will automatically use the system certificate store).

Solution 2

import urllib 
import requests
url = '....'
response = urllib.request.urlopen(url)
Share:
10,828
Miguel Alvarez
Author by

Miguel Alvarez

Updated on June 04, 2022

Comments

  • Miguel Alvarez
    Miguel Alvarez almost 2 years

    I am trying to send temperature data over onto one of my website currently online. This code consists of measuring the temperature through a sensor(ds18b20), sending that data onto a mysql databse entitled temp_pi and specifically onto a table intitled TAB_CLASSROOM and lastly sending that data onto a webpage of mine. Everything in this code runs except for the sendDataToServer() part. I specify the error right before this particular line. I have the PHP set up on my website for this to work.

    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()
    
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    AttributeError: module 'urllib3.request' has no attribute 'urlopen' this is the error I am now getting with the updated code u have suggested.
  • Florian Weimer
    Florian Weimer over 5 years
    urllib.request.urlopen, different top-level module.
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    when I do put that, it just gives this following error : NameError : name 'urllib' is not defined
  • Florian Weimer
    Florian Weimer over 5 years
    Sorry, you need to import it (import urllib.request).
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    where exactly would I put the url = '...'
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    Ok that changed the error so now it might be an error to have to do with PHP. But i am unsure. Here is the error : TypeError: Can't convert 'float' object to str implicitly
  • Florian Weimer
    Florian Weimer over 5 years
    You also need to add to change + temp into + str(temp), I assume, or use some other way to construct the request string.
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    Ok that got the code to run. But the data is not showing up onto my website... What does the str(temp) do? Because that could maybe have affected the PHP variables in my php code.
  • Florian Weimer
    Florian Weimer over 5 years
    It converts the floating point value (such as 21.2) into a string ('21.2').
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    Alright. So it has to be something to do with my PHP code?
  • Florian Weimer
    Florian Weimer over 5 years
    Sorry, I have no idea.
  • Miguel Alvarez
    Miguel Alvarez over 5 years
    Alright, well you made my python code work which was indeed my question lol. I have solved one part, the python. XD
  • Martin
    Martin over 5 years
    url is argument of the function: response = urllib.request.urlopen(url)