AIP是非常常用的,flask 又是搭建很简单的,用flask 快速搭建一个API
安装 Flask
pip install Flask
导入Flask模块
编写WEB flask
from flask import Flask,jsonifyapp = Flask(__name__)@app.route('/')def hello_world(): # put application's code here return 'Hello World!'if __name__ == '__main__': app.run(debug=True)
定义API
@app.route('/api', methods=['POST'])def home(): T = random.randint(11, 30) H = random.randint(50, 80) date_time = datetime.datetime.now() HongKong = random.randint(5, 20) GuangZhou = random.randint(5, 20) datas = [ { 'id': 1, 'T': T, 'H': H, "Time": 2, }, ] return jsonify({'datas': datas})
跨域
CORS(app, supports_credentials=True)
如果有中文
app.config['JSON_AS_ASCII'] = False
完整代码
from flask import Flask,jsonifyapp = Flask(__name__)CORS(app, supports_credentials=True)app.config['JSON_AS_ASCII'] = False@app.route('/')def hello_world(): # put application's code here return 'Hello World!'@app.route('/api', methods=['POST'])def home(): datas = [ { 'id': 1, 'T': T, 'H': H, "Time": 2 }, ] return jsonify({'datas': datas})if __name__ == '__main__': app.run(debug=True)
flask_restful- Flask API使用
http://www.pythondoc.com/Flask-RESTful/extending.html
安装flask-restful
pip install Flask-RESTful
导入模块
from flask_restful import Resource, Api
配置AIP应用
app = Flask(__name__)api = Api(app)class HelloWorld(Resource): def get(self): return {'hello': 'world'}api.add_resource(HelloWorld, '/', '/hello')
完整代码
from flask import Flask,jsonifyfrom flask_restful import Resource, Apiapp = Flask(__name__)app.config['JSON_AS_ASCII'] = False@app.route('/')def hello_world(): # put application's code here return 'Hello World!'app = Flask(__name__)api = Api(app)class HelloWorld(Resource): def get(self): return {'hello': 'world'}api.add_resource(HelloWorld, '/', '/hello')if __name__ == '__main__': app.run(debug=True)