from flask import Flask, Blueprint, jsonify, request from flask_restplus import Resource, Api, fields from json import loads from .utils import sanitize from .app_db.uobject import UObject app = Flask(__name__, instance_relative_config=True) bp = Blueprint('api', __name__, url_prefix='/api') env = app.config['DEBUG'] if env is not False: env = '/doc' api = Api( bp, doc=env, title="UMoSApi", description=""" Unity Mongo Save Api is a simple API for save Unity object in Mongo database. The terme uobject means Unity Object. """, version=0.1 ) uobject = UObject(app) class fieldsDict(fields.Raw): __schema_type__ = ["Dict"] __schema_example__ = {"key": "token"} uobject_model = api.model('UObject', { 'datas': fieldsDict( required=False, description='Variables of the uobject in JSON format.', example={"key": "token"} ) }) @api.route('/objects') class ObjectsList(Resource): def get(self): """ Get uobjects list """ uobjects = uobject.all() if not uobjects: return loads('{"msg": "No uobjects"}'), 404 return sanitize(uobjects), 200 @api.expect(uobject_model) def post(self): """ Register new uobject """ args = request.get_json(force=True) status = uobject.register(args.get('datas')) if '_id' in status: return {"_id": status['_id'], "msg": status['msg']}, status['code'] else: return {"msg": status['msg']}, status['code'] @api.route("/objects/<_id>") class Objects(Resource): @api.expect(uobject_model) @api.doc(params={'_id': '5d244cc13f3d46cb739912ae'}) def patch(self, _id): """ Edit an uobject. """ args = request.get_json(force=True) status = uobject.update(_id, args.get('datas')) return {"msg": status['msg']}, status['code'] @api.doc(params={'_id': '5d244cc13f3d46cb739912ae'}) def delete(self, _id): """ Remove an uobject """ status = uobject.remove(_id) return {"msg": status['msg']}, status['code'] @api.route("/objects//") class ObjectsEq(Resource): @api.doc(params={ 'key': 'kill or total.kill', 'value': '12', }) def get(self, key, value): """ Get uobjects matching key/value """ status = uobject.eq(key, value) return { "msg": status['msg'], "datas": sanitize(status['datas']) }, status['code'] @api.route("/objects/reset") class ObjectsClean(Resource): def get(self): """ Reset collection """ uobject.reset() return "done"