Skip to content

Commit

Permalink
Determine handler exports from Python module (#1788)
Browse files Browse the repository at this point in the history
After #1780, we now instantiate mainModule at top level (if not in workerd).
In that case we can determine the handler exports from the functions that
are defined on the Python module.
  • Loading branch information
hoodmane authored Mar 9, 2024
1 parent 99efdd5 commit a8b64d2
Showing 1 changed file with 28 additions and 17 deletions.
45 changes: 28 additions & 17 deletions src/pyodide/python-entrypoint-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,27 +173,38 @@ async function preparePython() {
return await getMainModule();
}


export default {
async fetch(request, env, ctx) {
function makeHandler(pyHandlerName) {
return async function (...args) {
try {
const mainModule = await preparePython();
if (mainModule.on_fetch === undefined) {
throw new Error("Python Worker should define an on_fetch method");
}
return await mainModule.on_fetch.callRelaxed(request, env, ctx);
return await mainModule[pyHandlerName].callRelaxed(...args);
} catch (e) {
console.warn(e.stack);
throw e;
}
},
async test(ctrl, env, ctx) {
try {
const mainModule = await preparePython();
return await mainModule.test.callRelaxed(ctrl, env, ctx);
} catch (e) {
console.warn(e.stack);
throw e;
};
}

const handlers = {};

if (IS_WORKERD) {
handlers.fetch = makeHandler("on_fetch");
handlers.test = makeHandler("test");
} else {
const mainModule = await getMainModule();
for (const handlerName of [
"fetch",
"alarm",
"scheduled",
"trace",
"queue",
"pubsub",
]) {
const pyHandlerName = "on_" + handlerName;
if (typeof mainModule[pyHandlerName] === "function") {
handlers[handlerName] = makeHandler(pyHandlerName);
}
},
};
}
}

export default handlers;

0 comments on commit a8b64d2

Please sign in to comment.