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

关于REST API,我们先看一个比较形象的图:
Flask Web开发入门(十三)之构建REST API_第1张图片

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

# 文件下载
@app.route('/download/')
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/', 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/',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/')

接口测试如下:

Flask Web开发入门(十三)之构建REST API_第2张图片

你可能感兴趣的:(综合,架构,中间件,Python,Flask,Python,Web开发,REST,FlaskR)