Last active
July 24, 2017 05:24
-
-
Save wannaphong/e99a92becc8a28c7bdfc69db58e32f6d to your computer and use it in GitHub Desktop.
ระบบบันทึกผู้เยี่ยมชมอย่างง่าย เขียนโดย นาย วรรณพงษ์ ภัททิยไพบูลย์ https://python3.wannaphong.com/2017/07/สร้างเว็บด้วย-bottle-ตอนที่-3.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from bottle import route, run, template,get, post, request | |
import csv | |
import codecs | |
@route('/') | |
def home(): | |
return ''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>บันทึกผู้มาเยี่ยมชม</title> | |
</head> | |
<body> | |
<h1>บันทึกผู้มาเยี่ยมชม</h1></br> | |
<h2><a href="/view">อ่านบันทึก</a><br> | |
<a href="/write">เขียนบันทึก</a></h2> | |
</body> | |
</html> | |
''' | |
@get('/write') | |
def write(): | |
return ''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>เขียน : บันทึกผู้มาเยี่ยมชม</title> | |
</head> | |
<body> | |
<h1>เขียน : บันทึกผู้มาเยี่ยมชม</h1></br> | |
<h2>เขียนบันทึก</h2><br> | |
<form action="/write" method="post"> | |
ชื่อ : <input type="text" name="user"> | |
ข้อความ :<textarea name="text"> | |
</textarea> | |
<input type="submit"> | |
</form> | |
</body> | |
</html> | |
''' | |
@post('/write') | |
def do_write(): | |
username = request.forms.user | |
text = request.forms.text | |
with codecs.open('data.csv', 'a+', encoding='utf-8') as csvfile: | |
writer = csv.writer(csvfile) #ใช้คำสั่ง csv.writer และเขียนข้อมูลไฟล์ใหม่ด้วยโหมด w+ | |
writer.writerow((username,text)) | |
csvfile.close() | |
return 'OK' | |
@route('/view') | |
def viewpages(): | |
dataall='' | |
try: | |
with codecs.open('data.csv','r', encoding='utf-8') as csvfile: | |
data= csv.reader(csvfile) | |
for row in data: | |
dataall+='<b>ข้อความ</b>:'+row[1]+'<br><b>จาก</b> : คุณ '+row[0]+'<hr><br>' | |
csvfile.close() | |
except: | |
dataall='ยังไม่มีข้อมูล' | |
return ''' | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>อ่าน : บันทึกผู้มาเยี่ยมชม</title> | |
</head> | |
<body> | |
<h1>อ่าน : บันทึกผู้มาเยี่ยมชม</h1></br> | |
'''+dataall+'</body></html>' | |
run(host='localhost', port=8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment