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()
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')