使用flask生成数据接口API-python

#-*- coding:utf-8 -*-
from flask import Flask, request, jsonify
from werkzeug.utils import redirect
app = Flask(__name__)

#数据显示支持中文
app.config['JSON_AS_ASCII'] = False


@app.route("/")
def hello_world():
    return "hello world"

@app.route("/hey/<username>/")
def hey_yingyong(username):
    return "hey %s" % username

@app.route("/my_number/<int:number>/")
def my_number(number):
    return "my %s" % (number+number)

@app.route("/my_float/<float:number>/")
def my_float(number): return "my %s" % (number+number)

@app.route("/baidu/")
def baidu():
    return redirect("http://www.baidu.com")

@app.route("/json")
def json():
    dict = [{"name":'张三'}, {"gender":'男'}]
    return jsonify(dict)

# 默认是get,可以改为post
@app.route("/p", methods=["GET"])
def he():
    return "hello_world"

# 处理get和post请求
@app.route("/test/my/first", methods=["POST"])
def first_post():
    try:
        my_json = request.get_json()
        print(my_json)
        get_name = my_json.get("name")
        get_age = my_json.get("age")
        if not all([get_name,get_age]):
            return jsonify(msg="缺少参数")

        get_age += 10
        return jsonify(name=get_name, age=get_age)
    except Exception as e:
        print(e)
        return jsonify(msg="出错了哦,请查看是否正确访问")


app.run(host="0.0.0.0")

 

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注