#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
from wsgiref.handlers import CGIHandler
from app import app
CGIHandler().run(app)
a=9
b=8
c=a+b
import test
d=test.addd(77,88)
print c
print d
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
"""The above code is in my cgi-bin folder as sumitup.py which works fine and gives the add part of the code as result in the browser when I remove the below import part."""
from wsgiref.handlers import CGIHandler
from app import app
CGIHandler().run(app)
"""I had created a test.py and tried calling the addd method which is also working fine.
Do I need to add the code of wsgiref.handlers library explicity in the same folder.
Note:- I am trying to deploy flask app on a shared hosting www.techpython.com
Can you help me for this.Thanks in advance."""
CGIHandler handles the CGI request for you.
There is no need to print content-length or something like this.
On top of the CGIHandler you could use something like Werkzeug ( http://werkzeug.pocoo.net/ ).
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 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!
I have created a CGIHTTPServer which works fine, problem is no matter what I do, the python pages are never rendered and the source code is always shown in the browser.
pyhttpd.py
#!/usr/bin/python
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = [""]
PORT = 8080
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
cgi-bin/hello.py
#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'
http://some.ip.address:8080/cgi-bin/hello.py:
#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'
I have set the permission on all files to executable, .html files render fine, even moving the file back to the root folder where the server is running makes no difference, I have tried running as root as well as another normal user, exactly the same results.
Tried googling "python pages not rendered" but have not found anything useful !
EDIT
I have also tried running a simpler server with no overrides, but the result is identical, pything code is never rendered:
pyserv.py
#!/usr/bin/python
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
serve = HTTPServer(("",80),CGIHTTPRequestHandler)
serve.serve_forever()
I believe you're having this issue because you have overridden cgi_directories.
The relevant portion of the documentation reads:
"This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts."
Either place your script in the root directory, or remove the override for cgi_directories and place the scrips in the /cgi-bin directory.
Here is a good link that describes a similar simple setup line by line:
https://pointlessprogramming.wordpress.com/2011/02/13/python-cgi-tutorial-1/
UPDATE:
According to a comment on the above page, it appears that setting cgi_directories = [""] results in disabling the cgi directory feature. Instead, set cgi_directories = ["/"], which sets it to the current directory.