Category Archives: Python

[Solved] from django.core.cache import cache Error

Import from django.core.cache import cache
Error:

django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Solution:

from django.conf import settings
settings.configure(DEBUG=True)

Done!

 

 

[Solved] AttributeError: ‘Manager‘ object has no attribute ‘get_by_natural_key‘

Problem description


E:\SweetYaya\MyProj03>python manage.py createsuperuser
Identifier: 12
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle
    error_msg = self._validate_username(username, verbose_field_name, database)
  File "D:\Program Files\Python36\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username
    self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'

terms of settlement


Add to the defined model

class SysUsers(models.Model):
    
	...
	# add
    objects = UserManager()
	
	...

Python netmiko library Cisco telnet switch automation

import time
from netmiko import *
import sys
import os
import getpass

# Read the ip address in the iplist.txt file
iplist = open('iplist_cisco.txt', 'r', encoding='ascii')
ip_addr = iplist.readlines()
iplist.close()

cmdlist = open('cmdlist_cisco.txt', 'r', encoding='ascii')
cmd_line = cmdlist.readlines()
cmdlist.close()

# Iterate through the ip_addr list to connect to the ip
for ip in iter(ip_addr):
    print(ip)
    try:
        S5130 = {
            'device_type': 'cisco_ios_telnet',
            'ip': ip,
            'username': 'cisco',
            'password': 'cisco',
        }
        net_connect = ConnectHandler(**S5130)

        for cmd in iter(cmd_line):
            cmd_result = net_connect.send_command(cmd)
            print('-----------------------------------------------------------------')
            print(cmd)
            print(cmd_result)
            print('-----------------------------------------------------------------')
            print('')
        net_connect.disconnect()
    except (EOFError, NetMikoTimeoutException):
        print('Can not connect to Device')
    except (EOFError, NetMikoAuthenticationException):
        print('username/password wrong!')

The solution of no such file or directory and cannot load native module running error of python3 pyinstaller after packaging

 

use  Pyinstaller is often used to package python3 programs   No such file or directory   Or cannot load native module error is because the required file is not entered into the final execution file. In this case, the parameter is needed when using pyinstaller  — Add binary and add code in the entry file function to solve the problem

Example 1. No such file or directory error   — Add binary parameter solution

Package the portal Python file:

pyinstaller -F -w test.py

Run the packaged executable file:

[root@0109c795032d src]# ./dist/test
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    from salt.client.ssh import ssh_py_shim
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller/test/pyimod03_importers.py", line 540, in exec_module
  File "salt/client/ssh/__init__.py", line 205, in <module>
  File "salt/utils/files.py", line 396, in fopen
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/_MEIudOUhL/salt/client/ssh/ssh_py_shim.pyc'
[5034] Failed to execute script test

By reporting an error, you can see that the file is missing, and it will be increased when pyinstall  — Add binary parameter, as follows:

pyinstaller -F -w test.py \
--add-binary="/opt/python3/lib/python*/site-packages/salt/client/ssh/ssh_py_shim.py:salt/client/ssh"

Parameter explanation:

–The syntax of add binary is: – add binary  & lt; SRC; DEST or SRC:DEST>
SRC is the packaged executable file. The missing file is in the local location,

Dest is the location of the directory that needs to be dynamically copied to when running the executable file. Dest is the relative directory,

The absolute path of the packaged execution file is from  / tmp/_ MEIudOUhL/   It started here_ Meiudouhl is generated automatically, different every time

Dest just needs to write the relative directory. For example, here is   salt/client/ssh

The final absolute path is  / tmp/_ MEIudOUhL/salt/client/ssh
The separator of SRC and dest is colon in Linux and semicolon in windows;

Adding this parameter means that the   ssh_ py_ The shim.py file is packaged into an executable file and dynamically released to a relative directory at runtime   Salt/client/SSH, so as to solve the problem that the error prompt can not find the file

Note:

The error in the error prompt cannot be found   ssh_ py_ Shim. PyC, but the   ssh_ py_ shim.py

This is because salt/client/SSH is the penultimate layer in the whole function call stack/__ init__. Py has the following code:

if not is_windows():
    shim_file = os.path.join(os.path.dirname(__file__), "ssh_py_shim.py")
    if not os.path.exists(shim_file):
        # On esky builds we only have the .pyc file
        shim_file += "c"
    with salt.utils.files.fopen(shim_file) as ssh_py_shim:
        SSH_PY_SHIM = ssh_py_shim.read()

