Search code examples
pythonflaskflask-restful

execute python script everytime the API gets request


This is my simple rest api

I'm getting the jira variable from the get_jira script

This is another python script which sends POST request to jira rest api to get a new jira ID

And it works fine but only once. When I start my application and send GET request to it, it gives me new jira ID, let's say ABC-01. The problem is when I send another GET request to get next jira ID, it gives me ABC-01 again

Looks like the get_jira is executed only once, no matter how many GET request I'll send. The only way is to restart the app

Is there any way to get new jira ID (jira) everytime I send GET request to my api?

from flask_restful import Resource, Api, request
import fileinput

app = Flask(__name__)
api = Api(app)

class Get(Resource):
        def get(self):

                ### ACCEPTED PARAMETERS
                source = request.get_json(force=True)['source']
                desc = request.get_json(force=True)['desc']

                ###
                .
                .
                ###

           ---> from get_jira import jira

                return jsonify({"desc":desc},{"source": source},{"jira": jira})

api.add_resource(Get, '/api/v1.0')

if __name__ == '__main__':
        app.run(port=5000,debug=True,use_reloader=True)

Solution

  • Imports should be done at the top of your file for several reasons that I wont get into here, but I think you would do well to do a bit of research into how imports in python work.

    From what I understand of your code, it could be reformatted as follows. Note that this assumes you have a file named get_jira.py which contains a function named generate_jira that returns a new jira name each time its run.

    from flask_restful import Resource, Api, request
    from get_jira import generate_jira
    import fileinput
    
    app = Flask(__name__)
    api = Api(app)
    
    class Get(Resource):
        def get(self):
    
                ### ACCEPTED PARAMETERS
                source = request.get_json(force=True)['source']
                desc = request.get_json(force=True)['desc']
                jira = generate_jira()
    
                return jsonify({"desc":desc},{"source": source},{"jira": jira})
    
    api.add_resource(Get, '/api/v1.0')
    
    if __name__ == '__main__':
        app.run(port=5000,debug=True,use_reloader=True)