I am new to PYTHON and usually code on PHP. This is the first script I am trying to run on Windows XAMPP. I enabled addhandler for .py and trying to run the following script:
#!C:\Python33\python.exe
# enable debugging
import cgitb
cgitb.enable()
print ("Content-Type: text/html;charset=utf-8")
print ("Hello World!")
and I am getting the following error while running the code:
The server encountered an internal error and was unable to complete your request.
Error message:
malformed header from script 'test.py': Bad header: Hello World!
If you think this is a server error, please contact the webmaster.
You should separate headers from body printing additional newline:
#!C:\Python33\python.exe
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print() # <----------- addtional newlnie for header/body separation.
print("Hello World!")
For anyone who's still getting an error, try replacing print() by print("\r\n") in the following way:
print("Content-Type: text/html;charset=utf-8")
print("\r\n")
print("Hello World!")
This should work!
Related
I am trying to build a redirect service that will allow me to track clicks within emails I send to foreign websites.
Example of the URL of this script:
https://example.com/cgi-bin/redir.py?rurl=https%3A%2F%2Fwww.example.com%2Fde&utm_content=test
I am using Apache2 on Ubunut20.04 with the cgi module, calling the following redir.py script:
#!/usr/bin/python3
import webbrowser
redirect_url = "https://www.example.com"
webbrowser.open(redirect_url)
Now this results in the following error:
End of script output before headers: redir.py
Adding a header:
print('Content-Type: text/plain')
print('')
print('hello world')
With this "hello world" output I get exactly this, a "hello world" message.
How to redirect if a header is needed?
Everything you print gets returned to the requesting browser. Your python file should look like this:
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
print("Content-Type: text/html\n\n")
print()
print("<meta http-equiv=\"refresh\" content=\"0; url=TARGETURL\" />")
Environment:
Python 3.7.7
Windows 10 64bits
Purpose of the code:
Display an HTML report of my software activity. It uses http.server module loaded by file Report.py and the data report are extracted by index.py.
I have a script myscript.py which launches the server by calling a method StartReportTool() inside the module Report.py.
Report.py launch the server and load the index.py.
Files & Folder tree:
- myscript.py <= call the method in module Report.py to launch web server
- /report
- /report/Report.py <= launch the web server
- /report/index.py <= extract the data and display them in html
Source code:
myscript.py:
def report():
from report import Report
Report.StartReportTool()
report()
/report/Report.py
#coding:utf-8
import http.server
import webbrowser
def StartReportTool():
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["/"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open('http://localhost:8888/index.py', new=2)
httpd.serve_forever()
index.py:
#coding:utf-8
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
print("Content-type: text/html; charset=utf-8\n")
html=f"""
<!DOCTYPE html>
My html code
"""
Problem:
When I run myscript.py which launches my http.server, my browser open url 'http://localhost:8888/index.py' and show error 404:
Error response
Error code: 404
Message: No such CGI script ('//index.py').
Error code explanation: HTTPStatus.NOT_FOUND - Nothing matches the given URI.
After investigation, I realized everything is fine when the server is launched by its own script Report.py:
#coding:utf-8
import http.server
import webbrowser
def StartReportTool():
port=8888
address=("",port)
server=http.server.HTTPServer
handler=http.server.CGIHTTPRequestHandler
handler.cgi_directories=["/"]
httpd=server(address,handler)
print(f"Report tool server started on port {port}")
webbrowser.open('http://localhost:8888/index.py', new=2)
httpd.serve_forever()
StartReportTool() # <======= Here is the line of code which launch the server itself inside the same module
You noticed here the last line of code StartReportTool() which calls the method inside the module itself. And it is working fine by this way. My index.py is loaded correctly.
The problem comes when the method StartReportTool() is called from outside the method.
I don't understand the reasons for the issue. Does anyone understand the source of the problem, please?
I created a litlle script but I already have an error, I don't know what causes this or how to fix it, it's on an ubuntu vps, the error is located on this site:
http://alfaxtronic.koding.io/python.py
This is the Script:
#!/usr/bin/python
import os
import platform
import cgitb
cgitb.enable()
print "Content-Type: text/html"
print
print "hi"
form = cgi.FieldStorage()
You missed an import. Add this to the import lines at the top:
import cgi
I configured the httpd file to run python scripts as given in a website. After the configuration I was amazed to see .py file getting executed when placed in the htdocs folder, but .cgi files are not being executed. The error says an internal error.
Thought of proceeding with .py files but when I try to access mysql database, I am not able to.
My .py file is:
import cgi
import MySQLdb
print "Content-type: text/html"
print
print "<html><head>"
print ""
print "</head><body>"
form=cgi.FieldStorage()
name=form["t1"].value
print "Hello. %s" %name
print "hai"
print '<input type="submit"/>'
Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="pwd", db="db1")
cursor = Con.cursor()
sql="SELECT * FROM rec"
cursor.execute(sql)
data = cursor.fetchone()
print "%s" %data
print "</body></html>"
I am not getting any error, but 'data' is not getting printed
output I got was:
hello name hai submit button
new to python. So can u guys please help me out?
python version-2.7
db-mysql
server-apache 2.2
win32 bit
Put following line at first line, and see what error happened (traceback).
import cgitb; cgitb.enable()
My .py file executes ok in terminal, but gives this error in the browser
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Internal Server Error</title>
</head><body>
<h1>Internal Server Error</h1>
...
...
Here is the .py file:
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
print "Content-Type: text/html\n\n" # HTML is following
print # blank line, end of headers
print "<TITLE>CGI script output</TITLE>"
print "<H1>This is my first CGI script</H1>"
print "Hello, world!"
Should i be saving this as a .cgi file? I have tried with the same errors, i have tried many files like this and none work, i am sure the apache server is working as there are other .cgi scripts running from the same directory without issues.
I have also tried:
#!/usr/local/bin/python &
#!/usr/bin/local/python
Any help appreciated.
EDIT
error log output:
(2) No such file or directory: exec of '.../.../.../test.py' failed
Premature end of script headers: test.py
Here is something I wrote up a while ago. These are some good things to look for when troubleshooting Python CGI.
There are some tips to getting Python working in CGI.
Apache setup: This may be old
Add python as a CGI by modifying the following in the configuration:
Options Indexes FollowSymLinks ExecCGI
AddHandler cgi-script .cgi .py
Always browse the pages through Apache.
Note that viewing files in the filesystem through a browser works for most things on an html page but will not work for CGI. For scripts to work they must be opened through the htdocs file system. The address line of your browser should look like:
\\127.0.0.1\index.html or
\\localhost\index.html
If you open a file up through the file system the CGI will not work. Such as if this is in the location bar of your browser:
c:\Apache\htdocs\index.html (or some other example location)
Convert end of lines of scripts to Unix format:
Most editors have options to "show end of lines" and then a tool to convert from Unix to PC format. You must have the end of lines set to Unix format.
State the path to the Python interpreter on the first line of the CGI script:
You must have one of the following lines as the first line of your Python CGI script:
#!C:\Python25\Python.exe
#!/usr/bin/python
The top line is used when you are debugging on a PC and the bottom is for a server such as 1and1. I leave the lines as shown and then edit them once they are up on the server by deleting the first line.
Print a content type specifying HTML before printing any other output:
This can be done simply by adding the following line somewhere very early in your script:
print "Content-Type: text/html\n\n"
Note that 2 end of lines are required.
Setup Python scripts to give debugging information:
Import the following to get detailed debugging information.
import cgitb; cgitb.enable()
An alternative if cgitb is not available is to do the following:
import sys
sys.stderr = sys.stdout
On the server the python script permissions must be set to execute.
After uploading your files be sure to edit the first line and set the permissions for the file to execute.
Check to see if you can hit the python script directly. If you can't, fix with the above steps (2-6). Then when the Python script is working, debug the shtml.