连接 mongodb 数据库方法:

1
2
3
4
5
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
client.database(用户名对应的数据库名称).authenticate("user","password")
print('连接数据库成功')
users = client.oneDB.users(client.数据库.表名)

数据库操 pip

1
2
3
4
5
6
7
8
# 定义json对象
post = {
"name": name,
"hex": hex,
"style": style
}
# 使用数据库操作命令操作表
users.insert_one(post)

打印数据库中存储字段方法:

1
2
3
import pprint
for user in users.find():
pprint.pprint(user)

抓取网页:

1
2
3
4
5
6
import requests
from bs4 import BeautifulSoup
url = "http://html-color-codes.info/color-names/"
hdrs = {'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'}
r = requests.get(url, headers=hdrs)
soup = BeautifulSoup(r.content)

通过 class 名获取标签的方法:

  1. 如果获取的结果是数组(tds=[]),需要先转换成字符串 string = ‘’.join(str(i) for i in tds)
  2. 通过方法 soup=BeautifulSoup(string)
  3. soup.find_all(attrs={‘class’,’demo’})即可找到所有 class 名为 demo 的标签

flask 写后台接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# coding=utf-8
# mongo.py
from flask import Flask,abort
from flask import jsonify
from flask import request
# from flask_pymongo import PyMongo
from pymongo import MongoClient

app = Flask(__name__)

client = MongoClient("mongodb://localhost:27017/")
client.myblog.authenticate("user","password")
database = client["myblog"]
collection = database["article"]

query = {}

# app.config['MONGO_DBNAME'] = 'myblog'
# app.config['MONGO_URI'] = 'mongodb://localhost:27017/myblog'
# 如果部署在本上,其中ip地址可填127.0.0.1
#
# mongo = PyMongo(app)

@app.route('/login', methods=['GET'])
def get_all_users():
star = collection.find(query)
output = []
for s in star:
output.append({'name' : s['name']})
return jsonify({'result' : output})

@app.route('/register', methods=['POST'])
def add_user():
star = mongo.db.userInfo
name = request.json['name']
pwd = request.json['pwd']
star_id = star.insert({'name': name, 'pwd': pwd})
new_star = star.find_one({'_id': star_id })
output = {'name' : new_star['name'], 'pwd' : new_star['pwd']}
return jsonify({'result' : output})

@app.route('/modify/<string:name>', methods=['PUT'])
def update_user(name):
user = mongo.db.userInfo.find({"name":name})
output = []
for s in user:
output.append({'name': s['name'], 'pwd': s['pwd']})
if len(output) == 0:
abort(404)
mongo.db.userInfo.update({"name":name},{'$set':{"name":"LZ111"}})
return jsonify({'result': output})

@app.route('/delete/<string:name>', methods=['DELETE'])
def delete_user(name):
user = mongo.db.userInfo.find({"name": name})
output = []
for s in user:
output.append({'name': s['name'], 'pwd': s['pwd']})
if len(output) == 0:
abort(404)
mongo.db.userInfo.remove({'name': name})
return jsonify({'result': True})

if __name__ == '__main__':
# app.run(host = '0.0.0.0', port = 80, debug = True)
app.run()