$ tree
.
├── app.py
└── get_view.py
0 directories, 2 files
# 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‘))
$ 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 环境下测试通过。
flask通过request.path获取定义view函数的文件和行号
原文:https://www.cnblogs.com/lyg-blog/p/14815547.html