python遇见的错误提示

第一种:TypeError: an integer is required (got type str)

def send_msg(udp_scoket):
    '''发送信息'''
    dest_ip = input("请输入对方的IP地址:")
    dest_port = int(input("请输入对方的端口:"))
    send_data = input("请输入要发送的内容:")
    udp_scoket.sendto(send_data.encode('utf-8'),(dest_ip,dest_port))

这里端口号,在scoket中端口号一定要用数字,而在python中经过输入的字符全都是字符串,需要经过字符串转码,把str类型转成int类型

第二种:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 1: invalid start byte

这种是编码格式错误造成的



def rece_msg(udp_scoket):
    recv_data = udp_scoket.recvfrom(1024)
    print(recv_data)
    # print("%s:%s"%(str(recv_data[1]),recv_data[0].decode('utf-8')))

这里我们先把返回值给打印出来,(b'm;R\xa8V\xdeu5\x8b\xddv\x84V\xde\x8c\x03', ('127.0.0.1', 8877))

我们会看见数据是b'm;R,
备注:现在还没有找到解决办法

第三种:ConnectionRefusedError: [Errno 61] Connection refused

这个其实是粗心大意造成的,其实就是socket服务器没开,拒绝访问

第四种: t.start()
TypeError: start() missing 1 required positional argument: 'self'

import  threading
import time


class MyThread(threading.Thread):
    def run(self) -> None:
        for i in range(5):
            time.sleep(1)
            msg = "IM " +self.name +"@ "+ str(self)
            print(msg)


'''
注意这个扩展类的方法,只能创建一个线程,并不能创建多个线程

'''



if __name__ == "__main__":
    t = MyThread
    t.start()

请注意观察倒数第二行,我引用了类对象,但是没有添加括号,其实这个报错的就是初始化对象的时候要添加()

第四种:TypeError: a bytes-like object is required, not 'str',这种基本都是编码格式错误造成的,加上编码格式即可,例如:

new_scoket.send(response.encode('utf-8'))

Traceback (most recent call last):
  File "/Users/wangying/PycharmProjects/Web服务器/05_httpServer_Files.py", line 32, in <module>
    main()
  File "/Users/wangying/PycharmProjects/Web服务器/05_httpServer_Files.py", line 28, in main
    server_client(new_scoket)
  File "/Users/wangying/PycharmProjects/Web服务器/05_httpServer_Files.py", line 13, in server_client
    new_scoket.send(response)
TypeError: a bytes-like object is required, not 'str'

第五种错误:TypeError: cannot use a string pattern on a bytes-like object

出错的主要原因是因为:

     TypeError: can’t use a string pattern on a bytes-like object.

     html用decode(‘utf-8’)进行解码,由bytes变成string。

     py3的urlopen返回的不是string是bytes。
解决方法是:把’html’类型调整一下:html.decode(‘utf-8’),给解析的数据,添加个数据类型。

request = new_scoket.recv(1024).decode('utf-8')

第六种错误:由 try else except引起的:“SyntaxError: invalid syntax”。这是由于在python3.7中写的顺序错误导致的,在3.5中没事,3.7中需要先写try,在写except,再写else,记得else一定要写在except的后面


    try:
        print(file_name)
        f = open("/admin"+file_name,'rb')
    except:
        response = 'HTTP/1.1 200 OK\r\n'
        response += '\r\n'
        response += '------------- file  not  found ---------'
        new_scoket.send(response.encode('utf-8'))
    else:
        html_content = f.read()
        f.close()
        # 加\r\n两个,是由于windows与linuex系统里面的转义字符不一样造成的
        response = 'HTTP/1.1 200 OK\r\n'
        response += '\r\n'
        # 把response header发送回去
        new_scoket.send(response.encode('utf-8'))
        # 把response body发送出去
        new_scoket.send(html_content)


        print("返回的数据", response)
        print("返回的body", html_content)

        print("*" * 100)