You can see that   ssh_ py_ The shim. Py file is also available, so just find it   ssh_ py_ Shim.py or   ssh_ py_ Shim.pyc in  ” Salt/utils/files. Py “, line 396   No file not found error occurs in fopen function

Example of official website:

https://pyinstaller.readthedocs.io/en/stable/usage.html#shortening -the-command

There are a number of them  — Examples of using Add binary and other related parameters

Example 2. Cannot load native module error forced introduction solution

The error of pyinstall after packing and running is as follows:

  File "test/test.py", line 41, in init_test
  File "salt/transport/client.py", line 27, in factory
  File "salt/utils/asynchronous.py", line 70, in __init__
  File "salt/transport/client.py", line 131, in factory
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller/test/pyimod03_importers.py", line 540, in exec_module
  File "salt/transport/zeromq.py", line 23, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller/test/pyimod03_importers.py", line 540, in exec_module
  File "salt/crypt.py", line 65, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller/test/pyimod03_importers.py", line 540, in exec_module
  File "Cryptodome/Cipher/__init__.py", line 27, in <module>
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "PyInstaller/test/pyimod03_importers.py", line 540, in exec_module
  File "Cryptodome/Cipher/_mode_ecb.py", line 35, in <module>
  File "Cryptodome/Util/_raw_api.py", line 297, in load_pycryptodome_raw_lib
OSError: Cannot load native module 'Cryptodome.Cipher._raw_ecb': Trying '_raw_ecb.cpython-39-x86_64-linux-gnu.so': cannot load library '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so': /tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so: cannot open shared object file: No such file or directory.  Additionally, ctypes.util.find_library() did not manage to locate a library called '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so', Trying '_raw_ecb.abi3.so': cannot load library '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.abi3.so': /tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.abi3.so: cannot open shared object file: No such file or directory.  Additionally, ctypes.util.find_library() did not manage to locate a library called '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.abi3.so', Trying '_raw_ecb.so': cannot load library '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.so': /tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.so: cannot open shared object file: No such file or directory.  Additionally, ctypes.util.find_library() did not manage to locate a library called '/tmp/_MEIPh0VXD/Cryptodome/Util/../Cipher/_raw_ecb.so'

This error also started missing files, missing  _raw_ecb.cpython-39-x86_ 64 Linux gnu.so or  _raw_ecb.so   First, add binary

pyinstaller -F -w test.py \
--add-binary="/opt/python3/lib/python*/site-packages/Crypto/Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so:Cryptodome/Util/../Cipher"

When running in package or reporting this error, repeatedly check that the source file destination address is correct,

At this point   Copy references in later projects _raw_ECB error code to the entry function

Let pyinstaller know that I can use it  _raw_ecb.cpython-39-x86_64-linux-gnu.so to force the package of this so file

The code is as follows:

if __name__ == "__main__":
    try:
        ip = "127.0.0.1"
        port = 1234

        config = {
            'id': 'root',
            'log_level': 'debug',
            'master_ip': ip ,
            'master_port': port,
            'auth_timeout': 5,
            'auth_tries': 1,
            'master_uri': f'tcp://{ip}:{port}'
        }

        salt.transport.client.ReqChannel.factory(config, crypt='clear')
    except Exception as e:
        pass

Package with pyinstall

pyinstaller -F -w test.py \
--add-binary="/opt/python3/lib/python*/site-packages/Crypto/Cipher/_raw_ecb.cpython-39-x86_64-linux-gnu.so:Cryptodome/Util/../Cipher"

Not at this time  — Add binary should be OK, not tested

Summary

In case of errors, the general idea is to use the function call stack to push backward,

If the file cannot be found, it can be used
1. — add binary parameter

2. Compulsory introduction

To solve the problem

[Solved] Plugin requires missing class loader for ‘Python‘

plugin requires missing class loader for ‘Python’

Original Cause Solution

Original cause

Remove the original pycharm on linux, reinstall tar.zip, and run pycharm.sh in the bin directory and get an error

solve

The reason for this is that there are residual files left over when removing pycharm.
After deleting the ~/.local/share/JetBrains and ~/.cache/JetBrains folders, re-run pycharm.sh and you're good to go.

[Solved] Pytorch-geometric Error: No module named torch_sparse

Error report using Python geometric: no module named torch_ Sparse solution:
1) define your torch version and GPU version or CPU
2) enter the download link and click to enter the same sub link as your version:

3) download the four WHL files according to the version number

4) use

pip install XX.whl

