Category Archives: Python

TypeError: Object of type ‘datetime‘ is not JSON serializable [Solved]

1. Problem description

When using python’s own json to convert data to json data, the data in datetime format reports an error: TypeError: Object of type’datetime’ is not JSON serializable

2. Solution

It is to rewrite and construct the json class, when encountering special date processing, the rest will be built-in.

from datetime import date, datetime

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

When using, json.dumps needs to call the class defined above, specify the cls parameter as ComplexEncoder, the code is as follows:

json.dumps(your_data, cls=ComplexEncoder)

3. Summary

As long as there is an error message about datetime xx is not JSON serializable at runtime, you can use the above methods to solve it perfectly.

Error reporting and resolution of Python 3 using binascii method

The environment is python 3

Problem:

Keep getting errors using the binascii method TypeError: a bytes-like object is required, not ‘str’

#coding: utf-8

import binascii

 a = 'worker'
 b = binascii.b2a_hex(a)
 print(b)

#b = binascii.b2a_hex(a)
#TypeError: a bytes-like object is required, not 'str'

Solution:

Later, the following code will be modified to avoid error reporting

b = binascii.b2a_hex(a.encode())

Principle:

In the new version of Python 3, the Unicode type is cancelled and replaced by the string type (STR) using Unicode characters. The string type (STR) becomes the basic type as shown below, and the encoded becomes the byte type (bytes), but the use methods of the two functions remain the same:

decode               encode

bytes ——> str(unicode)——> bytes

u = 'Chinese' # specify the string type object u
str = u.encode('gb2312') # encode u with gb2312 encoding to get bytes type object str
u1 = str.decode('gb2312') # decode the string str in gb2312 encoding to get the string type object u1
u2 = str.decode('utf-8')# If the result obtained by decoding str with the encoding of utf-8, the original content of the string will not be restored

[Solved] GeForce RTX 3090 with CUDA capability sm_86 is not compatible with the current PyTorch installation

I encountered a problem when running the model

GeForce RTX 3090 with CUDA capability sm_ 86 is not compatible with the current PyTorch installation
The current PyTorch install supports CUDA capabilities sm_ 37 sm_ 50 sm_ 60 sm_ 70 .

Check out the current cuda version:

cat /usr/local/cuda/version.txt
CUDA Version 11 . 0 . 182

Solution:

  1. Change python to python3.8 environment (At the time, an answer to the online information said, I directly changed it to 3.8 at the time, and did not verify whether 3.7 and 3.6 are feasible)
  2. Install nightly’s pytorch, corresponding to the cuda version of 11.0conda install pytorch torchvision cudatoolkit=11 -c pytorch-nightly

Successfully resolved

[Solved] ImportError: cannot import name ‘cached_property’ from ‘werkzeug’

After querying, I learned that this is because the module needs to be explicitly imported in the new version of werkzeug.
Add the following code to the error file (here is werkzeug/init.py) to solve the problem.

from werkzeug.utils import cached_property

Remark:

File path under CentOS system: /usr/local/lib/python3. 7 /site-packages/ werkzeug
File path under Ubuntu system: /usr/local/lib/python3. 6 /dist-packages/ werkzeug
File path under MAC system: /usr/local/lib/python3. 7 /site-packages/werkzeug

end!

[Solved] PyCharm Start Error: TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’

This prompt probably says: “Type error: The operation type is not supported as string and string”, directly put the two strings (BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__ ))) It is improper to connect in the list as the basic path, that is, the path of the entire project. Here the system understands “/” as a division sign, and the system understands it as “string/string”. In fact, what I want to express here is to concatenate BASE_DIR and’templates’ together to form a complete path, and “/” is the path separator.

