rest - Python: When to return a response code? -


i have api accepts user input , lots of processing on back. question is, should return response code (200) after input validation or should wait until input processing (saving mysql, formatting input, saving redis, etc) has ended?

sample code:

# should wait greenlets finish processing - might take long time? @app.route('/messages', methods=['post']) def send_message():     user_input = flask.request.form.get('user_input')      if user_is_valid() , user_input_is_valid(user_input):         process_input = [gevent.spawn(format_input_and_save_to_mysql, user_input),                          gevent.spawn(format_input_and_save_to_redis, user_input)]         gevent.join_all(process_input)         return 'processing done', 200      return 'unauthorized', 401  # or should return though processing still being done? @app.route('/messages', methods=['post']) def send_message():     user_input = flask.request.form.get('user_input')      if user_is_valid() , user_input_is_valid(user_input):         gevent.spawn(format_input_and_save_to_mysql, user_input)         gevent.spawn(format_input_and_save_to_redis, user_input)         return 'processing done', 200      return 'unauthorized', 401 

you should think returning response means: when browser receives response server browser thinks request done, redirected or failed somehow.

due should think every specific case. if need results of request handling @ end of tasks, might wait procedures completed , return result or suitable status code if 1 of sub-task fails.

however, if tasks long-running (like several seconds) might in trouble because of request timeouts. if so, there several techniques solve issue using interval polling, long-polling or websockets.

every kind of polling implemented in frontend means browser needs ask server new content or data. return response server when long-running tasks started. analyzing response in browser start polling against given api endpoint. based on progress of long-running tasks might return given status or processed data , stop polling. if processes not done return "still running" status , poll again. polling lead several requests browser , appropriate responses server.

websockets in contrast offer real-time communication between server , browser since both browser , server able raise called events on websockets connection.

at end of day, need decide need. websockets great imho bit tricky handle if beginner. however, there example how implement websockets using flask , gevent. however, there 1 big thing need keep in mind. when requesting progress of server tasks either polling or websockets need make sure have possibility status or progress message tasks totally different thing solve. if need starting point this, suggest having @ task queue, e.g. celery.


Comments