Command to install the four files, and then execute the

pip install torch-geometric

That’s it!

[Solved] Backtrader_plotting Error: RuntimeError: Unexpected data type

During installation and use of backtrader_plotting, an error was reported.
Traceback (most recent call last):
File “main.py”, line 86, in
cerebro.plot(b)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader\cerebro.py”, line 991, in plot
start=start, end=end, use=use)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\bokeh.py”,
line 516, in plot
self._blueprint_strategy(obj, start, end, tradingdomain, **kwargs)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\bokeh.py”,
line 228, in _blueprint_strategy
figureenv.plot(master)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\figure.py”, line 180, in plot
self.plot_data(obj)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\figure.py”, line 253, in plot_data
title = sanitize_source_name(labelizer.label(data))
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\labelizer.py”, line 84, in label
primary = _label_datafeed(obj)
File “C:\ProgramData\Anaconda3\lib\site-packages\backtrader_plotting-2.0.0-py3.7.egg\backtrader_plotting\bokeh\labelizer.py”, line 52, in _label_datafeed
raise RuntimeError(f’Unexpected data type: {data.__class__}’)
RuntimeError: Unexpected data type:

Check that it is the getattr(data, n, “”) statement that cannot get the name of the data, so it needs to be actively assigned, modifying the main code.
# Load data
cerebro.adddata(data)
for
# Load data
codename=’510300′
cerebro.adddata(data,name=codename)
Problem solved.

 

[Solved] ModuleNotFoundError: No module named ‘requests‘

environment

MacOS 11.4
has been implemented:

pip3 install requests

It’s still wrong.

This reminds me that there are two PIP3

report errors:

import requests
ModuleNotFoundError: No module named ‘requests’

terms of settlement

Execute the following code

/Library/Frameworks/Python.framework/Versions/3.9/bin/pip3 install requests

It was solved successfully.

Cause analysis:
there are two versions of python3 on my computer. I guess one comes with the system. One is that I use brew to install it automatically due to dependency.

The environment variable is /usr/local/opt/ [email protected]/bin/pip3 script is executed in /Library/Frameworks/Python.framework/Versions/3.9/bin/pip3.

The following test shows that my python3 and PIP3 paths do not match.

itkey@ycmit: ~ $ which python3                                                                           [16:43:26]
/usr/local/bin/python3
itkey@ycmit: ~ $ ls -all /usr/local/bin/python3                                                          [16:43:29]
lrwxr-xr-x  1 itkey  admin  69 12 22  2020 /usr/local/bin/python3 -> ../../../Library/Frameworks/Python.framework/Versions/3.9/bin/python3
itkey@ycmit: ~ $ which pip3                                                                              [16:43:32]
/usr/local/bin/pip3
itkey@ycmit: ~ $ ls -all /usr/local/bin/pip3                                                             [16:43:54]
lrwxr-xr-x  1 itkey  admin  35  4 24 08:25 /usr/local/bin/pip3 -> ../Cellar/[email protected]/3.9.4/bin/pip3

cut the weeds and dig up the roots

Now that the above reason analysis has shown that python3 and PIP3 in my path do not match, just modify them to match.

Put brew before the environment variable

#python3 Use brew
export PATH="/usr/local/Cellar/[email protected]/3.9.4/bin:$PATH"

[Solved] AttributeError: module ‘tensorflow‘ has no attribute ‘distributions‘

Recently, I was watching Mo fan’s PPO code running problems

norm_dist = tf.distributions.Normal(loc=mu, scale=sigma)

report errors:

AttributeError: module 'tensorflow' has no attribute 'distributions'

TF. Distributions is one of the core components provided by tensorflow. It is used to implement some common probability distributions and gives a series of auxiliary calculation functions.

The reason for the problem:
I didn’t look carefully. Mo fan’s version of TensorFlow is TensorFlow r1.3
his version is too old. It’s better to upgrade 1.2.0 to the same version
pay attention to the version of the code in the future

[Solved] ModuleNotFoundError: No module named ‘xxx’; ‘xxx’ is not a package

ModuleNotFoundError: No module named ‘xxx’; ‘xxx’ is not a package
Error.
ModuleNotFoundError: No module named ‘xxx’; ‘xxx’ is not a package
When debugging the script via pycharm, the following error occurs:
ModuleNotFoundError: No module named ‘xml.parser’; ‘xml’ is not a package
Cause.
project
|– xml
|– xml.py
Package name and .py file conflict
Solution.
Change the package name and the .py file name to be inconsistent