-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.py
83 lines (74 loc) · 2.73 KB
/
server.py
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: UTF-8 -*-
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
from bson import json_util
from bson.objectid import ObjectId
import json
import pymongo
conn = pymongo.MongoClient('localhost', 27017)
db = conn['taobao']
goods_coll = db['goods']
cate_coll = db['categories']
app = Flask(__name__)
def toJson(data):
return json.dumps(
data,
default=json_util.default,
ensure_ascii=False
)
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.route('/', methods=['GET'])
def index():
if request.method == 'GET':
total = goods_coll.count()
return render_template('index.html', total=total)
#if request.form['key']:
# key = request.form['key']
# return redirect(url_for('get_goods', key=key, page=1))
@app.route('/categories', methods=['GET'])
def categories():
if request.method == 'GET':
cates = cate_coll.aggregate([
{'$project': {'_id': 0,
'id': {'$slice': ['$categories.catid',1,1]},
'name': {'$slice': ['$categories.name',1,1]},
'sub': {'$slice': ['$categories',2,1]}}},
{'$unwind': '$id'}, {'$unwind': '$name'}, {'$unwind': '$sub'},
{'$group': {'_id': '$id',
'catid': {'$first': '$id'},
'name': {'$first': '$name'},
'subs': {'$addToSet': '$sub'}}}
])
return render_template('categories.html', cates=cates)
@app.route('/search', methods=['GET'])
@app.route('/search/<item>', methods=['GET'])
def get_goods(item=None):
if request.method == 'GET':
page = request.args.get('page', 1, type=int)
limit = request.args.get('limit', 60, type=int)
p = (page - 1) * limit
offset = request.args.get('offset', p, type=int)
catid = request.args.get('catid', None, type=str)
jsons = request.args.get('json', 'off')
keyword = request.args.get('key', '')
if not keyword:
keyword = item
if catid:
cursor = goods_coll.find({'categories.catid': catid})
else:
cursor = goods_coll.find({'title': {'$regex': keyword} })
#total = cursor.count()
#flash('已查询到 %d 个结果.'%total)
results = cursor.skip(offset).limit(limit)
resultList = []
for result in results:
resultList.append(result)
if jsons == 'off':
return render_template('search.html', entries=resultList)
else:
return toJson(resultList)
if __name__ == '__main__':
#app.run(host='0.0.0.0')
app.run(debug=True)