Flask Web开发入门(十三)之构建REST API

97 篇文章 1 订阅
91 篇文章 0 订阅
本文介绍了如何使用Flask-RESTful扩展在Python的Flask框架下构建REST API。通过示例展示了如何定义API类及其方法,并进行接口测试。
摘要由CSDN通过智能技术生成

关于REST API,我们先看一个比较形象的图:
这里写图片描述

在我们之前的章节中,我们其实已经涉及到了Flask框架下REST API接口的构建,比如,文件下载接口:

# 文件下载
@app.route('/download/<path:filename>')
def send_html(filename):
    logger.debug("download file, path is %s" % filename)
    return send_from_directory(app.config['UPLOAD_PATH'], filename, as_attachment=True)

或者,图片显示接口

# show photo
@app.route('/files/<string:filename>', methods=['GET'])
def show_photo(filename):
    if request.method == 'GET':
        if filename is None:
            pass
        else:
            logger.debug('filename is %s' % filename)
            image_data = open(os.path.join(app.config['UPLOAD_PATH'], 'files/%s' % filename), "rb").read()
            response = make_response(image_data)
            response.headers['Content-Type'] = 'image/png'
            return response
    else:
        pass

或者这种格式:

@app.route('/detail/<int:id>',methods=['GET'])
def detail(id):
    pass

除此之外,我们还可以使用Flask-RESTful来构建REST API

Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs. It is a lightweight abstraction that works with your existing ORM/libraries. Flask-RESTful encourages best practices with minimal setup. If you are familiar with Flask, Flask-RESTful should be easy to pick up.

Flask-RESTful可以很方便的将Python对象方法转换为RESTful API,下面我们示例说明:

定义类MonitorApi,类包含方法get,方法参数id

# http://www.flaskapi.org/
# https://www.fullstackpython.com/api-creation.html
# 使用Flask-RESTful构建REST API
# http://flask-restful.readthedocs.io/en/latest/
# https://www.codementor.io/sagaragarwal94/building-a-basic-restful-api-in-python-58k02xsiq
class MonitorApi(Resource):
    @staticmethod
    def get(id):
        return jsonify({'id': id, 'value': random.random(), 'timestamp': int(time.time())})

将方法注册为RESTful API:

api = Api(app)

api.add_resource(monitor_api.MonitorApi, '/api/<id>')

接口测试如下:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值