文章导航
前文讲到数据爬到了,这节讲编写api接口,我们需要以下俩接口
| 标题 | 名称 | 介绍 |
|---|---|---|
| /api/data | 搜索列表接口 | 用于搜索资源,带分页 |
| /api/data/detail | 资源详情接口 | 查询资源详情 |
爬到的数据编写成api接口,爬虫的时候用了python,干脆服务端也用python, 装个flask来用
pip install flask
MantiSerach兼容mysql语法,编写起查询语句相当方便 ch兼容mysql语法,编写起查询语句相当方便
编写列表接口
#api.py
#访问mantiSearch接口
def postToManti(match_contnet,offset,page_size):
url = "http://localhost:9308/sql"
headers = {
'Content-Type': 'application/json'
}
data = {
"mode": "raw",
"query": f"select * from resource_item where match('{match_contnet}') limit {page_size} offset {offset}"
}
print(data)
response = requests.post(url, headers=headers, data=data)
print(response.text)
return response.text
#api控制器,列表查询接口
@app.route('/api/data', methods=['GET'])
def get_data():
page = int(request.args.get('page', 1)) # 默认为第一页
page_size = int(request.args.get('page_size', 10)) # 默认每页10条数据
start = (page - 1) * page_size
end = start + page_size
paginated_data = postToManti(start,page_size)
res =json.loads(paginated_data) [0]
k=0
for item in res['data']:
res['data'][k]['id'] = str(item['id'])
k = k+1
return jsonify(res)
if __name__ == '__main__':
#允许跨域
CORS(app)
app.run(debug=True,port=8634, host="0.0.0.0")
运行
python api.py
详情接口
#获取详情信息
def postDetail(id):
url = "http://localhost:9308/sql"
headers = {
'Content-Type': 'application/json'
}
data = {
"mode": "raw",
"query": f"select * from resource_item where id={id}"
}
response = requests.post(url, headers=headers, data=data)
return response.text
#详情接口
@app.route('/api/data/detail', methods=['GET'])
def get_detail():
id = int(request.args.get('id', '') ) # 默认每页10条数据
paginated_data = postDetail(id)
res =json.loads(paginated_data) [0]
k=0
for item in res['data']:
res['data'][k]['id'] = str(item['id'])
k =k+1
res['total'] = getCount()
return jsonify(res)
浏览器访问{服务器ip}/api/data?page=1&page_size=10,就可以查到manti_search里的数据了