Skip to content

Instantly share code, notes, and snippets.

@Julien00859
Last active January 8, 2021 10:55
Show Gist options
  • Save Julien00859/a4c7c1f7196842b50ca38c00e07863e8 to your computer and use it in GitHub Desktop.
Save Julien00859/a4c7c1f7196842b50ca38c00e07863e8 to your computer and use it in GitHub Desktop.
Using wsgi, keep the worker alive after the request was fully sent
# Courtesy of JKE
from odoo import http
from functools import partial
from contextlib import closing
import datetime
import time
class JucController(http.Controller):
def process(self, **kw):
with closing(self.registry.cursor()) as self.env.cr:
now = datetime.datetime.now
print("%s LONG PROCESS START with args %r" % (now(), kw))
time.sleep(5)
print("%s LONG PROCESS END" % now())
@http.route('/juc', type='http', auth="public")
def juc(self, **kw):
response = request.make_response("Hello JUC <br/><br/> %r" % request.params)
post_process = partial(self.process, **kw)
response.call_on_close(post_process)
return response
"""
POC
Using wsgi, keep the worker alive after the request was fully sent.
The concrete use-case is to reply to cashier immediately when they call
back to confirm a payment. They need a 200 OK response immediatly but
we need to process the paiement which takes some time becauses it
begins a new flow in the ERP.
Paypal Odoo
|
|
|--POST /paiement/process-> .
.<------HTTP 200 OK-------- |
| set tx done
| postprocess (invoicing, stock, ...)
.
To test the bellow code : $ curl http://localhost:8000
The curl command returns immediately, the time.sleep/print are then
executed.
"""
from wsgiref.simple_server import make_server
import time
def simple_app(environ, start_response):
start_response('200 OK', [
('Content-Type', 'text/plain; charset=utf-8'),
('Content-Length', '256'),
])
yield b"chunk of data__\n" * 16 # reply immediatly, the client closes the request as len(...) == headers["Content-Length"]
# Simulate heavy worker, worker that would timeout the initial http request
for i in range(5):
time.sleep(1)
print(".")
with make_server('', 8000, simple_app) as httpd:
print("Serving on port 8000...")
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment