Python CGI Script Error: End of script output before headers - python

I'm getting an internal server error (500 err) "End of script output before headers" trying to run a cgi using
XAMPP Apache on Windows
Python 3.3
Notepad++ with UNIX Style (\n) newline chars
My script reads as follows
#!"C:\Python33\python.exe"
import cgi
def htmlTop():
print("Content-type: text/html")
print()
print("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My Server Side Test</title>
</head>
<body>""")
def htmlTail():
print("""</body>
</html>""")
if ___name___ == "__main__":
try:
htmlTop()
print("Hello World")
htmlTail()
except:
cgi.print_exception()
Please note I have tried using print("Content-type: text/html\n\n") as opposed to the extra print statement. Thanks!

I know this is an old post but I found the errors in your script
The first mistake I found was the quote you used when requiring python, so
#!"C:\Python33\python.exe" should be changed to #!C:\Python33\python.exe
The second mistake I found was the additional bars you used There are 3 bars here->___name___<-and here so
___name___ should be changed to __name__
So the final code should be
#!C:\Python33\python.exe
import cgi
def htmlTop():
print("Content-type: text/html")
print()
print("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My Server Side Test</title>
</head>
<body>""")
def htmlTail():
print("""</body>
</html>""")
if __name__ == "__main__":
try:
htmlTop()
print("Hello World")
htmlTail()
except:
cgi.print_exception()

Related

How to call a python function which contains input function to a HTML

I have built a function in python that takes user input using input() and stores that into SQL.
I want to build a front end with flask and when I'm trying to call this python function in Html it displays none.
I tried a similar solution provided over StackOverflow, but as my function contains input(), it is not working.
def my_link():
x=input('your name: ')
return (x)
if __name__ == "__main__":
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Click me
</body>
</html>
I want my Html page to initiate the flask function i.e ask for user input and further my function also stores that user input to SQL server.
But when I'm trying to call this function(which has user input) over HTML, it displays none.

Python not importing files as modules correctly

