|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | + |
| 5 | +from flask_restx import Resource, Namespace |
| 6 | +from flask import Blueprint, Flask |
| 7 | +from flask_restx import Api, fields, Model |
| 8 | + |
| 9 | +### models.py contain models for data validation ### |
| 10 | +# just a simple model |
| 11 | +MyTest = Model('MyTest', { |
| 12 | + 'data': fields.String(required=True,readonly=True), |
| 13 | +}) |
| 14 | + |
| 15 | +### namespaces.py contains definition of routes |
| 16 | +namesp = Namespace(name="tests", validate=True) |
| 17 | +# register model |
| 18 | +namesp.models[MyTest.name] = MyTest |
| 19 | +@namesp.route('/<string:message>') |
| 20 | +class get_session(Resource): |
| 21 | + |
| 22 | + def __init__(self, api=None, *args, **kwargs): |
| 23 | + # sessions is a black box dependency |
| 24 | + self.answer_service = kwargs['answer_service'] |
| 25 | + super().__init__(api,*args, **kwargs) |
| 26 | + |
| 27 | + @namesp.marshal_with(MyTest) |
| 28 | + def get(self, message): |
| 29 | + # ducktyping |
| 30 | + # any used answer_service must implement this method somehow |
| 31 | + return self.answer_service.answer(message) |
| 32 | + |
| 33 | + |
| 34 | +### managers.py contain logic what should happen on request ### |
| 35 | + |
| 36 | +# loosly coupled and independent from communication |
| 37 | +# could be implemented with database, log file what so ever |
| 38 | +class AnswerService: |
| 39 | + def __init__(self,msg): |
| 40 | + self.msg=msg |
| 41 | + def answer(self, request:str): |
| 42 | + return {'data': request+self.msg} |
| 43 | + |
| 44 | +#### main.py ### |
| 45 | +blueprint = Blueprint("api", __name__, url_prefix="/api/v1") |
| 46 | + |
| 47 | +api = Api( |
| 48 | + blueprint, |
| 49 | + version="1.0", |
| 50 | + doc="/ui", |
| 51 | + validate=False, |
| 52 | +) |
| 53 | + |
| 54 | +# main glues communication and managers together |
| 55 | +ans= AnswerService('~nice to meet you') |
| 56 | +injected_objects={'answer_service': ans} |
| 57 | + |
| 58 | +### could also be defined without namespace ### |
| 59 | +#api.models[MyTest.name] = MyTest |
| 60 | +#api.add_resource(get_session, '/answer', |
| 61 | +# resource_class_kwargs=injected_objects) |
| 62 | + |
| 63 | + |
| 64 | +# inject the objects containing logic here |
| 65 | +for res in namesp.resources: |
| 66 | + res.kwargs['resource_class_kwargs'] = injected_objects |
| 67 | + print(res) |
| 68 | +# finally add namespace to api |
| 69 | +api.add_namespace(namesp) |
| 70 | + |
| 71 | +app = Flask('test') |
| 72 | +from flask import redirect |
| 73 | +@app.route('/', methods=['POST', 'GET']) |
| 74 | +def home(): |
| 75 | + return redirect('/api/v1/ui') |
| 76 | + |
| 77 | +app.register_blueprint(blueprint) |
| 78 | +app.run(debug=False, port=8002) |
0 commit comments