0

I created a simple API using Flask, in some methods I need to use jvm like this:

@app.route('/inference', methods=['POST'])
def inference():   
     jvm.start()

     #do somethings     

     jvm.stop()
     return something

but if i make my method this way, every time I call the API the server starts and stops jvm, it's very slow.

My question is where can a put the call jvm.start() for using in my methods without starting and stopping jvm every time I call API?

Thanks for any help

Yuan JI
  • 2,927
  • 2
  • 20
  • 29
Luciano Marqueto
  • 1,148
  • 1
  • 15
  • 24

2 Answers2

2

There is a before_first_request decorator in flask:

Registers a function to be run before the first request to this instance of the application.

The function will be called without any arguments and its return value is ignored.


You could create a function to start JVM and register this function by using the decorator:

@app.before_first_request
def start_jvm():
    jvm.start()
Community
  • 1
  • 1
Yuan JI
  • 2,927
  • 2
  • 20
  • 29
1

just use before_first_request as per Yuan JI answer. If you want to cleanup or manually stop the jvm you can use atexit. It will run once the app is terminated.

eg:

@atexit.register
def onend():    
    jvm.stop()
Luciano Marqueto
  • 1,148
  • 1
  • 15
  • 24