Shinyshell Community Forums > Coding >
Python General Questions


[<] [1]


September 06 02009, 01:34 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
said
I personally dislike Mako. I reckon templates are neater if they don't have embedded Python code.


said
Mako's another not-so neat idea, but probably acceptable if you've strapped for time, and have not got your own code.


That just makes everything else inconvenient. The reason why Mako is preferred over shoddy implementations like Genshi is because it's easy to understand.

All Mako does is provide a simple library with bindings to the actual Python language. It doesn't force you to revolve around it; it does on you. You shouldn't have to learn an entirely new way of getting things done in a templating system. If you want to stuff all your logic in the controller, then you're free to do that and just pass the content to render().

I recommend you try the recently fleshed out SUIT Framework, if that's your perspective on how templating should be handled. It allows you to define your own nodes. A Python implementation is being written. It's worth dropping in.

said
There are a lot of crap "frameworks" for Python, including Pylons and the heavyweight champion Django.


What exactly is the issue with Pylons? It's a clean approach to the MVC structure, and a great RAD tool. It offers you the general flexibility of Python, and doesn't impose silly rules that many frameworks call "coding standards".

In comparison to Django, Pylons ends up winning. Django makes use of too many in-house solutions and reinventing the wheel, which makes everything all the more non-Pythonic.
______________________________
FHQ

September 06 02009, 01:39 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

'key in dict'? I'm afraid I don't understand, Faltzer. D:

Thanks, everyone for all your help. :o You're all pretty awesome.

September 06 02009, 01:47 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
 d = {'a': 1, 'b': 2, 'c': 3}
 
 if 'a' in d :
 	print 'It's there!'
 
d = {'a': 1, 'b': 2, 'c': 3}

if 'a' in d :
print 'It's there!'
]]>

______________________________
FHQ

September 06 02009, 02:37 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Okay, now I see. ^-^

But about the AJAX thing, how do I get the information back to the Javascript? Can I simply print it?

September 06 02009, 02:43 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
...What?


______________________________
FHQ

September 06 02009, 03:09 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

I'm coding a quiz checker. Here's the quiz, then the Python script.