Solution: change the settings.py'DIRS': [BASE_DIR / 'templates'] 修改为 'DIRS': [str.format(BASE_DIR,'/templates']

Or’DIRS’: [(‘%s/templates’)% BASE_DIR]

Or’DIRS’: [os.path.join(BASE_DIR,’templates’)]  can also be solved

[Solved] Mac Install uwsgi Error: clang: error: no such file or directory: ‘/Users/steven/PycharmProjects/pythonProject/venv/lib/python3.8/config-3.8/libpython3.8.a’

I just changed the mac, install uwsgi and report an error:

1
clang: error: no such file or directory: '/Users/steven/PycharmProjects/pythonProject/venv/lib/python3.8/config-3.8/libpython3.8.a'

 

Solutions:

Global search libpython3.8.a

search results:

1
/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/config-3.8-darwin/libpython3.8.a

 

Solution:

1
2
3
4
5
6
cp -rf /Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/config-3.8-darwin
 /Users/steven/PycharmProjects/pythonProject/venv/lib/python3.8
mv config-3.8-darwin  config-3.8

 

Perform the installation again:

1
pip install uwsgi

PIP install troubleshooting under Windows [How to Solve]

Error:

Traceback (most recent call last): File"C:\Python27\Python27\Scripts\pip-script.py", line 9, in<module> load_entry_point('pip==1.4.1','console_scripts', 'pip')() File"C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\__init__
 .py", line 148, in main

return command.main(args[1:], options) File"C:\Python27\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\basecomm
 and.py", line 169, in main
 text = '\n'.join(complete_log) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb1 inposition 34: ordinal
 not in range(128)

Reason:
the CMD environment of windows defaults to GBK encoding, and pip defaults to UTF-8 encoding
however, in Linux and MAC, the terminal environment defaults to UTF-8 encoding, so no error will be reported

Solution:

Create a file sitecustomize.py in Python directory Python 27\lib\site-packages

import sys sys.setdefaultencoding('gbk')

Python will run this file automatically

 

[Solved] Django REST Framwork Use HyperlinkedModelSerializer Error: `HyperlinkedIdentityField` requires the request in the serializer context

background

When using Django’s ORM function in the project, it is inevitable that serialization and deserialization are involved (for example: python objects are converted into byte sequences that can be used for network transmission; byte sequence data in HTTP requests are converted into python objects) . In the design of Django REST Framwork (hereinafter referred to as DRF), one of the missions of the Serializers class and its subclasses is to help us complete this conversion.

 

Problem Description

Use postman to call DRF’s REST interface, and the following error is reported when reading data:

`HyperlinkedIdentityField` requires the request in the serializer context. Add `context={ ' request ' : request}` when instantiating the serializer. "

 

problem solved

After repeated testing, it is found that in specific Serializers, fields need to specify specific model attributes:

Wrong code:

class SimulationConfigSerializer(serializers.HyperlinkedModelSerializer):    
    . . .
    class Meta:
        model = SimulationConfig       
         fields =   " __all__ "

 

Correct code:

class SimulationConfigSerializer(serializers.HyperlinkedModelSerializer):    
    . . .
    class Meta:
        model = SimulationConfig
         fields = ['id','simulation_name','create_time']

Error reporting in Firefox using selenium in Python

python error in Firefox with selenium:

Traceback (most recent call last):
File “G:\python_work\chapter11\test_selenium_firefox.py”, line 10, in <module>
driver = webdriver.Firefox()
File “C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py”, line 154, in __init__
keep_alive=True)
File “C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 140, in __init__
self.start_session(desired_capabilities, browser_profile)
File “C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 229, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File “C:\Python34\lib\site-packages\selenium\webdriver\remote\webdriver.py”, line 297, in execute
self.error_handler.check_response(response)
File “C:\Python34\lib\site-packages\selenium\webdriver\remote\errorhandler.py”, line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Unable to find a matching set of capabilities

=============================

python version 3.4.3 , selenium version 3.4.3 , Firefox version 49.0.

 

The reason for the error is the version compatibility between python, selenium, Firefox , after upgrading Firefox to the latest version 55.0 the problem is solved.

Also selenium needs geckodriver when calling Firefox, download it and add it to the Firefox installation directory, and add the Firefox installation directory to the system environment variable Path.

=============================

Test code:

1 from selenium import webdriver
2 
3 driver = webdriver.Firefox()
4 driver.get("http://www.google.com")