Created
November 22, 2019 09:34
-
-
Save hoangpq/16139539a3783e9b532604db06ad3c65 to your computer and use it in GitHub Desktop.
Odoo Asyncio Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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), | |
] | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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