<script type="text/javascript"> 
function ajaxFunction()
{
// this will be your request object
var req = null;

// for newer IE browsers
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
// in case that fails, try for older IE browsers
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// otherwise use the Firefox/Chrome/etc objects
if (req == null) req = new XMLHttpRequest();

// set up an onreadystatechange callback
// it'll be called when the request state changes
req.onreadystatechange = process_req_change;
req.open("GET", "quiz1.py", true);
req.send(null);

function process_req_change()
{
// when the state is 4, it means that the
// data has been retrieved and can be used
if (req.readyState == 4)
{
// make sure HTTP/1.1 status code 200
// has been sent (OK).
if (req.status == 200)
{
response = req.responseText;
document.getElementById('result').innerHTML = response;
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}
}
</script>

<div id="result"></div>

<form method="get" action="javascript: ajaxFunction(); return false;">

<ol>
<li>
In the animé series, what is the main character's last name?
<br />
<input type="text" name="q1" />
</li>

<li>
What is the first Pokémon's name in the National Pokédex?
<br />
<input type="text" name="q2" />
</li>

<li>
What Pokémon could change gender when it evolves? <!--Azurill--!>
<br />
<input type="text" name="q3" />
</li>

<li>
This Pokémon is the pokemon with the lowest base stats <!--Shedinja--!>
<br />
<input type="text" name="q4" />
</li>

<li>
What Pokémon has the lowest base stats without anything special to make up for it's lack?<!--Luvdisc--!>
<br />
<input type="text" name="q5" />
</li>
</ol>
<input type="submit" />
</form>
<script type="text/javascript">
function ajaxFunction()
{
// this will be your request object
var req = null;

// for newer IE browsers
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
// in case that fails, try for older IE browsers
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
// otherwise use the Firefox/Chrome/etc objects
if (req == null) req = new XMLHttpRequest();

// set up an onreadystatechange callback
// it'll be called when the request state changes
req.onreadystatechange = process_req_change;
req.open("GET", "quiz1.py", true);
req.send(null);

function process_req_change()
{
// when the state is 4, it means that the
// data has been retrieved and can be used
if (req.readyState == 4)
{
// make sure HTTP/1.1 status code 200
// has been sent (OK).
if (req.status == 200)
{
response = req.responseText;
document.getElementById('result').innerHTML = response;
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}
}
</script>

<div id="result"></div>

<form method="get" action="javascript: ajaxFunction(); return false;">

<ol>
<li>
In the animé series, what is the main character's last name?
<br />
<input type="text" name="q1" />
</li>

<li>
What is the first Pokémon's name in the National Pokédex?
<br />
<input type="text" name="q2" />
</li>

<li>
What Pokémon could change gender when it evolves? <!--Azurill--!>
<br />
<input type="text" name="q3" />
</li>

<li>
This Pokémon is the pokemon with the lowest base stats <!--Shedinja--!>
<br />
<input type="text" name="q4" />
</li>

<li>
What Pokémon has the lowest base stats without anything special to make up for it's lack?<!--Luvdisc--!>
<br />
<input type="text" name="q5" />
</li>
</ol>
<input type="submit" />
</form>
]]>


#!/usr/bin/python 

print "Content-Type: text/html\n"

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

i = 0

set = 0

omgarray = ["q1", "q2", "q3", "q4", "q5"]

while i < 5:
check = omgarray[i]
if form.has_key(check):
i = i + 1
set = set + 1
else:
wrong = i + 1
i = i + 1

if set == 5:
correct = 0
i = 0
answers = ["Ketchum", "Bulbasaur", "Azurill", "Shedinja", "Luvdisc"]
while i < 5:
check = omgarray[i]
if form.getvalue(check) == answers[i]:
correct = correct + 1
i = i + 1
print "You got %d right." % correct
else:
print "You left %d fields blank." % wrong
#!/usr/bin/python

print "Content-Type: text/html\n"

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

i = 0

set = 0

omgarray = ["q1", "q2", "q3", "q4", "q5"]

while i < 5:
check = omgarray[i]
if form.has_key(check):
i = i + 1
set = set + 1
else:
wrong = i + 1
i = i + 1

if set == 5:
correct = 0
i = 0
answers = ["Ketchum", "Bulbasaur", "Azurill", "Shedinja", "Luvdisc"]
while i < 5:
check = omgarray[i]
if form.getvalue(check) == answers[i]:
correct = correct + 1
i = i + 1
print "You got %d right." % correct
else:
print "You left %d fields blank." % wrong
]]>


I want to check it with AJAX, just to learn how to use AJAX and check the form successfully without having the answers THERE in the source code, like with only JavaScript. :D

I just need to know how to call on the process_req_change function, I think.

EDIT: I just revised it a little. I put in the AJAX? And this is the page.

September 06 02009, 16:42 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Oh dear, first of all -- functions within functions are not what I'd do.
<script type="text/javascript"> 
var req = null;

