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 = """GET /123 HTTP/1.1
Host: 127.0.0.1:8888
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7"""
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.