Python and HTML: Assign a variable to a submit button - python

I'm writing this to a text file which is then read in by my browser. How do I assign the variable "i[0]" to the to the "submit" button so it is passed to my edit_python script?
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python"><input type="submit" value="Submit" /><></FORM></td><td>'+i[0]+'</td><td>'+i[1]+'</td>')
k.write('</tr>')
k.write('</table>')

Put it in a hidden input element. In this case, it will be assigned to the ivalue post request variable.
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python"><input type="hidden" name="ivalue" value="' + i[0] + '"/><input type="submit" value="Submit" /></form></td><td>'+i[0]+'</td><td>'+i[1]+'</td>')
k.write('</tr>')
k.write('</table>')
I cleaned up your HTML a bit too, what was this about before the end form tag?
<></FORM>
If you want a literal <> in your page, use <>. Also, the case of the tags should match for HTML, and should be lowercase for XHTML (which you appear to be using).
EDIT:
I'm writing this to a text file which is then read in by my browser
Also, you do realise the browser won't interpret Python? You need a web server set up correctly to do that.

You want to pass the i[0] attribute to your edit_python script? I think you're looking for a hidden field. So you would modify your script to write out:
Also when using Python variables in strings, I recommend not using the method you did. Check out Python string formatting for some great examples.
I also modified your write method to use dictionary passing for the attributes, which works well when you are calling the same variable multiple times in a stirng.
k.write('<table>')
for i in row:
k.write('<tr>')
k.write('<td><form action="edit_python" method="post" name="edit_python">
<input type="hidden" name="some_attr" value="%(some_attr)s" />
<input type="submit" value="Submit" /></form>
</td><td>%(some_attr)s</td><td>%(some_other_attr)s</td>'
% {"some_attr": i[0], "some_other_attr": i[1]})
k.write('</tr>')
k.write('</table>')

Related

Html form open's file in text insted of showing output from python code

This form shuld show the output on current page
<div class="form">
<form action="QA.py" method="POST" onsubmit="return false; >
<label for="form-search"></label>
<input type="text" id="form-search" placeholder="Search code ">
<!-- BUTTONS -->
<input type="submit" value="code Search" id="code_search" onclick = "processQuery()">
</form>
<p>Answer: </p>
<p id = 'output'></p>
</div>
Insted it just opens this code given billow
def main():
print("Hello,")
IN = input("query ")
QT = f"Q: {IN} ? A:"
response = openai.Completion.create(
model="text-davinci-003",
prompt=QT,
temperature=0,
max_tokens=64,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n\n"]
)
user will input query in form-search on Html page
after clicking submit query shuld go to QA.py Python code
in python code input quary shud be submited to "IN"
after python Proveieds "A:" output shuld seen in 'output
Insted it just opens QA.py
You are missing a quotation mark on the form OnSubmit. The resulting javascript error allows the form to submit to the specified action which is your python file.
The Python file will only execute if run on a webserver that is properly configured. It may be that your web server is not configured for Python, or that you are running the html as a local file (ie from disk, not via a web server), and thus your Python file gets served as a file rather than executed.
It would appear you are trying to run a submit through javascript on a button. In which case the form action isn't required. Instead your processQuery() function which you haven't shared needs to specify which file to exectue.

How to control my webapp with Alexa

I built an alexa skill using Python with Flask_ask, which goes to my DB and retrieves information that I need and spells it out.
I am now trying to create a web UI which would have an option of asking the required question by typing it in or speaking directly to alexa. The web UI works easily as it redirects to the page I want as below :
#app.route('/getdog')
def getdog():
return render_template('mypage.html')
Ideally I would configure an intent which would trigger the change in webpage e.g.
#ask.intent('myintent')
def changepage():
getdog()
Any ideas how to handle this?
You can use use a simple HTML form with a text input box:<form method="POST" action="/changepage/">
Enter Your Query: <input type="text" name="intent_string" />
<input type="submit" value="Ask Alexa"/>
</form>
Your changepage url should call a method which handles calling other intents based on whatever string has been passes in the POST request.
If you not able to exactly match the required intent to call you can add a full text search and match with that

Obtain 'post' form URL using .cgi file

File name: http://localhost/PostForm.html
<form method ="post" action="Information.cgi">
<table>
<tr><td>New date: </td><td> <input type ="date" name="DateNew" /></td></tr><br>
<tr><td>Old date: </td><td> <input type ="date" name="OldDate" /></td></tr><br>
</table>
<input type="submit" name = "submitname" value="Add Entry" />
</form>
Is there any way in which I can obtain the file name, which the post form is located on, from the .cgi python file?
I want to obtain the file name http://localhost/PostForm.html in the Information.cgi Python file.
Any help is greatly appreciated.
Yes, you can get that information, but not in a completely secure way. Browsers insert a header, Referer: which names the previous page.
Reference:
http://en.wikipedia.org/wiki/HTTP_referer
One way would be to grab the referrer info within Information.cgi using an Environmental Variable:
$ReferringPage = $ENV{HTTP_REFERER};
However, that's unreliable. Some users change browser settings to prevent sending referrer info amongst other possible situations where it might not pass.
You could also hard-code something in the referring page's form HTML that lets you know which page sent the referral:
<input type="hidden" name="wherefrom" value="Somepage.html">
Then, in your Information.cgi script, just grab that value and do whatever with it:
use CGI;
$in = new CGI;
$WhichPage = $in->{'wherefrom'};
This could be bypassed by the user or it might not work depending on your setup, but could work in some situations.

how to send response to html using cgi python script

I am trying to design and implement a basic calculator in HTML and Python(using CGI). Below given is a static HTML web page and it is being redirected to a python script (calci.py) where, I am able to calculate the sum but unable to append the resultant to the 'output' textbox.
calculator.html
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form action="python_scripts/calci.py" method="post">
Input 1 : <input type="text" name="input1"/><br>
Input 2 : <input type="text" name="input2"/><br>
<input type="submit" value="+" title="add" /><br>
output : <input type="text" name="output"/><br>
</form>
</body>
</html>
calci.py
import cgi
form = cgi.FieldStorage()
input1 = form.getvalue('input1')
input2 = form.getvalue('input2')
output = str(int(input1)+int(input2))
#how to return the response to the html
#and append it to the textbox
Thanks
This is not the way Web applications work - not hat simply, at least.
If you want to rely only on the browser, and plain HTML for your application, each request has to send the whole html page as a string. You have to use Python's string formatting capabilities to put the resulting number in the correct place in the HTML form.
This way of working is typical of "Web 1.0" applications (as opposed to the "Web 2.0" term used about ten years ago).
Modern web applications use logic that runs on the client side, in Javascript code, to make an HTTP request to retrieve only the needed data - and them, this client-side logic would place your result in the proper place in the page, without reloading the page. This is what isgenerally known as "ajax". It is not that complex, but the html + javascript side of the application become much more complex.
I think one should really understand the "Web 1.0" way before doing it the "Ajax way". in your case, let's suppose your HTML containing the calculator form is in a file called "calc.html". Inside it, where the result should lie, put a markup that can be understood by Python's built-in native string formatting methods, like {result} -
<html>
<body>
...
calculator body
...
Answer: <input type="text" readonly="true" value={result} />
</body>
</html>
And rewrite your code like:
import cgi
form = cgi.FieldStorage()
input1 = form.getvalue('input1')
input2 = form.getvalue('input2')
result = int(input1)+int(input2)
html = open("calc.html".read())
header = "Content-Type: text/html; charset=UTF-8\n\n"
output = header + html.format(result=result)
print (output)
The CGI way is outdated, but is nice for learning: it relies on your whole program being run, and whatever it prints to the standard output to be redirected to the HTTP request as a response. That includes the HTTP Headers, which are included, in a minimal form, above.
(I will leave the complete implementation of a way for the raw '{result}' string not to show up in the inital calculator form as an exercise from where you are 0- the path is to get the initial calculator html template through a CGI script as well, instead of statically, (maybe the same) as well - and just populate "result" with "0" or an empty string)
you can transfer response with the help of java script.
use under print("window.location=url")

Uploading file to Google App Engine using new dev_appserver

Google App Engine documentation makes it appear very simple to get the contents of an uploaded file (self.request.get('user_file')), but while I can do this with old_dev_appserver.py, I cannot get it with the current dev_appserver.py (v1.9.2).
Here's a simple example that generates the incoming data:
<form name="myform" action="http://localhost:8080/sync?cmd=tester" enctype="multipart/form-data" method="post">
Username: <input type="file" name="user_file" />
<input type="submit" value="Submit" />
</form>
In old_dev_appserver.py, one could get the file in GAE via self.request.get('user_file'), but not with the latest (1.9.2) dev_appserver.py
WebApp2 says "Uploaded files are available as cgi.FieldStorage (see the cgi module) instances directly in request.POST." But, request.POST is empty, and cgi.FieldStorage() does not contain 'user_file' either.
Strangely, if I print out self.request.params, I do see an element in the UnicodeMultiDict that is (u'user_file', FieldStorage(u'user_file', u'myfile.ico')). But when I try to get that element, either via named access or just iterating over params, I cannot get it. Even if I do a Len(self.request.params) I get one less than what I see, and the 'user_file' element is missing. If I do this with old_dev_appserver, the Len(self.request.params) is correct.
How do I get user_file?
Figured it out (finally!). I had been logging elements of the request (params, body, etc.) as I sorted through other issues. But you can only instantiate a cgi.FieldStorage element once, so by the time I got to the actual self.request.get('user_file'), it was already gone.
Classic case in which removing the debugging actually makes it work.

Categories