function process_req_change()
{
// when the state is 4, it means that the
// data has been retrieved and can be used
if (req.readyState == 4)
{
// make sure HTTP/1.1 status code 200
// has been sent (OK).
if (req.status == 200)
{
response = req.responseText;
document.getElementById('result').innerHTML = response;
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}

function ajaxFunction()
{
// for newer IE browsers
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
// in case that fails, try for older IE browsers
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
// otherwise use the Firefox/Chrome/etc objects
if (req == null) req = new XMLHttpRequest();

// get answer data
var the_answers = "";

var answers = document.getElementById("inputlist").getElementsByTagName("li");
for (var i = 0; i < answers.length; i++)
{
var inputs = answers[i].getElementsByTagName("input");

for (var j = 0; j < inputs.length; j++)
{
name = inputs[j].getAttribute("name");
status = inputs[j].value;

if (status == null) status = "";
the_answers += "&" + name + "=" + status;
}
}
the_answers = the_answers.substr(1, the_answers.length);

// set up an onreadystatechange callback
// it'll be called when the request state changes
req.onreadystatechange = process_req_change;
req.open("GET", "quiz1.py?" + the_answers, true);
req.send(null);
}
</script>
<script type="text/javascript">
var req = null;

function process_req_change()
{
// when the state is 4, it means that the
// data has been retrieved and can be used
if (req.readyState == 4)
{
// make sure HTTP/1.1 status code 200
// has been sent (OK).
if (req.status == 200)
{
response = req.responseText;
document.getElementById('result').innerHTML = response;
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}

function ajaxFunction()
{
// for newer IE browsers
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
// in case that fails, try for older IE browsers
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
// otherwise use the Firefox/Chrome/etc objects
if (req == null) req = new XMLHttpRequest();

// get answer data
var the_answers = "";

var answers = document.getElementById("inputlist").getElementsByTagName("li");
for (var i = 0; i < answers.length; i++)
{
var inputs = answers[i].getElementsByTagName("input");

for (var j = 0; j < inputs.length; j++)
{
name = inputs[j].getAttribute("name");
status = inputs[j].value;

if (status == null) status = "";
the_answers += "&" + name + "=" + status;
}
}
the_answers = the_answers.substr(1, the_answers.length);

// set up an onreadystatechange callback
// it'll be called when the request state changes
req.onreadystatechange = process_req_change;
req.open("GET", "quiz1.py?" + the_answers, true);
req.send(null);
}
</script>
]]>


That will get the stuff from your forms and make it AJAX-sendable.

<div id="result"></div>  
<form method="get" onsubmit="return false;">

<ol id="inputlist">
<li>
In the animé series, what is the main character's last name?
<br />
<input type="text" name="q1" value="" />
</li>

<li>
What is the first Pokémon's name in the National Pokédex?
<br />
<input type="text" name="q2" value="" />
</li>

<li>
What Pokémon could change gender when it evolves?
<br />
<input type="text" name="q3" value="" />
</li>

<li>
This Pokémon is the pokemon with the lowest base stats
<br />
<input type="text" name="q4" value="" />
</li>

<li>
What Pokémon has the lowest base stats without anything special to make up for it's lack?<!--Luvdisc-->
<br />
<input type="text" name="q5" value="" />
</li>
</ol>
<input type="submit" onmouseup="ajaxFunction(); return false;" />
<div id="result"></div>
<form method="get" onsubmit="return false;">

<ol id="inputlist">
<li>
In the animé series, what is the main character's last name?
<br />
<input type="text" name="q1" value="" />
</li>

<li>
What is the first Pokémon's name in the National Pokédex?
<br />
<input type="text" name="q2" value="" />
</li>

<li>
What Pokémon could change gender when it evolves?
<br />
<input type="text" name="q3" value="" />
</li>

<li>
This Pokémon is the pokemon with the lowest base stats
<br />
<input type="text" name="q4" value="" />
</li>

<li>
What Pokémon has the lowest base stats without anything special to make up for it's lack?<!--Luvdisc-->
<br />
<input type="text" name="q5" value="" />
</li>
</ol>
<input type="submit" onmouseup="ajaxFunction(); return false;" />
]]>


That HTML will work with the above JS. So now you've only got your Python side to worry about. Oh, yeah, and HTML comments are
<!-- comment --> 
<!-- comment -->
]]>

Not
 <!-- bad syntax --!>
 
<!-- bad syntax --!>
]]>


The Python code looks okay to me, though I've made some changes.

#!/usr/bin/python  

print "Content-Type: text/html\n"

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

wrong = 0
set = 0
omgarray = ["q1", "q2", "q3", "q4", "q5"]

for check in omgarray:
if form.has_key(check): set += 1
else: wrong += 1

if set == 5:
correct = 0
i = 0
answers = ["Ketchum", "Bulbasaur", "Azurill", "Shedinja", "Luvdisc"]
while i < 5:
check = omgarray[i]
if form[check].value == answers[i]: correct += 1
i += 1
print "You got %d right." % correct
else:
print "You left %d fields blank." % wrong
#!/usr/bin/python

print "Content-Type: text/html\n"

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

wrong = 0
set = 0
omgarray = ["q1", "q2", "q3", "q4", "q5"]

