Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call python functions from a flask instance and return values

here is what I need to do:
I have a python app with a Flask instance running on machine A and another python app running on machine B. The code on machine B shall call a url post request with a json like this:

response=requests.post(url="http://127.0.0.1:5000/get_remote_data", json={"my_key":"my_value"})

The problem is that I don’t know how to call a class method from the received route function and pass the parameter. This is my code on machine A:

from flask import Flask

class MyClass:
    def receive_and_return_values(self, incoming):
        return {"my_return_key":"my_return_value"}

app=Flask(__name__)
@app.route('/get_remote_data', methods=['POST'])
def get_remote_data():
    my_json=request.get_json()
    #Here I want to call 'MyClass.receive_and_return_values' with the parameter 'my_json' and receive the return value.

if __name__ == '__main__':
    app.run(host='127.0.0.1',port=5000)

Grateful for any advice

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can create an instance for my class on both machines and use it like this

import MyClass

@app.route('/get_remote_data', methods=['POST'])
def get_remote_data():
    my_json=request.get_json()
    receive_and_return_values(my_json)

if you want it to be the same object use a singleton design pattern,
of course the class should be in a separate file and import it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading