Fork me on GitHub

restfulApi及单例设计模式

restful api

restful: 有统一接口, URI来表示一个资源 使用HTTP的各种请求方法 来完成对资源的增删改查

创建一个urls.py实例化api:

1
2
3
4
5
from flask_restful mport Api
api = Api()
api.init_app(app)

# 在下方写路由

创建一个apis.py编写restful代码:

1
from flask_restful import Resource, marshal_with, fields, reqparse

填写restful代码需注意:

  • 输出格式:函数最后return的json中包含的数据格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
输出格式:
方式1:
first_fields = {
    'code' = fields.Integer,               # 整型
    'msg' = fields.String(default='ok')    # 字符串
}
注:可以添加字符串
方式2:
second_fields = {
    'hobby': fields.List(fields.String),    # 列表 里面是字符串
}
方式3:
third_fields = {
    'data': fields.Nested(one_fields)        # 输出字典类型
}
方式4: 
forth_fields = first_fields                  # 复制first_fields
forth_fields['data'] = fields.Sting          # 在first_fields的基础上添加data
  • 参数解析:函数中需要解析的参数
1
2
3
4
5
6
7
8
9
10
11
test_params = reqparse.RequestParser()

test_params.add_argument('name', dest='my_name')       # 为name改名

test_params.add_argument('id', type=int, required=True, help='id 为必填字段, int类型')

test_params.add_argument('hobby', required=True, action='append')  # 给一个参数赋多个值

test_params.add_argument('pwd', type=str, location='form')     # 从form中获取数据

test_params.add_argument('picture', type=werkzeug.datastructures.FileStorage,  location='files')                                        # 获取文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
my_params.add_argument()中第一个数据为要解析的参数

dest: 为获取的参数修改名字

type: 设置类型

required: 设置是否必填,True表示必填

help: 当解析出错的时候的提示文字

action='append': 给一个参数赋多个值

location: 指定获取数据的位置,不填则默认args

choices: 参数值的约束

type=werkzeug.datastructures.FileStorage,  location='files': 获取文件
1
2
3
4
5
6
7
8
9
解析器继承:当重写了一个next_params = reqparse.RequestParser()
next_params可以继承test_params的所有参数:
继承方法: next_params = test_params.copy()

在原来的基础上添加: next_params.add_argument('age', type=int)

在原来的基础上修改:next_params.replace_argument('hobby', type=str)

在原来的基础上删除: next_params.remove_argument('picture')
  • 开始编写函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class 类名(Resource):
	@marshal_with(输出格式)
    def get(self):                         # 函数名为传输方式
        params = test_params.parse_args()  # 使用上述解析的参数获取数据
        name = params.get('name')
        return {'code': 1}                 # 返回符合自己设置的fields的格式

例如:
class TestAPI(Resource):
	@marshal_with(forth_fields)
	def get(self):
		params = test_params.parse_args()
		name = params.get('my_name')
		return {'data': name}  

在urls.py中填写路由:

1
2
3
4
5
6
7
8
9
from flask_restful mport Api
# 从apis.py中导入程序
from apis.py import *
api = Api()
api.init_app(app)


# 在下方写路由
api.add_resource(TestApi, '/test')

注: 访问时需要将必填的参数填上,否则无法返回正确的数据

想要了解更多可以查看官方文档

单例设计模式

不管怎么创建对象 得到都是同一个

装饰器方式

1
2
3
4
5
6
7
8
def outer(cls):
    instance = None
    def inner(*args, **kwargs):
        nonlocal instance
        if instance == None:
            instance = cls(*args, **kwargs)
        return instance
    return inner

__new__方式

1
2
3
4
5
6
7
8
9
class SQLTool:
    __instance = None
    def __new__(cls, *args, **kwargs):
        print("new")
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            return cls.__instance