Python requests packages urllib3

Fix Error – ImportError: No module named packages.urllib3.exceptions

Recently when I was creating Python automation script I faced this weird error. This literally wasted my couple of days and needless to mentioned frustration it caused.

Below is the error message which I was getting

* fatal: [127.0.0.1]: FAILED! => \n from requests.packages.urllib3.exceptions import InsecureRequestWarning\nImportError: No module named packages.urllib3.exceptions" "stderr_lines": ["CreateFileSystem.py:49: SyntaxWarning: name 'unity_headers' is used prior to global declaration" " global unity_headers" "Traceback (most recent call last):" " File \"CreateFileSystem.py\" line 5 in " " from requests.packages.urllib3.exceptions import InsecureRequestWarning" "ImportError: No module named packages.urllib3.exceptions"] "stdout": "" "stdout_lines": []>

As you can see from the error it keeps saying that there’s error importing “urllib3” package. But This was already installed in the system

For resolving this I had to follow below steps.

  • Uninstall below packages
    • python-devel
    • libevent-devel
    • openssl-devel
    • libffi-devel
    • Requests (pip)
    • urllib3 (pip)
    • Install below packages
      • python-devel
      • libevent-devel
      • openssl-devel
      • libffi-devel
      • Run below command
      pip install requests urllib3

      These steps resolved the issue I was facing.

      Also, DO NOT install pip packges (requests and urllib3) individually, run them as single command. This makes sure that required pip dependencies are also auto installed. Strangely I haven’t seen dependencies getting installed when you install them one by one.

      Источник

      How to use the requests.packages function in requests

      To help you get started, we’ve selected a few requests examples, based on popular ways it is used in public projects.

      Secure your code as it’s written. Use Snyk Code to scan source code in minutes — no build needed — and fix issues immediately.

      def check_until_timeout(url, attempts=30): """ Wait and block until given url responds with status 200, or raise an exception after the specified number of attempts. :param str url: the URL to test :param int attempts: the number of times to try to connect to the URL :raise ValueError: exception raised if unable to reach the URL """ try: import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) except ImportError: # Handle old versions of request with vendorized urllib3 from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) for _ in range(attempts): time.sleep(1) try: if requests.get(url, verify=False).status_code == 200: return except requests.exceptions.ConnectionError: pass raise ValueError('Error, url did not respond after attempts: '.format(attempts, url))
      # https://github.com/jas502n/St2-057 # ***************************************************** import argparse import random import requests import sys try: from urllib import parse as urlparse except ImportError: import urlparse # Disable SSL warnings try: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except Exception: pass if len(sys.argv) <= 1: print('[*] CVE: 2018-11776 - Apache Struts2 S2-057') print('[*] Struts-PWN - @mazen160') print('\n%s -h for help.' % (sys.argv[0])) exit(0) parser = argparse.ArgumentParser() parser.add_argument("-u", "--url", dest="url", help="Check a single URL.", action='store') parser.add_argument("-l", "--list",
      #Author: @_tID #This module requires TIDoS Framework #https://github.com/the-Infected-Drake/TIDoS-Framework import os import time import requests import sys import FileUtils sys.path.append('lib/FileUtils/') from FileUtils import * from colors import * from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) file_paths = [] dir_path = [] def check0x00(web, dirpath, headers): try: for dirs in dirpath: web0x00 = web + dirs req = requests.get(web0x00, headers=headers, allow_redirects=False, timeout=7, verify=False) try: if (req.headers['content-length'] is not None): size = int(req.headers['content-length']) else: size = 0 except (KeyError, ValueError, TypeError):
      import logging import mmap import os import requests import stat import sys from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed # Logging log = logging.getLogger('utils') # Silence warnings from requests try: requests.packages.urllib3.disable_warnings() except Exception as e: log.debug('Unable to silence requests warnings: '.format(str(e))) def check_transfer_size(actual, expected): """Simple validation on any expected versus actual sizes. :param int actual: The size that was actually transferred :param int actual: The size that was expected to be transferred """ return actual == expected def get_pbar(file_id, maxval, start_val=0):
      def set_connection(cls, user_name, password, end_point, session_verify): """Setting the connection settings for the API server. :param user_name: the API accounts user name :param password: the API account password :param end_point: the API's URL/end point :param session_verify: if you want to check the API cert or not """ if not session_verify: requests.packages.urllib3.disable_warnings() cls.user_name = user_name cls.password = password cls.end_point = end_point cls.session = requests.Session() cls.session.auth = HTTPBasicAuth(user_name, password) cls.session.verify = session_verify
      import time import re import sys # Define utf8 as default encoding reload(sys) sys.setdefaultencoding('utf8') # pylint: disable=maybe-no-member if not demisto.params()['proxy']: del os.environ['HTTP_PROXY'] del os.environ['HTTPS_PROXY'] del os.environ['http_proxy'] del os.environ['https_proxy'] # disable insecure warnings requests.packages.urllib3.disable_warnings() ''' GLOBAL VARS ''' SERVER = demisto.params()['server'][:-1] if demisto.params()['server'].endswith('/') else demisto.params()['server'] USERNAME = demisto.params().get('credentials').get('identifier') PASSWORD = demisto.params().get('credentials').get('password') USE_SSL = not demisto.params().get('unsecure', False) CERTIFICATE = demisto.params().get('credentials').get('credentials').get('sshkey') FETCH_TIME_DEFAULT = '3 days' FETCH_TIME = demisto.params().get('fetch_time', FETCH_TIME_DEFAULT) FETCH_TIME = FETCH_TIME if FETCH_TIME and FETCH_TIME.strip() else FETCH_TIME_DEFAULT FETCH_BY = demisto.params().get('fetch_by', 'MALOP CREATION TIME') STATUS_MAP = < 'To Review': 'TODO', 'Remediated': 'CLOSED', 'Unread': 'UNREAD',
      #!/usr/bin/python # # Get configured interfaces using RESTconf # # darien@sdnessentials.com # import requests import sys requests.packages.urllib3.disable_warnings() HOST = 'ios-xe-mgmt.cisco.com' PORT = 9443 USER = 'root' PASS = 'C!sc0123' def get_configured_interfaces(): """Retrieving state data (routes) from RESTCONF.""" url = "http://:

      /api/running/interfaces".format(h=HOST, p=PORT) # RESTCONF media types for REST API headers headers = 'Content-Type': 'application/vnd.yang.data+json', 'Accept': 'application/vnd.yang.data+json'> # this statement performs a GET on the specified url response = requests.get(url, auth=(USER, PASS), headers=headers, verify=False)

      # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time from st2common.runners.base_action import Action from orionsdk import SwisClient from lib.node import OrionNode from lib.utils import send_user_error, is_ip # Silence ssl warnings import requests requests.packages.urllib3.disable_warnings() # pylint: disable=no-member class OrionBaseAction(Action): def __init__(self, config): super(OrionBaseAction, self).__init__(config) self.client = None if "orion_host" not in self.config: raise ValueError("Orion host details not in the config.yaml") elif "orion_user" not in self.config: raise ValueError("Orion user details not in the config.yaml") elif "orion_password" not in self.config: raise ValueError("Orion password details not in the config.yaml") def connect(self):
      import os import codecs from eth_keyfile import create_keyfile_json, extract_key_from_keyfile from icxcli.icx import FilePathIsWrong, PasswordIsNotAcceptable, NoPermissionToWriteFile, FileExists, \ PasswordIsWrong, FilePathWithoutFileName, NetworkIsInvalid from icxcli.icx import WalletInfo from icxcli.icx import utils from icxcli.icx import IcxSigner from icxcli.icx.utils import get_address_by_privkey, get_timestamp_us, get_tx_hash, sign, \ create_jsonrpc_request_content, validate_address, get_payload_of_json_rpc_get_balance, \ check_balance_enough, check_amount_and_fee_is_valid, validate_key_store_file, validate_address_is_not_same from icxcli.icx.utils import post import requests requests.packages.urllib3.disable_warnings() def create_wallet(password, file_path): """ Create a wallet file with given wallet name, password and file path. :param password: Password including alphabet character, number, and special character. If the user doesn't give password with -p, then CLI will show the prompt and user need to type the password. :param file_path: File path for the keystore file of the wallet. :return: Instance of WalletInfo class. """ if not utils.validate_password(password): raise PasswordIsNotAcceptable key_store_contents = __make_key_store_content(password)
      def _disable_http_warnings(self): # disable HTTP verification warnings from requests library requests.packages.urllib3.disable_warnings()

      Источник

      Saved searches

      Use saved searches to filter your results more quickly

      You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

      Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

      By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

      Already on GitHub? Sign in to your account

      AttributeError: module ‘requests.packages’ has no attribute ‘urllib3’ #4104

      AttributeError: module ‘requests.packages’ has no attribute ‘urllib3’ #4104

      Comments

      This commit seems to have broken requests.packages.

      Expected Result

      requests.packages.urllib3 to be the urllib3 package

      Actual Result

      AttributeError: module ‘requests.packages’ has no attribute ‘urllib3’

      Reproduction Steps

      import requests requests.packages.urllib3

      System Information

      < "chardet": < "version": "3.0.3" >, "cryptography": < "version": "" >, "implementation": < "name": "CPython", "version": "3.6.1" >, "platform": < "release": "4.11.2-1-ARCH", "system": "Linux" >, "pyOpenSSL": < "openssl_version": "", "version": null >, "requests": < "version": "2.17.1" >, "system_ssl": < "version": "1010006f" >, "urllib3": < "version": "1.21.1" >, "using_pyopenssl": false > 

      The text was updated successfully, but these errors were encountered:

      I’m able to reproduce this locally. It looks like this may be the product of removing the actual import statements.

      Thanks for the speedy resolution!

      Thanks for the speedy release, but it does not work for us.

      Update: I restarted that run. Maybe it interfered with the release. Let’s see how it works.

      Update: 2.17.2 fails with the same symptom as in 2.17.1:

      Successfully installed certifi-2017.4.17 chardet-3.0.3 click-6.7 click-repl-0.1.2 click-spinner-0.1.7 decorator-4.0.11 idna-2.5 pbr-3.0.1 progressbar2-3.20.2 prompt-toolkit-1.0.14 python-utils-2.1.0 requests-2.17.2 stomp.py-4.1.17 tabulate-0.7.7 urllib3-1.21.1 wcwidth-0.1.7 zhmcclient-0.13.1.dev39 python -c "import zhmcclient; print('Import: ok')" Traceback (most recent call last): File "", line 1, in File "zhmcclient/__init__.py", line 30, in from ._session import * # noqa: F401 File "zhmcclient/_session.py", line 29, in from requests.packages import urllib3 ImportError: cannot import name urllib3 

      Источник

      Читайте также:  Php null пустая строка
Оцените статью