for check in omgarray:
if form.has_key(check): set += 1
else: wrong += 1

if set == 5:
correct = 0
i = 0
answers = ["Ketchum", "Bulbasaur", "Azurill", "Shedinja", "Luvdisc"]
while i < 5:
check = omgarray[i]
if form[check].value == answers[i]: correct += 1
i += 1
print "You got %d right." % correct
else:
print "You left %d fields blank." % wrong
]]>


I tested this code out, so it should work for you. Let me know how it goes, and if anything needs explaining.

September 06 02009, 17:22 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Ok, I'm PRETTY SURE I did everything right. I even modified the Python file with the code you provided (I see what you did there, thanks). Page. I think everything's in order... it doesn't work, though. :'[

This is probably because I suck majorly at JavaScript or something. xD

September 06 02009, 17:42 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Okay, I'm afraid I can't find the Javascript included anywhere in the page xD

September 06 02009, 18:09 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Like I said.

I suck at JavaScript.

xD I c/p'd the HTML you supplied, figuring that was the problem, and accidentally replaced the JS, too. Thx.

September 06 02009, 18:31 GMT
SpaceMan
Member

SpaceMan's avatar
Location: Earth
Post count: 32
ca
Actually, I don't know the whole Python CGI API, that's why I don't know has_key is deprecated.

I also made the following quiz script as a practice, I'm going to write a Ruby and Perl one and compare them.
My server supports Ruby, Perl, Python and even ASP.NET 2.

#!/usr/bin/env python 
import cgi;

# header
print "Content-Type: text/html";
print "";

# list of all questions
questions = [
{
"question": "Question 1",
"correct": 1, # NOTE array index, not id
"options": [
"Wrong one",
"Correct one",
"Wrong one"
]
},
{
"question": "Question 2",
"correct": 0,
"options": [
"Correct one",
"Wrong one",
"Wrong one"
]
},
{
"question": "Question 3",
"correct": 1,
"options": [
"Wrong one",
"Correct one",
"Wrong one"
]
},
];

form = cgi.FieldStorage();

if ('submit' in form):
# print results
print "<div>";
print "<ul>";

correct = 0;
unanswered = 0;
wrong = 0;

i = 0;
for question in questions:
# check all questions
print "<li><b>%s</b>:" % question["question"];

# make sure that form field exists
try:
answer = form["radio%s" % i].value;
except KeyError:
answer = '-';

# result
if (answer == "%d" % question["correct"]):
print " <span style='color:green'>Correct.</span>";
correct += 1;
elif (answer == "-"):
print " <span style='color:orange'>Unanswered.</span>";
unanswered += 1;
else:
print " <span style='color:red'>Wrong.</span>";
wrong += 1;

print "</li>";
i += 1;
print "</ul>";
print "<p><strong>%d</strong> correct, <strong>%d</strong> wrong, <strong>%d</strong> unanswered, <strong>%d</strong> total</p>" % (correct, wrong, unanswered, i);
print "</div>";

else:
# print form
print "<form action='#' method='post'>";
i = 0;
for question in questions:
print "<fieldset>";
print " <legend id='question%d'>%s</legend>" % (i, cgi.escape(question["question"]));
print " <div>";

# print options
j = 0;
for optionname in question["options"]:
print " <input type='radio' name='radio%d' value='%d' %s/>%s<br />" % (i, j, ["checked='checked' ", ''][not not j], optionname);
j += 1;

print " </div>";
print "</fieldset>";
i += 1;

print "<input type='submit' name='submit' value='Submit' />";
print "</form>";
import cgi;

# header
print "Content-Type: text/html";
print "";

# list of all questions
questions = [
{
"question": "Question 1",
"correct": 1, # NOTE array index, not id
"options": [
"Wrong one",
"Correct one",
"Wrong one"
]
},
{
"question": "Question 2",
"correct": 0,
"options": [
"Correct one",
"Wrong one",
"Wrong one"
]
},
{
"question": "Question 3",
"correct": 1,
"options": [
"Wrong one",
"Correct one",
"Wrong one"
]
},
];

form = cgi.FieldStorage();

if ('submit' in form):
# print results
print "<div>";
print "<ul>";

correct = 0;
unanswered = 0;
wrong = 0;

i = 0;
for question in questions:
# check all questions
print "<li><b>%s</b>:" % question["question"];

# make sure that form field exists
try:
answer = form["radio%s" % i].value;
except KeyError:
answer = '-';

# result
if (answer == "%d" % question["correct"]):
print " <span style='color:green'>Correct.</span>";
correct += 1;
elif (answer == "-"):
print " <span style='color:orange'>Unanswered.</span>";
unanswered += 1;
else:
print " <span style='color:red'>Wrong.</span>";
wrong += 1;

print "</li>";
i += 1;
print "</ul>";
print "<p><strong>%d</strong> correct, <strong>%d</strong> wrong, <strong>%d</strong> unanswered, <strong>%d</strong> total</p>" % (correct, wrong, unanswered, i);
print "</div>";

else:
# print form
print "<form action='#' method='post'>";
i = 0;
for question in questions:
print "<fieldset>";
print " <legend id='question%d'>%s</legend>" % (i, cgi.escape(question["question"]));
print " <div>";

# print options
j = 0;
for optionname in question["options"]:
print " <input type='radio' name='radio%d' value='%d' %s/>%s<br />" % (i, j, ["checked='checked' ", ''][not not j], optionname);
j += 1;

print " </div>";
print "</fieldset>";
i += 1;

print "<input type='submit' name='submit' value='Submit' />";
print "</form>";
]]>