第七种错误:在引用C语言动态文件时报错了,报错的内容
OSError: dlopen(./libdead_loop.so, 6): no suitable image found.  Did find:
  主要是我引用了windows中动态编辑后的文件造成的,其实就是您的python和调用的动态文件之间存在体系结构不匹配。使用file检查什么的架构调用的动态文件

解决办法:

直接使用mac终端再次生成下动态文件

/usr/local/bin/python3.7 /Users/wangying/PycharmProjects/Web服务器/main.py
Traceback (most recent call last):
  File "/Users/wangying/PycharmProjects/Web服务器/main.py", line 7, in <module>
    lib = cdll.LoadLibrary("./libdead_loop.so")
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 442, in LoadLibrary
    return self._dlltype(name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(./libdead_loop.so, 6): no suitable image found.  Did find:
	./libdead_loop.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00
	/Users/wangying/PycharmProjects/Web服务器/libdead_loop.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00

第八种错误:RecursionError: maximum recursion depth exceeded while calling a Python object

这个错误看字面意思就是:递归深度超出限制

这有两种,一种是自己写的代码进入死循环了,在反复递归,这时就需要查找原因,找到为什么会反复递归,下面的例子中的方法setMoney中self.money = value,就陷入了死循环,会反复递归

class Money(object):
    def __init__(self):
         self.__money = 0
    def getMoney(self):
        return self.__money
    def setMoney(self,value):
        if isinstance(value,int):
            '''
            这里需要特别注意,当我使用self.money时,其实我调用的是setMoney这个方法,进入了死循环
            '''
            # self.money = value
            #所以我们要使用__money
            self.__money = value
        else:
            print("error:不是整型数字")

    def delMoney(self):
        print("删除金额")
        del self.__money

    #定义个属性,当对这个Money设置值时调用setMoney,当获取值时调用getMoney
    money = property(getMoney,setMoney,delMoney,"商品售价")

a = Money()
print(a.money)
a.money = 100
print(a.money)
del a.money

第二种是我们真的需要深度递归,但是递归次数超出默认设置,python默认的递归深度是很有限的(默认是1000),因此当递归深度超过999的样子,就会引发这样的一个异常。

解决方法很简单,在代码头部加入:(修改递归深度的值,让它变大大一点)

import sys
sys.setrecursionlimit(1000000)

这样修改Python最大递归为100万次,根据个人需求设置次数。

第九种:

问题描述:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)

这个是在https中禁用证书验证后提示的

解决:
禁用安全请求警告

  • 如果requests >= 2.16.0
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

第十种:

问题藐视:

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)

During handling of the above exception, another exception occurred:

使用https,request要验证证书,

解决办法:verify=False

    response = requests.get(url,verify=False)
    print(response)

第十一种:

context must be a dict rather than RequestContext.这个是在Django使用 模板表的时候报的错误:

解决代码context直接等于参数,不需要再经过HttpRequest了

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,RequestContext
# Create your views here.

def my_render(request,template_path,context_dict={}):
    temp = loader.get_template(template_path)
    # context = RequestContext(request, context_dict)
    context = context_dict #最新的Django2.0以上,直接这样写
    res_html = temp.render(context)
    return HttpResponse(res_html)

#定义视图函数,HttpRequest
# http://127.0.0.1:8000/index
def index(request):
    # return HttpResponse('djdjdjdjdjdjjd')
    return my_render(request,'book/index.html',{})

第十二种:_禁止访问 _CSRF验证失败. 

在Django开发时访问一个url时,回有一个注册页面的响应,输入对应的信息后,单击注册按钮进行提交进行页面跳转,显示禁止访问 _CSRF验证失败. 请求被中断_更多信息请设置选项DEBUG=True。

最简单也最不安全的办法

将settings.py文件的MIDDLEWARE中的csrf设置注掉后,再次运行,问题解决。

第十三种:在Django中template遇到

Exception Type: TypeError at /index
Exception Value: context must be a dict rather than RequestContext.、

原代码

# 使用模板文件
# 1.加载模板文件,获取一个模板文件
temp = loader.get_template('booktest/index.html')
 
