Flask get和post请求使用

安装 Flask

pip install Flask

直接上代码(代码都有注释)

from flask import Flask, request, abort

app = Flask(__name__)


# methods为'GET', 'POST',其它类型的请求都会被拒绝访问
@app.route('/test', methods=['GET', 'POST'])
def test():
    try:
        # GET请求
        if request.method == 'GET':
            # 获取URL上的参数并返回,也可以做逻辑处理,也可以返回400,abort(400, 'GET请求,不允许访问')
            # 判断URL上是否有参数
            if not request.args:
                return 'GET请求,无参数'
            # URL上有参数
            return '用户名:%s\n 密码:%s' % (request.args['username'], request.args['password'])
        else:
            # POST请求,获取传入的json参数
            data = request.json
            # 参数为空返回400
            if not data:
                abort(400, '参数为空')
            # 参数不为空做其它处理
            return print_data(data)
    except Exception as e:
        # 做一下异常处理,也可加上日志打印logger.error(......)
        abort(400, '后台出错:%s' % e)


def print_data(data):
    # 可以编写处理逻辑
    return '传入数据:%s' % data


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=8888)

测试(右键--运行--服务启动即可测试)

get请求测试:

Flask get和post请求使用_第1张图片


Flask get和post请求使用_第2张图片


post请求测试:

Flask get和post请求使用_第3张图片


Flask get和post请求使用_第4张图片


参考资料

Flask中文文档

你可能感兴趣的:(Python,python)