flask启动为什么会调用__call__

先来看看__call__什么时候时候可以调用

class Aninmal(object):
    def __init__(self,name):
        self.name=name
    def __call__(self, *args, **kwargs):
        print('姓名是:%s'%self.name)

a=Aninmal('小明')

不返回任何结果

class Aninmal(object):
    def __init__(self,name):
        self.name=name
    def __call__(self, *args, **kwargs):
        print('姓名是:%s'%self.name)

a=Aninmal('小明')
a()

有结果返回

D:\python38\python.exe D:/pyprogram/vuefronted/dbinit.py
姓名是:小明

注意这个__call__必须要实例化之后才可以调用不然不会调用

class Aninmal(object):
    def __call__(self, *args, **kwargs):
        print('姓名')

a=Aninmal()

无任何结果返回

内置函数同样可以用__call__()方法来调用

def fun():
    print("hello world")
fun()
fun.__call__()

自定义函数也也可以通过__call__()方法来调用

print(int(3))
print(int.__call__(3))

接下来理解为什么

from flask import Flask
app=Flask(__name__)
if __name__ == '__main__':
    app.run(debug=False)

这个最后会调取Flask的__call__方法

from werkzeug.serving import run_simple
def func(environment,start_response):
    print("请求来了")
    pass

if __name__=='__main__':
    run_simple('127.0.0.1',5000,func)
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit

浏览器输入http://127.0.0.1:5000 这个之后

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
请求来了
127.0.0.1 - - [21/Jul/2023 13:20:04] "GET / HTTP/1.1" 500 -

看到没有执行了func程序,所以会调用这个

你可能感兴趣的:(flask,python,后端)