Search code examples
pythonflask-restful

Flask API - Auto Exit


i am making an Flask-API for my project and i want to achieve something when the server restarts or runs, meaning whenever the main block is executed i want to do a check.

the code:

if __name__ == '__main__':

    try: 
        with open('x.p','rb') as pkl_PR:
            ps=pickle.load(pkl_PR) 

        with open('y.p','rb') as pkl_df: 
            df=pickle.load(pkl_df)

        with open('z.p','rb') as pkl_spl: 
            spl_df = pickle.load(pkl_spl)
    except Exception as e:
        logger.debug(e)


    app.run(debug=True)

so if any one of the pickle file doesn't exist, i dont want to start the server and save a log file with error.

so how do i go about it?


Solution

  • You can call sys.exit() from inside the except block, that will cause your program to exit before starting the flask server.