How to make 'Content-type: text/html' not to be displayed in out

ghz 15hours ago ⋅ 4 views

How to make 'Content-type: text/html' not to be displayed in output?

I have a cgi python script which gets data from html form, handles it and makes a table which put to html code.

The snip of the code:

# -*- coding: utf-8 -*-
import cgi

print('Content-type: text/html\n')
print()
print("""<!DOCTYPE HTML>
        <html>
        # and etc.

When I use the form I see the new page with a table but before this table I see the text string

Content-type: text/html\

How to change the python code for not displaying this string in browser. Put it in comment doesn't help.

Answer

The issue occurs because the newline (\n) after Content-type: text/html is not correctly placed, and the web server interprets it as part of the response body instead of the HTTP header. To fix this issue, ensure there are exactly two newlines between the headers and the start of the HTML content.

Here’s the corrected code:

# -*- coding: utf-8 -*-
import cgi

print("Content-type: text/html")  # Correct HTTP header
print()  # Blank line to indicate end of HTTP headers
print("""<!DOCTYPE HTML>
<html>
<head>
    <title>Table Example</title>
</head>
<body>
    <h1>Your Table</h1>
    <!-- Add your table generation code here -->
</body>
</html>
""")

Explanation:

  1. print("Content-type: text/html"):

    • Sends the Content-type header to the client, which informs the browser that the response is HTML.
  2. print() (empty print statement):

    • Adds a blank line to separate the HTTP headers from the response body. This blank line is required by the HTTP protocol.
  3. The rest of the content follows as HTML. Now, the browser will correctly render the page without displaying the Content-type header.