Home > Mobile >  HTTP Python - Image not loading
HTTP Python - Image not loading

Time:09-24

Evening guys!

I tryed some googling about this issue but i didn't find nothing really good to help me, so i game here. The thing is: I want to load a image to my HTTP server but it just doesn't work as intended. My code is:

from http.server import BaseHTTPRequestHandler, HTTPServer
from PIL import Image

im = Image.open(r"calculator.png")

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # processamento
        if self.path in ("/", "Aula12_HTML.html", "/Aula12_2_HTML.html", im):
            # linha de resposta
            self.send_response(200, "OK")

            # linhas de cabeçalhos
            self.send_header("Content-Type", "text/html; charset=utf-8")

            # linha em branco
            self.end_headers()

            if self.path == "/":
                self.path = "/Aula12_HTML.html"

            f = open(self.path[1:])

            # Resposta do Servidor
            self.wfile.write(f.read().encode())
        else:
            self.send_response(404, "NOT FOUND")

And one of my HTML codes is this simple one:

<!DOCTYPE html>

<html>
   <head>
      <meta charset="utf-8">
      <title> Bossbattle </title>
   </head>
   <body>
    <h1> A Calculadora </h1>
    <img src="calculator.png" alt= ">:C" title="U SHAL PERISH"/>
    <p> Olá, seja bem-vi... <b> Você não é bem vindo nessa página!! >:C </b> </p>
    <form action="calcular" method="POST">
        Nível da habílidade      [numb]: <input type="text" name="n1" value="" /> <br>
        Força da habilidade      [numb]: <input type="text" name="n2" value="" /> <br>
        Resisten a habilidade [ -*/]: <input type="text" name="n3" value="" /> <br>
        <input type="submit" name="Enviar" value="Atacar" />
    </form>
   </body>
</html>

CodePudding user response:

Here's a version that works:

from http.server import BaseHTTPRequestHandler, HTTPServer

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # processamento
        if self.path in ("/", "/Aula12_2_HTML.html"):
            print("html")
            self.send_response(200, "OK")
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.end_headers()

            document = "Aula12_HTML.html"

            f = open(document)

            self.wfile.write(f.read().encode())
        elif self.path == '/calculator.png':
            self.send_response(200, "OK")
            self.send_header("Content-Type", "image/png")
            self.end_headers()

            self.wfile.write(open('calculator.png','rb').read())
        else:
            self.send_response(404, "NOT FOUND")

httpd = HTTPServer(('127.0.0.1', 8080), RequestHandler )
httpd.serve_forever()
  • Related