赞
踩
一、python3写一个http接口服务,给别人调用2--flask
这次选择flask,Flask是一个用于构建web应用程序的Python微框架,是一个轻量级的WSGI web应用程序框架。它的目的是使web入门变得快速和容易,并能够扩展到复杂的应用程序。它最初是一个围绕Werkzeug和Jinja的简单包装器,现在已经成为最流行的Python web应用程序框架之一。简易而且本地win10能够跑起来。
二、Flask的get接口代码实现
1. 安装: pip install flask
2. 代码:
- # -*- coding: UTF-8 -*-
- # !/usr/bin/python
- # @time :2019/10/12 11:11
- # @author :Mo
- # @function :service of flask
-
-
- from flask import Flask, request, jsonify
-
- app = Flask(__name__)
-
-
- @app.route('/add', methods=["GET", "POST"])
- def calculate():
- if request.method == 'GET':
- params = request.args
- else:
- params = request.form if request.form else request.json
- a = params.get("a", 0)
- b = params.get("b", 0)
- c = int(a) + int(b)
- res = {"result": c}
- return jsonify(content_type='application/json;charset=utf-8',
- reason='success',
- charset='utf-8',
- status='200',
- content=res)
-
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0',
- threaded=True,
- debug=False,
- port=8868)
3. GET接口访问:http://127.0.0.1:8868/add?a=1&b=4
GET 浏览器访问结果1:
GET---postman访问结果2:
4.POSTMAN访问接口 http://127.0.0.1:8868/add
三、Flask的post接口代码实现
1. 代码:
- # -*- coding: UTF-8 -*-
- # !/usr/bin/python
- # @time :2019/10/12 11:11
- # @author :Mo
- # @function :service of flask
-
-
- # flask
- from flask import Flask, request, jsonify
-
- app = Flask(__name__)
-
- @app.route('/add', methods=["POST"])
- def calculate():
- params = request.form if request.form else request.json
- print(params)
- a = params.get("a", 0)
- b = params.get("b", 0)
- c = a + b
- res = {"result": c}
- return jsonify(content_type='application/json;charset=utf-8',
- reason='success',
- charset='utf-8',
- status='200',
- content=res)
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0',
- threaded=True,
- debug=True,
- port=8868)
2. 接口访问:http://127.0.0.1:8868/add
postman访问结果:
希望对你有所帮助!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。