使用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")

 

版权声明:
作者:k, k
链接:http://kuyour.top/index.php/2022/03/13/flask%e4%bd%bf%e7%94%a8-python/
来源:KuKey
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
使用flask生成数据接口API-python
#-*- coding:utf-8 -*- from flask import Flask, request, jsonify from werkzeug.utils import redirect app = Flask(__name__) #数据显示支持中文 a……
<<上一篇
下一篇>>