web.py+sqlite寫的簡單留言本
阿新 • • 發佈:2019-02-20
程式碼很亂,而且沒有用到模板,把html程式碼跟Python程式碼混在一起了,而且也沒有用到web.py本身提供的資料庫操作模組,絕對粗超的程式碼!
學習了很多東西,首先當然是web.py,然後是sqlite,接下來是time模組——看來也唯有不斷的實踐,才真正能進步!
說實在的,偶學html到現在這麼久,還是半桶水,悲劇了!
01 #!/usr/bin/env python
02 #coding=utf-8
03
04 import os,web,time
05 import sqlite3 as db
06
07 urls = (
08 '/', 'hello',
09 '/add','add'
10 )
11
12 class hello:
13 def GET(self):
14 #例項化sqldb,然後獲取內容
15 s = ""
16 sdb = sqldb()
17 rec = sdb.cu.execute("""select * from msgs""")
18 dbre = sdb.cu.fetchall()
19 for i in dbre:
20 s = "<p>"+i[2]+" <span style=/"color: blue
21
22 sh = """
23 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
24 <HEAD><meta http-equiv="X-UA-Compatible" content="IE=8" />
25 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
26 <TITLE> OK!</TITLE> </HEAD> <BODY><h1>Hello World!</h1>
27 """
28 sb = """
29 <h2>add a note</h2>
30 <form method="post" action="/add">
31 UserName:<INPUT TYPE="text" NAME="uname"><br />
32 <textarea name="content" ROWS="20" COLS="60"></textarea><br />
33 <button type="submit">save</button></form></BODY></HTML>
34 """
35 s = sh + s + sb
36 return s
37
38 class add:
39 def POST(self):
40 i = web.input('content')
41 n = web.input('uname')
42 date = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
43 sdb = sqldb()
44 rec = sdb.cu.execute("""select * from msgs""")
45 dbre = sdb.cu.fetchall()
46 for k in dbre:
47 j = k[0]+1
48 t = (j,n.uname,date,i.content)
49 sdb.cu.execute('insert into msgs values(?,?,?,?)',t)
50 sdb.conn.commit()
51 return web.seeother('/')
52
53 def GET(self):
54 return web.seeother('/')
55
56 class sqldb:
57 #先驗證資料庫是否存在
58 def __init__(self):
59 if os.path.exists("msg.db"):
60 #如果資料庫存在,就直接連線
61 self.conn = db.connect("msg.db")
62 self.cu = self.conn.cursor()
63 else:
64 #如果資料庫不存在,連線,並生成表
65 self.conn = db.connect("msg.db")
66 self.cu = self.conn.cursor()
67 self.cu.execute("""create table msgs(
68 id integer primary key,
69 name text,
70 date text,
71 content text) """)
72 self.cu.execute("""insert into msgs values(1,'Ahai','2010-05-19 15:11:20','Ahi alaws be ok!')""")
73 self.conn.commit()
74
75 if __name__=="__main__":
76
77 app = web.application(urls,globals())
78 app.run()