0

I have faced an issue with a built-in python3 http.server module. Specifically, wfile.write() method in BaseHTTPRequestHandler class.

I'm trying to send an html form pre-defined as a string to a client with a GET request. The output stream to the client is encoded as bytes-like object and transferred to the client.

However, on the client side when the server is started it's not rendered as html form. It ends up wrapped into <pre> tag and displayed as a preformatted text.

Here is the code:

#!/usr/bin/env python3

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs

form = '''<!DOCTYPE html>
  <title>Message Board</title>
  <form method="POST" action="http://localhost:8000/">
    <textarea name="message"></textarea>
    <br>
    <button type="submit">Post it!</button>
  </form>'''

class MessageHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(form.encode())

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MessageHandler)
    httpd.serve_forever()

1 Answer 1

0

It turned out I simply forgot to update 'Content-type' header in GET response method

self.send_header('Content-type', 'text/html; charset=utf-8')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.