flask通过request.path获取定义view函数的文件和行号
Posted 心有事焉 勿忘勿助
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. 参考
以上是关于flask通过request.path获取定义view函数的文件和行号的主要内容,如果未能解决你的问题,请参考以下文章
request.get_full_path() 和request.path区别