Tag Archives: keyerror

[Solved] django mysql\base.py error: KeyError:

Tracking source code:

Problem file:Python36\lib\site-packages\django\db\backends\mysql\base.py

    def get_new_connection(self, conn_params):
        conn = Database. connect(** conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
         return conn

 

solution

  1. Downgrade MySQLclient. Uninstall first, then install the specified version. pip3 uninstall mysqlclientpip3 install mysqlclient==1.3.
  2. My initial solution was to change the django code ( Python36\lib\site-packages\django\db\backends\mysql\base.py ), add an “if” as below:
    def get_new_connection(self, conn_params):
        conn = Database. connect(** conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type] #First
         determine whether the bytes exist in the encoder, and if so, perform the operation 
        if bytes in conn.encoders:
            conn.encoders[SafeBytes] = conn.encoders[bytes]
         return conn
copy code

Python keyerror exception

If you don’t know if there’s a key value in dict, you’d better use it

dict.get(key)
If you read with dict[key] it will report a KeyError exception,

Dict. Get method mainly provides a function to return the default value if the value of corresponding key is not obtained.

And dict[key] actually calls the method with ___
D.get(key[, d]) -> D[K] if K in D, else D. defaults to None