装完apache,打通网路之后,基本就可以写python cgi了。Apache会用python去执行目标脚本显示在页面上。这篇主要记录一下环境里面的基本要点。
#!/usr/bin/env python #前面这段#!必须要,是在告诉apache用python执行改文件
#把用户组和用户改为www, 整个cgi-bin的权限去到775
#目前server的cgi脚本都放在/usr/lib/cgi-bin里面。
import cgi
form = cgi.FieldStorage()
name = form.getvalue('name','world')
print """Content-type: text/html
<html>
<head>
<title>Greeting Page</title>
</head>
<body>
<h1>Hello, %s!</h1>
<form action='simple3.cgi'>
Change name <input type='text' name='name' />
<input type='submit' />
</form>
</body>
</html>
""" % name
后面这部分主要也是为了突出一个python句式,为了postgres的基设再开一篇有点太啰嗦了。
try else:
#!/usr/bin/env python
print 'Content-type: text/html\n'
import cgitb;cgitb.enable()
import psycopg2 as psycopg
conn = psycopg.connect('dbname=**** user=**** password=****’)
curs = conn.cursor()
print """
<html>
<head>
<title>The FooBar Bulletin Board</title>
</head>
<body>
<h1>The FooBar Bulletin Board</h1>
"""
curs.execute('SELECT * FROM messages')
names = [d[0] for d in curs.description]
rows = [dict(zip(names,row)) for row in curs.fetchall()]
toplevel = []
children = {}
for row in rows:
parent_id = row['reply_to']
if parent_id is None:
toplevel.append(row)
else:
children.setdefault(parent_id,[]).append(row)
def format(row):
print row['subject']
try:kids = children[row['id']] #Try完之后没有exception它会去else
except KeyError: pass
else:
print 'testing'
print '<blockquote>'
for kid in kids:
format(kid)
print '</blockquote>'
print '<p>'
for row in toplevel:
format(row)
print """
</p>
</body>
</html>
"""