Tuesday, 22 March 2022

Flask app: handle requests on trigger (no server, non blocking)

TLDR

consider a flask app:

# server.py
import flask

app = flask.Flask(__name__)
# routes, views, etc go here...
# ...

# run app
if __name__ == '__main__':
    app.run()

instead of running the server, I would like to trigger requests and get responses when I decide:

# server-trigger.py
from server import app

dummy_request = """User-Agent: PostmanRuntime/7.26.8
Accept: */*
Postman-Token: 307519e9-11ea-49a8-80f8-9872e40779b0
Host: localhost:4333
Accept-Encoding: gzip, deflate, br
Connection: keep-alive"""

res = app.handle_request(dummy_request) # handle request is not real, but needed.
# app.dispatch_request({})  # tried this, doesn't work.
# app.full_dispatch_request() # doesn't work either.

does it possible using flask?

Scenario details

not necessary to understand, but can help

I have already built and tested Flask app, currently served locally via app.run() option.

instead of running the flask dev server locally, I want another enterprise server to handle requests for my app. I'm trying to integrate with this server. this server allows custom handling requests on custom endpoints.

for example

enterprise-server.com/                   - server home endpoint
enterprise-server.com/custom-endpoint    - my custom endpoint on this server

I can run any python code that I would like on this endpoint, but I must process the request and return a valid response. means that this function cannot start a server, because it will block the thread and wait for requests, without returning any response.

the thing is, I already have a flask app that I want to leverage instead of rewriting my flask app.

so I thought, all the routes already defined in my app instance (which is an instance of Flask server), but I don't want to run the server and listen to requests, I just want to forward requests to the app instance when I decide to.

# flask-server.py
# instead of 
app.run()

# enterprise-server-custom-endpoint-handle.py
# run this instead:
def handle_custom_endpoint(req:string):
   res = app.handle_request(req)
   return res

of course that some adjustments will be made to the flask routes as it runs on other path.



from Flask app: handle requests on trigger (no server, non blocking)

No comments:

Post a Comment