dimanche 28 juin 2020

How to render python on browser

I'm new to python. Im trying to get Python called from my Javasctipt so it can appear on my HTML. I created a small file to act as my webserver, however the response I'm getting from my Javascript is the content of python file itself as opposed to the output of the script. How I can I tell my server to run my python script as opposed to giving back the file?

Note: I'll make my life easier using Flask and I'll be using it for real development, but I just want to get a sense of what is happening in the background.

Thanks!

Myserver.py

from http.server import HTTPServer, BaseHTTPRequestHandler

class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
        if self.path == '/':
            self.path = '/index.html'
        try:
            file_to_open = open(self.path[1:]).read()
            self.send_response(200)
        except:
            file_to_open = "File not found"
            self.send_response(404)
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))

httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>tittle</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="test.js"></script>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>

Test.js

$.ajax({
                    url: '/test2.py',
                    success: function(data) {
                    alert(data);
                    }
})

test2.py

print("Hello there")
print("Hello one, ")
print("Hello two2, ")



Aucun commentaire:

Enregistrer un commentaire