Search code examples
javascriptpythonhtmlsvgcloudflare-workers

Python Code in a JavaScript running on a Cloudflare Worker


I am building a worker that displays an svg file that is generated using a python code triangles.py. In this python code, I have a function:

getSVGCode(vw, vh):
    ⋮
    callingOtherFunction(inThisFile)
    ⋮
    return svgCode

This function needs to be called from a javascript that is running on Cloudflare Workers (using their method given below). The svgCode is inserted into the html string that the javascript returns to the browser.

const html = `<!DOCTYPE html>
<body>
  <h1>Hello World</h1>

  <svg>My svg here</svg>

  <p>This markup was generated by a Cloudflare Worker.</p>
</body>`

async function handleRequest(request) {
  return new Response(html, {
    headers: {
      "content-type": "text/html;charset=UTF-8",
    },
  })
}

addEventListener("fetch", event => {
  return event.respondWith(handleRequest(event.request))
})

So, I want to know a way to get the Javascript code to pass the viewport dimensions (vh and vw) to the python function so that the svg can be generated using this size. If this option is not possible, I will have to resize the svg which can look stretched. I also want to know how to make the Worker run the python code from javascript too.

I am a beginner at coding, and javascript especially. Please include full information so that I can understand your answers. Thanks!


Solution

  • So, I figured I can use <script></script> inside the html variable. I used something like the following.

    <script>
        const vw = document.documentElement.clientWidth;
        const vh = document.documentElement.clientHeight;
        var svgHref = "https://your.url.here/using?height=vh&ampwidth=vw";
        document.getElementById("triangles-svg").src = svgHref;
    </script>
    

    This was accompanied by a body with,

    <body>
        <img id="triangles-svg">
    </body>
    

    Viola. :)