# 用Python 简单访问 MongoDB
# server.py
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8000
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
# index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a href="add.html">用户添加</a>
</body>
</html>
# add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>添加页面</title>
</head>
<body>
<form action="/cgi-bin/add.py" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
邮箱:<input type="text" name="email"><br>
性别:<input type="radio" name="sex" value="0" checked>女
<input type="radio" name="sex" value="1">男<br>
<br>
<button>添加</button>
</form>
</body>
</html>
# add.py
#!/usr/bin/python3
import cgi,cgitb,pymongo
cgitb.enable()
print("Content-Type: text/html;charset=utf-8") # HTML is following
print() # blank line, end of headers
# 接收数据
fs = cgi.FieldStorage()
data = {}
for key in fs.keys():
data[key] = fs[key].value
# print(data)
#链接到 127.0.0.1 的mongo
client = pymongo.MongoClient('127.0.0.1', 27017)
#选择test库
db = client.py7
# print(db)
# 执行添加
db.user.insert(data)
print('<script>location.href="/cgi-bin/index.py"</script>')
#!/usr/bin/python3
import cgi,cgitb,pymongo
cgitb.enable()
print("Content-Type: text/html;charset=utf-8") # HTML is following
print() # blank line, end of headers
# print(data)
#链接到 127.0.0.1 的mongo
client = pymongo.MongoClient('127.0.0.1', 27017)
#选择test库
db = client.py7
# print(db)
trs = ''
# 查询出所有的用户的key
res = db.user.find()
for x in res:
# 循环读取用户信息
if x['sex'] == '0':
sex = '女'
else:
sex = '男'
print(x['username'])
# print(sex)
trs += '''
<tr>
<td>{uname}</td>
<td>{upass}</td>
<td>{uemail}</td>
<td>{usex}</td>
<td>
<a href="/cgi-bin/del.py?uid={uid}">删除</a>
<a href="/cgi-bin/edit.py?uid={uid}">编辑</a>
</td>
</tr>
'''.format(uid=x['_id'],uname=x['username'],upass=x['password'],uemail=x['email'],usex=sex)
html = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>用户列表</title>
</head>
<body>
<a href="/add.html">用户添加</a>
<center>
<table>
<tr>
<th>ID</th>
<th>用户名</th>
<th>密码</th>
<th>邮箱</th>
<th>性别</th>
<th>操作</th>
</tr>
{trs}
</table>
</center>
</body>
</html>
'''.format(trs=trs)
print(html)
from http.server import HTTPServer, CGIHTTPRequestHandler
port = 8000
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
print("Starting simple_httpd on port: " + str(httpd.server_port))
httpd.serve_forever()
兄弟连学python
Python学习交流、资源共享群:563626388 QQ