最近發(fā)現(xiàn)一個問題钱骂,從項目開始到現(xiàn)在,url 的路徑要爆炸了涕烧,因此要看一下項目里所有 spring controller 的路徑配置咖气。正好前一段時間學(xué)了一點 python挨措,就嘗試使用 python 寫個小程序掃描一下。
需要用到的python函數(shù)
- 讀取文件夾
- 打開文件
- 讀取文件內(nèi)容
- 簡單字符串處理
分析文件內(nèi)容
讀取文件使用 open函數(shù)崩溪,第一個參數(shù)為文件全路徑浅役,第二個參數(shù)為讀寫標識,'r'表示只讀
file.readlines()函數(shù)直接把每一行讀取出來伶唯,返回一個數(shù)組
遍歷數(shù)據(jù)時使用了 enumerate 函數(shù)觉既,這樣可以同時得到行號
tuple是個好東西,簡單的數(shù)據(jù)結(jié)構(gòu)直接用 tuple 來實現(xiàn),不需要新建一個數(shù)據(jù)結(jié)構(gòu)或者對象了瞪讼,函數(shù)返回一個 tuple 也可以讓返回值變得更加豐富
def parse_springmvcfile(filepath, filename):
request_mapping = []
file = open(filepath + "/" + filename, "r")
is_spring_file = False
root_path = None
# 一行一行的讀取文件
for linenum, line in enumerate(file.readlines()):
if is_spring_file: # 已經(jīng)找到配置行說明該文件是 spring controller 文件
if "@RequestMapping" in line: # 找到 springmvc 路徑配置行
if root_path is None:
root_path = get_cotroller_path(line) # 根路徑
else:
request_mapping.append((linenum+1,root_path + get_cotroller_path(line))) # 解析路徑字段
else: # 還沒找到配置行說明該文件是 spring controller 文件,別干其它的,繼續(xù)找
if "@Controller" in line:
is_spring_file = True
return is_spring_file, request_mapping
掃描文件夾
遞歸掃描文件夾钧椰,并將指定后綴的文件全路徑放到數(shù)組中返回
數(shù)組的并接使用 extend 函數(shù),使用 append 函數(shù)向數(shù)組中添加元素
def scanpath(filepath, suffix):
filelist = []
print("開始掃描【{0}】".format(filepath))
if not os.path.isdir(filepath):
print("【{0}】不是目錄".format(filepath))
exit(-1)
for filename in os.listdir(filepath):
if os.path.isdir(filepath + "/" + filename):
filelist.extend(scanpath(filepath + "/" + filename, suffix))
else:
if filename.endswith(suffix):
filelist.append((filepath, filename))
return filelist
截取路徑配置
controller 里的路徑是配置成@RequestMapping("/路徑")符欠,要把里面的路徑取出來嫡霞,需要對字符串進行處理。我對正則不熟背亥,只好用比較土的方法
def get_cotroller_path(request_mapping):
group = request_mapping.split("\"")
path = group[1]
if path.endswith("/"):
path = path[:-1]
if not path.startswith("/"):
path = "/" + path
return path
現(xiàn)在調(diào)用scanpath后使用parse_springmvcfile秒际,就可以把所有controller 文件找到并顯示里面所有的路徑配置悬赏。
開會了開會了狡汉,有些路徑要調(diào)整一下
:)