September 06 02009, 22:45 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

New problem. We're using MyBB for the forum for now, so the DirectoryIndex thing in the .HTACCESS file messes that up a little. It doesn't seem to recognize index.php as an index. : [

September 06 02009, 23:15 GMT
SpaceMan
Member

SpaceMan's avatar
Location: Earth
Post count: 32
ca
This is a PHP and .htaccess problem, not a Python one, did you reply to a wrong thread? (It almost happened to me several times)

September 06 02009, 23:20 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
He probably did. Just put a new .htaccess into your forum directory with DirectoryIndex index.php in it :)

September 06 02009, 23:24 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

No I didn't xD I figured that it pertained to the topic, since I created the topic with the same site in mind. : o

Thanks guys. ^-^

September 07 02009, 00:23 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
That type of syntactical reference is found in the manual, actually. That also goes for everything else. I didn't ever have to ask anybody else for help on why my program was not working, why x function returned None, etc.. The manual had everything I ever needed. Everything else was a simple matter of logic and intelligence.

When it comes to programming, I find that giving people answers directly is just going to make them even more reluctant to actually use real sources of help and basically ask the same "can you do this for me?" questions.
______________________________
FHQ


[<] [1]



Forum Information
  Currently Active Members [detailed] (0 members and ? guests)
-
Forum Statistics
Topics: 0, Posts: 0, Members: 108.
Welcome to our newest member, adamthephantump
Most members online was 5, on August 28 2009, at 21:49:28.
Legend
    Forums with unread topics in them are indicated by a strong yellow colouring around the forum icon.
    Forums with no unread topics have the standard pale yellow colouring around the forum icon.
    Forums with a blue arrow icon will redirect you to a non-forum page.
    Locked forums have a little padlock by their icon. You won't be able to post in these forums.
Shinyshell Home | Contact | Staff List | Archive | Top 

Conventional Login

Don't have an account? You may want to create one.

OpenID Login
OpenID login and registration is usable, but not finished.
What is OpenID?
Search

(advanced search)
Site Stats
  Total members: 108
  Latest member: adamthephantump
  Members currently online: 0
  Most online: 5 - Aug 28, 2009 (21:49)
  Front page hits: 88100
Developer info
  Site version: 3.5 Alpha
  16 queries - 9 templates
Under the Spotlight
Collide Site
Collide make fabulously dreamy electronic-industrial music, they're one of my favourite bands! Give them a chance to take control of your life - myspace | youtube - "Euphoria".

Collide Site - Hits: 4919

5/5 (2) | Rate this site?