Shinyshell Community Forums > Coding >
Python General Questions


[1] [>]


August 28 02009, 22:03 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Okay! So I want to code a site in Python as opposed to PHP (which I'm used to). I want to write an include script, like I use in PHP.

Faltzer told me I should use the Mako Templating system. I don't understand it at all. I just figured I'd use regular Python t-t. I'd have to import cgi so I've heard, which I don't understand. How do I end the CGI framework-thing?

I'm confused xD

August 28 02009, 22:16 GMT
Pikachu
Kelp is good!

Pikachu's avatar
Location: California
Post count: 50
us
Well, you can do a template system, or you can do something electron taught me when I asked him about includes in Python.

First create a file that will store the stuff you want to include. Put the stuff in a variable.
words = "<b>These are words</b>" 
words = "<b>These are words</b>"
]]>

Say you place this file called includes.py into a folder called stuff. Also in this folder, create a file called __init__.py. Leave this empty. Just create it, no need to chmod.

Now create the page you wish to include stuff in. This file is called whatever you want to call it:
#!/usr/bin/python 

import stuff.includes

print "Content-type: text/html\n"
print stuff.includes.words
#!/usr/bin/python

import stuff.includes

print "Content-type: text/html\n"
print stuff.includes.words
]]>

This file needs to be chmod and with Unix line endings.

What does this output? These are words.

Hope this helped. And electron, if I did anything wrong, please correct me.



______________________________

Linux | Chrome | Python | Chuck

August 28 02009, 22:40 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Okay, Pikachu did a great job explaining how to do something similar to an include in Python. Python doesn't have includes per se, but it does have modules, and that's what Pikachu demonstrated.

So, essentially you can store your whole layout in separate variables in your include.py (or whatever other name you can think of) and print them out when you please. Also, you can't multi line strings in Python as you can in PHP:

# wrong! 
layout = "<html>
<head><title>Title</title></head>
<body>
Hello!
</body>
</html>"
# wrong!
layout = "<html>
<head><title>Title</title></head>
<body>
Hello!
</body>
</html>"
]]>


Normal strings can only go one line (you have to put backslashes at the end of each line if you want to multi-line), but you can use triple-quoted strings, which can stretch as many lines as you want:

# works fine 
layout = """
Yay

as many

lines



as you want! :)
"""
# works fine
layout = """
Yay

as many

lines



as you want! :)
"""
]]>


So by using these two techniques, you can build a simple site. It's not as easy as PHP, but remember Python isn't just a Server-Side language, unlike PHP.

Using a templating system or a framework can make life easier for you. I didn't want to, so I wrote my own "mini-framework" by grouping functions and classes I developed over time. It becomes easier to connect to a database, and do other initially complicated and long-winded stuff.

August 28 02009, 23:19 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

I have done it like so:

f = open('html.html') 
print f.read();
f = open('html.html')
print f.read();
]]>


And it worked?

Also, I don't know how to use import with CGI? ?_?

August 28 02009, 23:46 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Of course, you can do it like that if you want. You can also store the html in a database.

Hmm, not sure what you mean about CGI. Importing the CGI module is dead easy:

import cgi 


The cgi module has a number of different functions you can use, including something similar to htmlspecialchars(), and FieldStorage, which lets you access POST and GET variables. Is that what you were referring to?

August 30 02009, 19:53 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Also, how do I make index.py the default file? See example.

August 30 02009, 20:53 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
Add this into a .htaccess file:

DirectoryIndex index.py

That directory and any sub directories will use index.py as the index page.

September 02 02009, 21:22 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

How do you use MySQL in Python? I recall there being a topic containing a reference to a MySQL/Python library, but I can't seem to find it now. :[ Thanks guys : D

September 03 02009, 20:47 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Bump and bump.

September 03 02009, 22:42 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
We've got two pages of threads now. The one you're looking for was on page two :D

http://shinyshell.net/community/topic?id=14

September 04 02009, 21:07 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Thanks : D

I was just wondering... well, I've never done any forms with AJAX before. I was kind of wanting to try it. The biggest thing I didn't understand was the whole 'return' thing. . Also, how do you get the returned information from the Python script back into the JavaScript stuff? @_@

September 04 02009, 22:26 GMT
Pikachu
Kelp is good!

Pikachu's avatar
Location: California
Post count: 50
us
Wait, did Peter just magically become a moderator? Not that I don't want him to be one, of course. Just wanted to know how it happened.

Edit by Peter: How am I a moderator?
______________________________

Linux | Chrome | Python | Chuck

September 05 02009, 09:32 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
:) Nick, Navarr and yourself were pseudorandomly selected by the governing board of Shiny Shell (consisting of me and no one else) and promoted to staff ranks without being asked. Since you don't really have any responsibilities, I thought that was okay to do, but if anyone's uncomfortable with it demotions can be arranged. Lol, so it's not a mistake.

Oh, heh, AJAX is really easy. What it really does is send a request to your Python script (as you would do when you open it in your browser). The response doesn't come immediately, as data has to be transferred. Once the state is 4, it's complete, and JavaScript has already received the full content of your page. There's nothing you really need to worry about more.

You can use "the old fashioned way" or you can use AJAX functions and objects provided by libraries and frameworks like mootools, jquery, etc. I used to always use the old fashioned way, but these libraries really simplify your scripting (and, hence, life).

For the sake of understanding how it works, here's how to do it without using any libraries:

// 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", "ajax.py", true);
req.send(null);
// 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", "ajax.py", true);
req.send(null);
]]>


A callback is a name for a function that get called by some other function (usually multiple times). In this case, process_req_change should be the name of a function that you have in your code (above the part where you try to assign it, or it'll cause an error). We'll take a look at how to write that sort of function in a bit.

That code sends a HTTP GET request to ajax.py. You can also send POST requests with data, but that's slightly more complicated so we'll not do that right now. Onto process_req_change!

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;
alert(response);
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}
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;
alert(response);
}
// it's an error otherwise
else
{
alert("Problem retrieving data by AJAX.");
}
}
}
]]>


In this case, the data returned by the server was text, not XML (you can also return XML and then get the data inside it and load it into a page, but that's slightly more difficult)

So basically we're just alerting the user with that data. You would probably like to put it into the page somewhere, so just use the innerHTML of a page element and put it there.

And that's about it. W3C has some good tutorials on AJAX, so you can find more complex examples there. I'm not sure what exactly you were referring to with the whole "return" thing.

September 05 02009, 09:56 GMT
Nick^
merciful justice

Nick's avatar
Location: Brisbane, Australia
Post count: 78
au
Thank you for the moderator thing.

Anywho, I'm looking forward to experimenting with AJAX with Lazurane, and this basic tutorial is definitely a start! :D
______________________________
Lazurane

September 05 02009, 15:48 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

1) Yes, thank you also for the pseudo part of the random selection. :P

By return, I mean... Well, I send the form info to the Python file. It's a five question quiz, so I have to know which questions are correct and which aren't. This means that the information has to be returned from the Python, right? ?_?

I really liked your explanation, though, of AJAX. It's very clear. ^-^

2) I've found another issue.

#!/usr/bin/python 

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

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

i = 0

omgarray = ["1", "2", "3", "4", "5"]

while i < 5:
check = "q" + omgarray[i]
if form.has_key[check]:
print "yay <br />"
i= i + 1
else:
print "poop"
#!/usr/bin/python

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

import cgi
import cgitb
cgitb.enable()

form = cgi.FieldStorage()

i = 0

omgarray = ["1", "2", "3", "4", "5"]

while i < 5:
check = "q" + omgarray[i]
if form.has_key[check]:
print "yay <br />"
i= i + 1
else:
print "poop"

]]>


http://islanddocks.aiirodesign.com/quiz1.py

I'm trying to check five form parts at once, called q1, q2, q3, q4, and q5. I just thought a while loop would be easier. ^-^

September 05 02009, 18:52 GMT
SpaceMan
Member

SpaceMan's avatar
Location: Earth
Post count: 32
ca
form.has_key is a typo, it should be form.has_key(check)

September 05 02009, 19:22 GMT
Peter*
A Pythonic One

Peter's avatar
Location: US
Post count: 99

Thanks, SpaceMan... I blame PHP for that one, haha.

September 06 02009, 00:44 GMT
Faltzer
Member

Faltzer's avatar
Location: Glendale, New York
Post count: 38
us
For this sort of stuff, you should use a framework, not the cgi module. CGI scripts grow overly complex very quickly. Juno or Pylons are alright. The former is fine for what you want to accomplish. There is nothing wrong with using a framework. You'll learn how to actually structure your code, and it'll emphasize even more the idea of code reuse. The above posts don't seem to emphasize that at all. Just ad-hoc methods analogous to PHP "programmers." :)

Electron is making a "mini-framework", but there are already so many good web frameworks out there, like Pylons (which I just mentioned,) that makes his fit the YAWF acronym. Don't do that; don't reinvent the wheel. There are good solutions (modules) out there for just about everything in Python. If x module missing something, then submit a patch for it so it can improve. People aren't going to do everything for you.

I hear this all of the time: "I won't use every feature in library, so I'll just go ahead and make my own with the functions that I will use." The simple solution is just use what you need. It's still astoundingly useful to have extra functionality lying around if you ever DO need it. Incidentally, speaking of text editing, I had about the same attitude when I tried Vim; I learned enough to move around and type and that was about it. But I kept finding more advanced things I wanted to do, went off to learn how to do them efficiently, and now I'm a Vim ninja. A Vimja, if you will.

.has_key() is deprecated, use 'key in dict'

imports should be done at the top of the file.

Concatenating is slow. Whenever possible, try using string formatting.

''.join('q', omgarray) is better than using the concatenation operator.

Using docstrings to store "content" when there are better solutions is just ignorance and stupidity on everyones part here, and they should feel ashamed for suggesting such STUPID methods when templating systems exist for this very reason.

Use Mako. Besides being excellent, it also has bindings to the actual language, so you don't need to learn a completely new formatting language.

If you guys are going to use Python, then memorize the fact that Python is not PHP. The general idea is that if it can be done in PHP, it can't or shouldn't be done in Python. It's for good reason. We don't baby you through programming like they did. You code like scrubs.

______________________________
FHQ

September 06 02009, 00:57 GMT
lec**
Supra stultitiam

lec's avatar
Location: Varaždin, Croatia
Post count: 173
hr
I personally dislike Mako. I reckon templates are neater if they don't have embedded Python code. There are a lot of crap "frameworks" for Python, including Pylons and the heavyweight champion Django. Mako's another not-so neat idea, but probably acceptable if you've strapped for time, and have not got your own code.


[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: 87937
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: 4479

5/5 (2) | Rate this site?