Skip to content

Instantly share code, notes, and snippets.

@razvanioan
Forked from hoangpq/controller.py
Created November 5, 2021 15:09
Show Gist options
  • Save razvanioan/a0ef5e3ccf84b85a805a9c6fa5fad08c to your computer and use it in GitHub Desktop.
Save razvanioan/a0ef5e3ccf84b85a805a9c6fa5fad08c to your computer and use it in GitHub Desktop.
Odoo Asyncio Example
# -*- coding: utf-8 -*-
from odoo import http
import aiohttp
import asyncio
import time
import json
async def get_json(client, url):
async with client.get(url) as response:
assert response.status == 200
return await response.read()
async def fetch_data(name):
async with aiohttp.ClientSession() as client:
return await get_json(client, "http://localhost:3000/{}".format(name))
async def async_run():
try:
task = await asyncio.gather(fetch_data('hoangpq'), fetch_data('odoo'))
return list(map(lambda item: json.loads(item), task))
except:
return []
class AsyncIOController(http.Controller):
def __init__(self):
super(AsyncIOController, self).__init__()
self.__loop = asyncio.new_event_loop()
@http.route('/asyncio/test', type='http', auth="none")
def web_test(self):
start_time = time.time()
user_data = asyncio.run(async_run())
end_time = time.time() - start_time
data = {
'data': user_data,
'execution': str(end_time) + 's'
}
return http.request.make_response(
json.dumps(data),
headers=[
('Content-Type', 'application/json'),
('Cache-Control', 'max-age=%s' % http.STATIC_CACHE),
]
)
const http = require('http');
const PARAMS_REG = /\/(\w+)$/;
function getUserName(req) {
let match;
if ((match = PARAMS_REG.exec(req.url))) {
return match[1];
}
return '';
}
http.createServer(function (req, res) {
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
});
res.write(JSON.stringify({name: getUserName(req)}));
// delay 1s
setTimeout(() => res.end(), 1000);
}).listen(3000, '0.0.0.0', 511, function () {
console.log('Server listen on port 3000');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment