开发者

Making cgi.FieldStorage Store User Inputs?

开发者 https://www.devze.com 2023-02-26 16:39 出处:网络
I wrote a simple Python CGI script but it has a bug : #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout

I wrote a simple Python CGI script but it has a bug :

#!/usr/bin/python2.7

import cgi,sys,random

sys.stderr = sys.stdout

num1 = random.randrange(1,11)
num2 = random.randrange(1,11)
answer = num1 + num2

print("Content-type: text/html\n")
print("<code>%d + %d :</code>") % (num1,num2)
print("""
<form method=POST action="">
<hr>
<th align=right>
<code><b>Answer:</b></code>
<input type=text name="answer">
<tr>""")

form = cgi.FieldStorage()

try:
    if form["answer"].value == str(answer):
        print "<br><b>Good</b>"
    else:
        print "<br><b>Wrong</b>"

except KeyError:
    pass

The numbers regenerates each time this code executes and it can't compare the user input to the answer becouse c开发者_开发问答gi.FieldStorage does not store that input:

Making cgi.FieldStorage Store User Inputs?

PHP programmers use " session_start() " to do what I want to do :

<?php
//Start the session so we can store what the code actually is.
session_start();
$text = rand(1,11);
$_SESSION["answer"] = $answer;
.......
?>

What about Python ? How can we do it?

Edit : I'm really not sure if it is sessions or not .. what I just need is a way to keep what user has inputed so I can compare his answer with the correct answer


You have a couple of options. One is beaker. It's a WSGI middleware designed to do caching and session storage. Not sure how it integrates with a regular CGI app, but shouldn't be too difficult. This would close to PHP's session_start() and storing things in $_SESSION. Beaker has a number of ways to store session information (cookie with session data, cooking with session id, etc etc)

The other way I can think of would be to have a hidden <input> element with the original numbers. This would be submitted with the form, and available in form. To be honest, this is a bad way to do things. It's open to a user attack and therefore is not secure. I know this is just a test application, but might as well start off on the right foot :)

0

精彩评论

暂无评论...
验证码 换一张
取 消