Python CGI Script Not Executing - python

Just doing a basic python project with HTML file, i came across a tutorial which gave an idea about how i can execute the code,
here is the HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Admin Login</title>
</head>
<body>
<big><big>Login
Here<br>
<br>
</big></big>
<form action="/var/www/cgi-bin/Login.py" name="LoginForm"><big>Administration
Login<br>
User Name<br>
<input name="UserName"><br>
<br>
<br>
Password<br>
<input name="PassWord"><br>
</big><br>
<br>
<br>
<input type="submit">
<br>
</form>
__ <br>
</body>
</html>
and the python code..
#!/usr/bin/python
import cgi
import cgitb; cgitb.enable()
# get the info from the html form
form = cgi.FieldStorage()
#set up the html stuff
reshtml = """Content-Type: text/html\n
<html>
<head><title>Security Precaution</title></head>
<body>
"""
print reshtml
User = form['UserName'].value
Pass = form['PassWord'].value
if User == 'Myusername' and Pass == 'MyPasword':
print '<big><big>Welcome'
print 'Hello</big></big><br>'
print '<br>'
else:
print 'Sorry, incorrect user name or password'
print '</body>'
print '</html>'
The problem is, when i submit the username and password, it just shows the whole code back on the browser and not the required Welcome message :(. I use Fedora13 .. can anyone tell me what is going wrong? I even changed the permissions of the file(s).

Most likely, your webserver is not configured to execute the script. Even if it's marked as 'executable' in the file system, that doesn't necessarily mean the webserver knows that it should be executing .py files (rather than just serving them 'straight up'). Have a look here if you're running Apache: http://httpd.apache.org/docs/2.0/howto/cgi.html

<form action="/var/www/cgi-bin/Login.py" name="LoginForm">
Try
<form action="/cgi-bin/Login.py" name="LoginForm">
/var/www is probably the path from your ftp site. The web server will only look inside /var/www, so it puts that part there automatically.

Related

python requests.get is returning html page instead of csv content

I am trying to read a csv attachment using python requests.get method with oAUTH token. Its working fine in postman but not from from my program.
I am trying to use below code
import requests
def callF():
url = "https://jiraurl.com/secure/attachment/26433/Bulk_Repo_Archival_SMDH.csv"
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6IkpKRmRuSURYTngt"
jira_headers = {"Authorization":str(token)}
#print(jira_headers)
data = requests.get(url,headers= jira_headers,verify=False)
print(data.content)
if __name__ == '__main__':
callF()
I am getting below response:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body onload="document.forms[0].submit()">
<noscript>
<p>
<strong>Note:</strong> Since your browser does not support JavaScript,
you must press the Continue button once to proceed.
</p>
</noscript>
<form action="https://idag2.jpmorganchase.com/adfs/ls/" method="post">
<div>
<input type="hidden" name="RelayState" value="-ZIP8P-/secure/attachment/2226433/Bulk_Repo_Archival_SMDH.csv"/>
<input type="hidden" name="SAMLRequest" value="PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDJwOkF1dGhuUmVxdWVzdCB4bWxuczpzYW1sMnA9InVybjpvYXNpczpuYW1lczp0Yz"/>
</div>
<noscript>
<div>
<input type="submit" value="Continue"/>
</div>
</noscript>
</form>
</body>
</html>
However in postman also it gave same response for me for sometime but later somehow it is giving proper csv file data. I tried checking in multiple places but no luck. FYI it was working fine when we used basic authentication but after shifting to oAUTH its not working.
Please help.
I am able to resolve this by using below code:
from jira import JIRA
from jira_oauth import get_access_token
username = 'A12345'
jira_access_token = get_access_token()
download_folder = "downloads/"
server = "https://jira.prod.aws.net"
jira = JIRA(basic_auth=(username, jira_access_token), options={'server': server,'verify': False})
issue = jira.issue('DEVSERVOPS-11111', fields='summary,comment,attachment')
for attachment in issue.fields.attachment:
with open(download_folder + '%s' % (attachment.filename), 'wb') as file:
file.write(attachment.get())

Is there an easy way to let a html button execute a python function

I have a python function that creates a .txt file with an output / results and saves it in my project directory. Now i have a html js files where i take that data from the .txt file and i use it and display the data.
Now my problem is, i want to have a button that executes the python script and creates fresh data depending on a variable.
Is there an easy way to do it.
I am quite new to programming web applications.
you can use frameworks like flask. with flask you just paste your function with a root that will be executed when you go on that root.
just set Form action to your root and then make your method there like it:
<form method="POST" action={{ url_for('your_function') }}>
<div style="text-align: center;">
<H1>Admin panel login </H1> <br>
Username <input type = "text" name= "username" /> <br>
Password <input type = "password" name = "password" /> <br>
<input type = "submit">
</div>
</form>
then in your python file :
def your_function():
...
Browser has no permission to read local file system. So you must serve the .txt file first.
foo.txt
Foo
Bar
Baz
foo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
fetch("foo.txt").then(x => x.text()).then(text => document.getElementsByTagName("body")[0].innerText = text)
</script>
</html>
Start HTTP Server in same directory of foo.txt and foo.html
python3 -mhttp.server 8888
Then open http://localhost:8888/foo.html to see the result.

How to invoke python s cript on clicking submit on a web form?

my web form looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
<link rel="stylesheet" href="formstyle.css" type="text/css" />
</head>
<body>
<h1>Form Example</h1>
<form action="checkpoint.py" method="POST">
<input type="text" size="6" maxlength="20" name="text2" />
<input type="submit" value="Go!" />
</form>
</body>
</html>
On clicking submit, the browser prompts for opening the checkpoint.py file instead of executing it. The file is present in the same folder. Can you please help me with what I am doing wrong here?
I am completely new to front end and web development.
First of all you need to have server running (in my case it is runned in cgi-bin\ directory). Here you have source code:
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.' # where your html files and cgi-bin script directory live
port = 8080 # default http://localhost or http://127.0.0.1
srvraddr = ("", port)
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()
Then you need a script for requests processing:
#!/usr/bin/python
import cgi
form = cgi.FieldStorage() # parse form data
print('Content-type: text/html\n')
print('<title>Reply Page</title>')
print(form)
if not 'text2' in form:
print('<h1>Who are you?</h1>')
else:
print('<h1>Hello <i>%s</i>!</h1>' % cgi.excape(form['text2'].value))
And, of course, html file, which you already have (remember about correct value in "action" form attribute).
Run server (leave it running), open your form (http://localhost:8080), and send it - then in your cmd window with running server you should see some info about http request -> that's mean your server is running correctly and getting the requests.
EDIT: this code works on Windows + Python3, but should work also on Linux.

String literals are truncated using flask in python 3.4

When I run the following simple piece of python / flask I do not get the entire string passed through to the html page - instead of "hello this is simon" I get "hello"
I am working on Python 3.4.2
I thought it might be something to do with encoding but I have tried everything I can think of with encoding and still no joy. Any help gratefully received :)
This is the python file (testit.py)
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def init_logon():
email = "hello this is simon"
return render_template("testit.html", email=email)
if __name__ == '__main__':
app.debug = True
app.run()
This is the simple template (testit.html)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" value={{ email }}>
</p>
</body>
</html>
The out put from a number of browsers is all the same: the text is truncated at the first white space
All that is displayed in my browser is:
"hello" - none of the text after the first white space is passed through
apologies I am not allowed to post the image I created :(
In your HTML, you didn't quote the attribute value, so the result of your template is
<input type="text" name="email" id="email" value=hello this is simon>
That means only the "hello" is the value of the "value" attribute. You should be able to see this if you look at the source of the generated page.
You could change your template so it has value="{{ email }}".

Python scripting

I have been following along in Programming Python 4th Edition. One of the tasks is to write a web page that uses cgi to call a python script. It all seems simple enough, but rather than run the script, the browser echos the script instead. I think it may be related to the shebang but I am not sure.
The HTML:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8" />
<title>Interactive Page</title>
</head>
<body>
<form method=POST action="cgi-bin/cgi101.py">
<p><b>Enter your name</b></p>
<p><input type=text name=user /></p>
<p><input type=submit title=Submit /></p>
</form>
</body>
</html>
The script:
#!python
import cgi
form = cgi.FieldStorage()
print('Content-type: text/html\n')
print('<title>Reply Page</title>')
if not 'user' in form:
print('<h1>Who are you?</h1>')
else:
print('<h1>Hello <i>%s</i></h1>' % cgi.escape(form['user'].value))
Instead of a new page showing "Hello Tim" I'm getting a new page with the script dumped into it.
This is an Apache configuration issue that I have not quite worked through. Now when I run it, I get a file not found error from Apache. Progress I guess...

Categories