I am trying to get Python code to work on a web browser using the CGI module, as well as some other file modules that I am trying to import into the main program.
My initial program, which works as required, is the following:
#!C:\Users\Student\AppData\Local\Programs\Python\Python37-32\python.exe
import cgi
def htmlTop():
print("Content-type: text/html")
print()
print("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>My Server Side Test</title>
</head>
<body>""")
def htmlTail():
print("""</body>
</html>""")
if __name__ == "__main__":
try:
htmlTop()
print("Hello World")
htmlTail()
except:
cgi.print_exception()
In the same folder as this program, I have a Python file called "_serverTestModules" containing:
def _serverTestFunction():
print("The file has been imported successfully")
If I then add:
import _serverTestModules
to the original file, both of which are in the same directory, and attempt to access the function from the original code, I get this error:
Traceback (most recent call last):
File "C:/xampp/htdocs/inventorysystem/_serverTest.py", line 26, in <module>
_serverTestFunction()
NameError: name '_serverTestFunction' is not defined
So basically my test program works, but as soon as I try to import functions from other files which are in the same directory (something which I need for my main project), the code fails. Is this a problem with the computer system or the network? Every other answer I have seen on Stack Overflow has either had no answer or an incorrect answer, so any help is much appreciated.
You need to use this
from _serverTestModules import _serverTestFunction

Flask redirect stops working after one try?

When I run flask with python test.py, and then navigate to http://localhost:5000 in my browser, I would expect the terminal to read:
test-1 test-2 test-3
The three print statements ONLY appear when test.py is run for the first time. After that, the terminal will only show:
test-1 test-2
For some reason, the redirecting to the second page is not occurring after the initial run. Is there some sort of weird caching nonsense going on? Can someone please explain what is happening?
from flask import Flask, redirect, url_for, send_from_directory
app = Flask(__name__)
#app.route('/')
def home():
print('test-2')
return redirect(url_for('page2'))
#app.route('/secondPage')
def page2():
print('test-3')
return send_from_directory('.', 'test_dashboard_4.html')
if __name__ == '__main__':
print('test-1')
app.run(debug=True)
I was finding lying around and I found this question is old and no answers yet.
So I will be the one who may help you.
Use render_template and put all of your htmls to templates folder. Something like this
import flask
app = flask.Flask("My life sucks")
#app.route('/')
def index():
return flask.render_templates('your html page here.')
if __name__ == '__main__':
app.run(debug=True)
One other thing, you can't put javascript to same directory where html was.
Instead put it in static folder and add static to where you import javascript like.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<h1>
Hello world!
</h1>
<script src="static/hi.js"></script>
</body>
</html>
This is javascript file if you want to see something
console.log("I get imported!");
document.body.innerHTML += '<p>:D</p>'
Here's the tree
D:.
│ app.py
│
├───static
│ hi.js
│
└───templates
index.html

Template error , while creating a simple website using python

I was creating a simple website using web.py framework . But when i ran the website it gave template error.
My html file code
def with (greeting)
<html>
<head>
<title> "This is a web project"</title>
<body>
<H1>"Yoyo honey singh"</H1>
<H6>greeting<H6>
</body>
</head>
</html>
My python file code
import web
urls = ("/","Index")
app = web.application(urls,globals())
render = web.template.render("\templates")
class Index:
def GET(self):
greeting = "HELLO WORLD"
return render.index(greeting = greeting)
if __name__ == "__main__":
app.run()
I placed the index.html file in the template folder and the python script in the bin folder. The directory structure is like
D:\WEBSITE
WEBSITE
NAME
init.py
bin
app.py
tests
init.py
docs
templates
According to the documentation you should put a $ before each python statement in the template. Therefore the first file becames:
$def with (greeting)
<html>
<head>
<title> "This is a web project"</title>
<body>
<H1>"Yoyo honey singh"</H1>
<H6>$greeting<H6>
</body>
</head>
</html>

How can I print special characters with Python 3? [duplicate]

For HTML5 and Python CGI:
If I write UTF-8 Meta Tag, my code doesn't work.
If I don't write, it works.
Page encoding is UTF-8.
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
şöğıçü
</body>
</html>
""")
This codes doesn't work.
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head></head>
<body>
şöğıçü
</body>
</html>
""")
But this codes works.
For CGI, using print() requires that the correct codec has been set up for output. print() writes to sys.stdout and sys.stdout has been opened with a specific encoding and how that is determined is platform dependent and can differ based on how the script is run. Running your script as a CGI script means you pretty much do not know what encoding will be used.
In your case, the web server has set the locale for text output to a fixed encoding other than UTF-8. Python uses that locale setting to produce output in in that encoding, and without the <meta> header your browser correctly guesses that encoding (or the server has communicated it in the Content-Type header), but with the <meta> header you are telling it to use a different encoding, one that is incorrect for the data produced.
You can write directly to sys.stdout.buffer, after explicitly encoding to UTF-8. Make a helper function to make this easier:
import sys
def enc_print(string='', encoding='utf8'):
sys.stdout.buffer.write(string.encode(encoding) + b'\n')
enc_print("Content-type:text/html")
enc_print()
enc_print("""
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
şöğıçü
</body>
</html>
""")
Another approach is to replace sys.stdout with a new io.TextIOWrapper() object that uses the codec you need:
import sys
import io
def set_output_encoding(codec, errors='strict'):
sys.stdout = io.TextIOWrapper(
sys.stdout.detach(), errors=errors,
line_buffering=sys.stdout.line_buffering)
set_output_encoding('utf8')
print("Content-type:text/html")
print()
print("""
<!doctype html>
<html>
<head></head>
<body>
şöğıçü
</body>
</html>
""")
From https://ru.stackoverflow.com/a/352838/11350
First dont forget to set encoding in file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Then try
import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
Or if you use apache2, add to your conf.
AddDefaultCharset UTF-8
SetEnv PYTHONIOENCODING utf8

Categories