在做前后端分离项目的时候,我们经常还要一层`JSDK`来存放我们的后端请求,后端加一个前端也要加一个,有时候就感觉很麻,有感而发,就想自己搞一个代码生成工具,其实后面还可以开发代码自动生成工具,但是都自动生成了,还有程序员干啥,这个就暂时不写(实际上是作者写不出来),来看看下面的代码
```python
# -*- coding: UTF-8 -*-
import os
import re
from urllib import request
import json
class Tool:
"""
swagger 转js sdk工具类
"""
def __init__(self, host, dir_path):
"""
:param host:远程json文件地址
:param dir_path: 写入文件目录
"""
self.host = host
self.dir_path = dir_path
def raise_api(self):
url = self.host
req = request.Request(url)
res = request.urlopen(req)
res = json.loads(res.read().decode('utf-8'))
paths = res['paths']
# 清空文件
self.clear_file()
# 存放方法字符串数据
for x in paths:
path = x
tmp_x = x[1:-1]
method_name = re.sub(r'\/|-', '_', re.sub('{|}', '', tmp_x))
file_name = method_name.split('_')[0]
params = re.findall(r'.*?\{(.*?)\}.*?', path)
if params:
params.append('params')
params = tuple(params).__str__()
else:
params = '(params)'
for method in paths[x]:
# 过滤掉路径中的 parameters
if method == 'parameters':
continue
tmp_method_name = self.request_methods(paths[x][method]['operationId'], method, params)
fun_content_str = self.fun_content(method, path)
desc = ''
if 'description' in paths[x][method]:
desc = paths[x][method]['description']
note = self.raise_note(path, desc)
if os.path.exists(self.dir_path + file_name + '.js'):
pass
else:
self.init_file(file_name + '.js')
fun_str = '%s%s%s\n' % (note, tmp_method_name, fun_content_str)
file = open(self.dir_path + file_name + '.js', 'a')
file.write(fun_str)
file.close()
def request_methods(self, fun_name, method, params):
"""
构造方法名
:param fun_name:
:param params:
:return:
"""
return 'export const %s = %s => {\n' % (re.sub(r'_(v1|v2|v3|0)', '', fun_name), re.sub(r'\'', '', params))
def fun_content(self, method, path):
"""
构造方法内容
:param method:
:param path:
:return:
"""
return ' return http.%s(`%s`, params)\n}\n' % (method, re.sub(r'\{', '${', path))
def raise_note(self, path, description):
"""
生成注释
:param path:
:param description:
:return:
"""
return '/**\n * path: %s\n * description: %s\n */\n' % (path, re.sub(r'\n', ' \n * ', description))
def clear_file(self):
"""
清空文件
:return:
"""
files = os.listdir(self.dir_path)
for x in files:
if os.path.exists(self.dir_path + x):
file = open(self.dir_path + x, 'w')
file.truncate()
file.write('''/**
* %s API
*/\n
import http from 'src/utils/http'\n
''' % (re.sub(r'.js', '', x)))
file.close()
def init_file(self, file_name):
"""
初始化文件,主要是初始化头部
:param file_name:
:return:
"""
file = open(self.dir_path + file_name, 'w')
file.write('''/**
* %s API
*/\n
import http from 'src/utils/http'\n
''' % (re.sub(r'.js', '', file_name)))
file.close()
```
调用方式
```python
from app.swagger2js import tool
# json的地址
url = 'http://192.168.2.22:5002/swagger.json'
# 保证你的同级目录下面有sdk这个文件夹,我懒,我不想检测有没有这个文件夹
dir_path = os.getcwd() + '\sdk\\'
tmp = tool.Tool(url, dir_path)
tmp.raise_api()
```
**该方法适用`swagger`和用`YAPI`导出的`json`**,来一来看一看大家以后不用谢`sdk`层了
网友评论