Calling flask restful API resource methods

前端 未结 3 1130
眼角桃花
眼角桃花 2021-02-01 22:52

I\'m creating an API with Flask that is being used for a mobile platform, but I also want the application itself to digest the API in order to render web content. I\'m wondering

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 23:02

    I managed to achieve this, sometimes API's get ugly, in my case, I need to recursively call the function as the application has a extremely recursive nature (a tree). Recursive functions itself are quite expensive, recursive HTTP requests would be a world of memory and cpu waste.

    So here's the snippet, check the third for loop:

    class IntentAPI(Resource):
        def get(self, id):
            patterns = [pattern.dict() for pattern in Pattern.query.filter(Pattern.intent_id == id)]
            responses = [response.dict() for response in Response.query.filter(Response.intent_id == id)]
            return jsonify ( { 'patterns' : patterns, 'responses' : responses } )
    
        def delete(self, id):
            for pattern in Pattern.query.filter(Pattern.intent_id == id):
                db.session.delete(pattern)
    
            for response in Response.query.filter(Response.intent_id == id):
                db.session.delete(response)
    
            for intent in Intent.query.filter(Intent.context == Intent.query.get(id).set_context):
                self.delete(intent.id) #or IntentAPI.delete(self, intent.id)
    
            db.session.delete(Intent.query.get(id))
            db.session.commit()
            return jsonify( { 'result': True } )
    

提交回复
热议问题