python flask 封装属于自己的api

python flask 封装属于自己的api

  • 0x01 demo
  • 0x02 测试
  • 0x03 解决 WARNING: This is a development server. Do not use it in a production deployment. falsk WSGI

0x01 demo

from flask import Flask, jsonify, request

# 创建服务
app = Flask(__name__)

# 指定接口的访问路径,和支持什么请求方式get,post
@app.route('/hello',methods=['get','post'])
def hello():
    people = request.args.get('people')
    return f"hello:\t{people}"

@app.route('/hi',methods=['get'])
def hi():
    people = request.args.get('people')
    age = request.args.get('age')
    data = {}
    data['age'] = age
    data['hi'] = people
    return jsonify(data)

if __name__ == '__main__':
    # host:指定绑定IP,port:指定绑定端口,debug指定:是否接受调试,是否返回错误信息
    app.run(host='192.168.1.104', port=8802, debug=True)

0x02 测试

通过get方式测试,hello路径:
python flask 封装属于自己的api_第1张图片
通过get方式测试hi路径:
python flask 封装属于自己的api_第2张图片
通过requests请求测试:

import requests
base_url = "http://192.168.1.104:8802/hi?people=jerry&age=18"
res = requests.get(url=base_url)
if res.ok:
    print(res.status_code)
    print(res.text)

python flask 封装属于自己的api_第3张图片

0x03 解决 WARNING: This is a development server. Do not use it in a production deployment. falsk WSGI

python flask 封装属于自己的api_第4张图片

通过WSGI启动flask:参考

from flask import Flask, jsonify, request
from gevent import  pywsgi

# 创建服务
app = Flask(__name__)

# 指定接口的访问路径,和支持什么请求方式get,post
@app.route('/hello',methods=['get','post'])
def hello():
    people = request.args.get('people')
    return f"hello:\t{people}"

@app.route('/hi',methods=['get'])
def hi():
    people = request.args.get('people')
    age = request.args.get('age')
    data = {}
    data['age'] = age
    data['hi'] = people
    return jsonify(data)

if __name__ == '__main__':
    server = pywsgi.WSGIServer(('192.168.1.104', 8802), app)
    server.serve_forever()

python flask 封装属于自己的api_第5张图片

你可能感兴趣的:(python,python,api,python封装api)