效果图
## 实现过程
1.搭建好CGI的运行环境,Linux服务器配置好python的环境(一般默认安装好了python2),我用的是python3.6,所以手动配置了pythoon3,下面的源码是python3的,除此之外,还需要配置容器去存放程序,我这里用的是tomcat,需要手动去开启支持cgi编程,这里不做详细介绍,当然和windows一样,你连接数据库需要用到第三方库,所以在服务器上要安装这些需要的库(要求对Linux比较熟悉)。配置好环境后,我们来看看代码部分,以下是源码。
源码
负责连接数据库并展示,前端的随便写一个表单提交就好了(不展示)
#!/bin/python3
# -*- encoding: UTF-8 -*-
import time
import cgi
import sys
import codecs
#防止中文乱码
sys.stdout = codecs.getwriter("gbk")(sys.stdout.detach())
import mysql.connector
class note():
def __init__(self):
self.text=''
self.date=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
self.db=mysql.connector.connect(
host="",#你的主机号
user='',#用户名
passwd='',#密码
database=''#数据库名字
)
def getCursor(self):
self.mycurdor=self.db.cursor()
return self.mycurdor
def execute(self,sql):
self.getCursor().execute(sql)
self.close()
def close(self):
self.mycurdor.close()
def save(self,pub_con):
sql = 'insert into notebook(pub_con,pub_time) values("%s","%s")'
info = (pub_con,self.date)
self.execute(sql % info)
self.db.commit()
self.close()
def getText(self,id):
sql="select * from notebook where id={}".format(id)
self.getCursor().execute(sql)
res =self.mycurdor.fetchall()
self.mycurdor.close()
return res
def show(self,id):
res = self.getText(id)
if res:
print("<h1 style='text-align:center;color:blue;font-size:24px;font-fimaly:黑体;'>留言内容</h1>")
print("<ul style='text-align:left;color:white;font-size:18pxfont-fimaly:楷体;'>")
print('<li style="list-style: none;">留言编号:', res[0][0], '</li>')
print('<li style="list-style: none;">留言内容:', res[0][1], '</li>')
print('<li style="list-style: none;">留言时间:', res[0][2], '</li>')
print("</ul>")
else:
print("该留言不存在!")
form=cgi.FieldStorage()
a=form.getvalue('a')
b=form.getvalue('b')
notebook=note()
print('Content:text/html\n\n')
print('<!DOCTYPE html>')
print('<html>')
print('<head>')
print('<title>Internet-NoteBook-Show</title>')
print('</head>')
print('<body style="width: 100%;height: 100%;margin: auto;text-align: center;justify-content: center;background-color:pink;background-repeat: no-repeat;background-size: cover;margin: 0 auto;">')
if a!=None:
notebook.save(a)
print("<h1 style='text-align:center;color:blue;font-size:24px;font-fimaly:黑体;'>留言成功</h1>")
print("<ul style='text-align:left;color:white;font-size:18pxfont-fimaly:楷体;'>")
print('<li style="list-style: none;">留言内容:',a, '</li>')
print('<li style="list-style: none;">留言时间:', notebook.date, '</li>')
print("</ul>")
elif b!=None:
notebook.show(b)
print("<button><a href='/test/notebook.html'>返回</a></button>")
print('</body>')
print('</html>')
notebook.db.close()