用falsk写一个简单的接口,这个接口的数据本来是爬虫爬取的数据,但是今天只写一个flask接口,数据就用测试数据好了。
import random
import re
import time
import requests
import flask,json
from flask import request
server = flask.Flask(__name__)
@server.route('/accessoriesName',methods = ['get','post'])
def reg():
dict = {}
data = json.loads(request.get_data())
print(data)
vehicle_model = data.get('vehicle_model')
vehicle_parts = data.get('vehicle_parts')
parts = vehicle_parts.split(',')
dic = {}
for part in parts:
price1 = random.randint(31, 300)
price2 = random.randint(31, 300)# time.sleep(25)
part1 = part.split(' ')[0].split('(')[0]
dic[part1] = {"taobao": price1, "jingd": price2}
return json.dumps(dic, ensure_ascii=False)
#端口号用0.0.0.0,表示局域网和外网都可以访问。
server.run(port = 6100,debug = True,host = '0.0.0.0',threaded = True)
这个是服务器端,是一个简单的web服务器。
我们再写一个调用接口的应用端
import json
import requests
# 'url': 'http://111.230.203.153:1680/accessoriesName',
#ip是公网ip哦,不是本机ip,6120是端口号
CONFIG = {'url': 'http://111.230.203.153:6100/accessoriesName' }
url = CONFIG['url']
data = json.dumps({"vehicle_model":"北京现代","vehicle_code":"Cx4",'vehicle_parts':"前叶子板",'vehicle_price':'266'})
print(data)
response = requests.post(url=url, data=data, timeout=40)
print(response.status_code, response.text)