私は何かを探す場合はほとんどシーケンシャル処理で正規表現でさがす。
あつかうデータがいろいろでフォーマットも不明な場合が多いからだ。
でもDBがあるなら、キーで検索すれば瞬時に見つかる。
検索フォーム
<!DOCTYPE html> <html> <head> <title>dbq</title> </head> <body> <form action="/cgi-bin/dbq.py" method="POST"> <input type="text" name="text" value="id" /> <input type="submit" name="submit" /> </form> </body> </html>検索cgi
dbq.py
#!/usr/bin/python
import cgi
import psycopg2
import psycopg2.extras
import os
path = "localhost"
port = "5432"
dbname = "monqy"
user = "postgres"
password = "hogehoge"
pg_params = "host={} port={} dbname={} user={} password={}"
pg_params = pg_params.format(path,port,dbname,user,password)
connection = psycopg2.connect(pg_params)
cur = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
html_body = """
<!DOCTYPE html>
<html>
<head>
<title>your query</title>
<style>
h1 {
font-size: 3em;
}
</style>
</head>
<body>
<h1>%s</h1>
</body>
</html>
"""
form = cgi.FieldStorage()
qtext = form.getvalue('text','')
cur.execute('SELECT * FROM Users WHERE id = %s', (qtext,))
results = cur.fetchone()
if results is None:
text = "not found"
else:
text = results['name']
cur.close
connection.close
print(html_body % (text))
テーブル users から、idというフィールドが検索文字列と一致するレコードを探し、
一致しなければ「not found」、一致すればそのレコードの name フィールドを表示する。
単純な動作なのでフォームや実行結果を表示するまでもないでしょう。
このテーブルはid がkeyであり重複するレコードはないので fetchoneを使っている。
「レコードが見つからない場合」をどう書くのか、少し探した。見つからない場合に results をそのまま表示すると「None」となることはわかったのだが、
results eq None
とか
results == "None"
ではダメで、
正しくは
results is None
であった。