# -*- coding: utf-8 -*-
import datetime
import time
from flask import Flask as _Flask
from flask import request, jsonify as _jsonify
from flask.json import JSONEncoder as _JSONEncoder
from flask_restful import Api, Resource
# 处理自定义数据类型的JSON编码
class JSONEncoder(_JSONEncoder):
def default(self, o):
if hasattr(o, 'keys') and hasattr(o, '__getitem__'):
return dict(o)
if isinstance(o, datetime.datetime):
return o.strftime('%Y-%m-%d %H:%M:%S')
if isinstance(o, datetime.date):
return o.strftime('%Y-%m-%d')
if isinstance(o, datetime.time):
return o.strftime('%H:%M:%S')
if isinstance(o, Exception):
return str(o)
return super(JSONEncoder, self).default(o)
# 改进jsonify,支持传入HTTP状态码和HTTP头
def jsonify(data_or_tuple, status_code=None, headers=None):
if type(data_or_tuple) == tuple and not status_code and not headers:
return jsonify(*data_or_tuple)
rsp = _jsonify(data_or_tuple)
if status_code:
rsp.status_code = status_code
if headers:
for k, v in headers.items():
rsp.headers[k] = v
rsp.headers["Access-Control-Allow-Origin"] = "*" # 允许跨域访问
return rsp
# 继承原始的Flask为了替换其中的JSONEncoder
class Flask(_Flask):
json_encoder = JSONEncoder
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False # 关闭返回JSON数据时根据KEY的字母序重新排序
api = Api(app)
class IndexResource(Resource):
def get(self): # 方法名即http method
obj = {
"str": "Hello world.",
"now": datetime.datetime.now()
}
return jsonify({"result_code": "success", "data": obj}, 200)
api.add_resource(IndexResource, "/") # 绑定主页URL到IndexResource类
class UserResource(Resource):
def get(self, name):
if 1 <= len(name) <= 10:
obj = {
"str": f"Hello, {name}.",
"now": datetime.datetime.now()
}
return jsonify({"result_code": "success", "data": obj}, 200)
else:
return jsonify({"result_code": "fail", "err_code": "INVALID_PARAM", "err_code_des": "name非法"}, 401)
def put(self, name):
pass
def delete(self, name):
pass
api.add_resource(UserResource, "/users/<name>")
class UsersResource(Resource):
# 使用 http://127.0.0.1:30101/users/ POST 访问
# RequestBody: {"name":"daimingzhuang"}
# 记得添加header: Content-Type : application/json
def post(self):
body_obj = request.get_json()
print(body_obj)
return jsonify({"result_code": "success", "data": body_obj}, 200)
api.add_resource(UsersResource, "/users/")
# 生产环境通过gunicorn启动
# 使用 pip3 install gunicorn 安装 gunicorn
# gunicorn -b <bind_ip>:<port> <filename>:<Flask app object>
# 例如: gunicorn -b 0.0.0.0:30101 app:app
if __name__ == '__main__':
SERVER_PORT = 30101
app.run(debug=True, host='0.0.0.0', port=SERVER_PORT)