You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
2.6 KiB

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 15:02:28
'''
import json
import datetime
import decimal
from flask import Flask as New_flask
from flask.json import JSONEncoder as _JSONEncoder
from flask_cors import CORS
from sqlalchemy.ext.declarative import DeclarativeMeta
#继承JSONEncoder处理sqlalchemy对象编码转换类
class JSONEncoder(_JSONEncoder):
def default(self, obj):
# if isinstance(obj, decimal.Decimal):
# return str(obj)
# elif isinstance(obj, datetime.datetime):
# return obj.isoformat()
# elif isinstance(obj, datetime.date):
# return obj.isoformat()
if isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
if isinstance(obj.__class__, DeclarativeMeta):
#SQLAlchemy类
fields = {}
for field in [x for x in dir(obj) if not x.startswith('_') and x != 'metadata']:
data = obj.__getattribute__(field)
try:
json.dumps(data) # 序列化对象
fields[field] = data
if data is None:
fields[field] = ''
except TypeError: # 添加了对datetime的处理
# if isinstance(data, datetime.datetime):
# fields[field] = data.isoformat()
# elif isinstance(data, datetime.date):
# fields[field] = data.isoformat()
if isinstance(data, (datetime.datetime, datetime.date)):
fields[field] = data.isoformat()
elif isinstance(data, datetime.timedelta):
fields[field] = (
datetime.datetime.min + data).time().isoformat()
elif isinstance(data, decimal.Decimal):
fields[field] = float(data)
else:
fields[field] = None
# Json编码字典
return fields
return json.JSONEncoder.default(self, obj)
class Flask(New_flask):
json_encoder = JSONEncoder
def register_blueprints(app):
"""
"""
from apps import all_router
app.register_blueprint(all_router, url_prefix="/api")
def create_app():
app = Flask(__name__)
CORS(app)
# app.config.from_object('setting')
app.config["SECRET_KEY"] = "wYdilHT~TRw7j{lF+Ee5MR3nFBINONPUcObwjwzge&/(~[C?Yz"
register_blueprints(app)
return app