# 2.定义模板上下文:给模板文件传递数据
context = RequestContext(request, {})
 
# 3.模板渲染:产生标准的html内容
res_html = temp.render(context)
 
# 4.返回给浏览器
return HttpResponse(res_html)

正确的代码

# 1.加载模板文件
temp = loader.get_template('booktest/index.html')
 
# 2.定义模板上下文:给模板文件传递数据
context =  RequestContext(request, {})
context.push(locals())
 
# 3.模板渲染:产生标准的html内容
res_html = temp.render(context=locals(), request=request)
 
# 4.返回给浏览器
return HttpResponse(res_html)

第十四种  在Django部署到iis时遇见的错误:

 Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Python34\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\Python34\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\Python34\lib\site-packages\wfastcgi.py", line 586, in get_wsgi_handler raise Exception('WSGI_HANDLER env var must be set') Exception: WSGI_HANDLER env var must be set StdOut: StdErr:

返回IIS控制台,进入“FastCGI设置”,双击打开,添加Django执行时候的环境变量

这里环境变量一共有三个:

WSGI_HANDLER 为 django.core.handlers.wsgi.WSGIHandler()
PYTHONPATH 为 网站根目录
DJANGO_SETTINGS_MODULE 为 django settings文件位置

添加完成后重启IIS或去应用程序池回收一下就好了

第十五种:还是Django部署在iis时环境变量配置问题

Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "django.core.handlers.wsgi.WSGIHandler()" could not be imported: Traceback (most recent call last): File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__ self.load_middleware() File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\core\handlers\base.py", line 39, in load_middleware for middleware_path in reversed(settings.MIDDLEWARE): File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\administrator\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 961, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'PythonDjango' StdOut: StdErr: 

这个问题是由于上面环境变量的最后一个:DJANGO_SETTINGS_MODULE 配置错误,正确的应该是项目名.settings

第十六个:在Django部署iis时出现的错误,这个错误的意思是配置程序错误了,这个检查的地方比较多,所以可能每个人遇见的情况不一样

Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__ self.load_middleware() File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\core\handlers\base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "c:\users\administrator\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1014, in _gcd_import File "", line 991, in _find_and_load File "", line 975, in _find_and_load_unlocked File "", line 671, in _load_unlocked File "", line 783, in exec_module File "", line 219, in _call_with_frames_removed File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\contrib\auth\middleware.py", line 3, in  from django.contrib.auth.backends import RemoteUserBackend File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\contrib\auth\backends.py", line 2, in  from django.contrib.auth.models import Permission File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\contrib\auth\models.py", line 2, in  from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\contrib\auth\base_user.py", line 48, in  class AbstractBaseUser(models.Model): File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\db\models\base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. StdOut: StdErr:

我这个解决的办法是:在web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <handlers>
            <add name="pythonFastCM" path="*" verb="*" modules="FastCgiModule" scriptProcessor="c:\users\administrator\appdata\local\programs\python\python38\python.exe|c:\users\administrator\appdata\local\programs\python\python38\lib\site-packages\wfastcgi.py"  resourceType="Unspecified" requireAccess="Script" />
        </handlers>
    </system.webServer>
	<appSettings>         
        <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" />  
                    <add key="PYTHONPATH" value="E:\Python\workjob" />         
                    <add key="DJANGO_SETTINGS_MODULE" value="workjob.settings" /> 
    </appSettings>
</configuration>

我添加了个《appSettings》就OK了。

 

第十七种:今天来Django中使用时间时报了个提醒:

RuntimeWarning: DateTimeField AffiliateOrderList.modified received a naive datetime (2020-07-02 23:01:04) while time zone support is active.   RuntimeWarning)

解决办法:settings中USE_TZ设置为False

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/shanghai'

USE_I18N = True

# 设置默认时间显示格式
USE_L10N = False
DATE_FORMAT = 'Y-m-d h:m:s'
DATETIME_FORMAT = 'Y年m月d日 h:m:s'

USE_TZ = False

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值