flask通过request.path获取定义view函数的文件和行号

1. 目录结构:

$ tree
.
├── app.py
└── get_view.py
0 directories, 2 files  

2. 代码:

# app.py


from flask import Flask

app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello():
    return 'hello'

@app.route('/a', methods=['GET'])
def a():
    return 'a'

@app.route('/a', methods=['POST'])
def b():
    return 'b'

if __name__ == '__main__':
    app.run()
# get_view.py
import inspect
import traceback
from pprint import pprint
from flask import request
from werkzeug.test import EnvironBuilder

from app import app


def get_view_func(path='/', method='GET', **kwargs):
    req = request
    with app.request_context(EnvironBuilder(path=path, method=method, **kwargs).get_environ()):
        rule = req.url_rule
        return app.view_functions[rule.endpoint]

def view_func_filename_linenum(func):
    fn = inspect.getsourcefile(func)
    line_num = inspect.getsourcelines(func)[1]
    return f'function: {func.__name__} -> {fn}: line {line_num}'
    
def get_view_func_location_from_path(path, method='GET'):
    func = get_view_func(path, method)
    return view_func_filename_linenum(func)

if __name__ == '__main__':
    print(view_func_filename_linenum(get_view_func()))
    print(view_func_filename_linenum(get_view_func('/a')))
    print(get_view_func_location_from_path('/a', 'post'))

3. 测试执行

$ python3 get_view.py
function: hello -> /mnt/d/luyangong/tmp/app.py: line 8
function: a -> /mnt/d/luyangong/tmp/app.py: line 12 
function: b -> /mnt/d/luyangong/tmp/app.py: line 16   

代码在 Python 3.8.5 Flask 1.1.2 Werkzeug 1.0.1 环境下测试通过。

4. 参考

  1. inspect标准库官方文档
  2. Flask进阶系列(一)–上下文环境
原文地址:https://www.cnblogs.com/lyg-blog/p/14815547.html