Flask提供的RESTful Web服务

REST全称是Representational State Transfer。他在论文中提到:“我这篇文章的写作目的,就是想在符合架构原理的前提下,理解和评估以网络为基础的应用软件的架构设计,得到一个功能强、性能好、适宜通信的架构。REST指的是一组架构约束条件和原则。
REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力, 更好地使用现有Web标准中的一些准则和约束。

REST的特性:
Client-Server:服务器端与客户端分离,服务器不再关注客户端的界面和状态,另一方面客户端也不再关注数据的存储问题,双方只要遵守共同约定就可以独立开发。
Stateless(无状态):每次客户端请求必需包含完整的信息,换句话说,每一次请求都是独立的,服务器不存储来自客户的某个请求信息,这些信息应由客户端负责维护。
Cacheable(可缓存):服务器端的返回内容可以在通信链中某处被缓存,以减少交互次数,提高网络效率。
Layered System(分层结构):允许在服务器和客户端间通过引入中间层(代理、网关等)代替服务器对客户端的请求进行回应。
Uniform Interface(统一接口):客户端与服务器端的通讯方法(GET,POST,PUT,DELETE等)必需是统一的。
Code on demand(按需执行代码,可选):服务器可以提供一些代码并在客户端中执行,以扩展客户端的某些功能。

REST Web 服务的核心概念是资源(resources)。资源被 URI(Uniform Resource Identifier, 统一资源标识符)定位,客户端使用 HTTP 协议操作这些资源,我们用一句不是很全面的话来概括就是:URI 定位资源,用 HTTP 动词(GET, POST, PUT, DELETE 等)描述操作。
GET:获取资源信息;
POST:创建新的资源;
PUT:更新资源;
DELETE:删除资源

GET方法:

# -*- coding: utf-8 -*-
from flask import Flask, jsonify, abort, make_response
app = Flask(__name__)
articles = [
    {
        'id': 1,
        'title': 'the way to python',
        'content': 'tuple, list, dict'
    },
    {
        'id': 2,
        'title': 'the way to REST',
        'content': 'GET, POST, PUT'
    }
]
@app.route('/blog/api/articles', methods=['GET'])
def get_articles():
    """ 获取所有文章列表 """
    return jsonify({'articles': articles})
@app.route('/blog/api/articles/<int:article_id>', methods=['GET'])
def get_article(article_id):
    """ 获取某篇文章 """
    article = filter(lambda a: a['id'] == article_id, articles)
    if len(article) == 0:
        abort(404)
    return jsonify({'article': article[0]})
@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5632, debug=True)

本机运行后输入http://localhost:5632/blog/api/articles

{
  "articles": [
    {
      "content": "tuple, list, dict", 
      "id": 1, 
      "title": "the way to python"
    }, 
    {
      "content": "GET, POST, PUT", 
      "id": 2, 
      "title": "the way to REST"
    }
  ]
}

http://localhost:5632/blog/api/articles/2

{
  "article": {
    "content": "GET, POST, PUT", 
    "id": 2, 
    "title": "the way to REST"
  }
}

http://localhost:5632/blog/api/articles/5

{
  "error": "Not found"
}

POST方法:

from flask import request
@app.route('/blog/api/articles', methods=['POST'])
def create_article():
    if not request.json or not 'title' in request.json:
        abort(400)
    article = {
        'id': articles[-1]['id'] + 1,
        'title': request.json['title'],
        'content': request.json.get('content', '')
    }
    articles.append(article)
    return jsonify({'article': article}), 201

PUT方法:

@app.route('/blog/api/articles/<int:article_id>', methods=['PUT'])
def update_article(article_id):
    article = filter(lambda a: a['id'] == article_id, articles)
    if len(article) == 0:
        abort(404)
    if not request.json:
        abort(400)

    article[0]['title'] = request.json.get('title', article[0]['title'])
    article[0]['content'] = request.json.get('content', article[0]['content'])
    return jsonify({'article': article[0]})

DELETE方法:

@app.route('/blog/api/articles/<int:article_id>', methods=['DELETE'])
def delete_article(article_id):
    article = filter(lambda t: t['id'] == article_id, articles)
    if len(article) == 0:
        abort(404)
    articles.remove(article[0])
    return jsonify({'result': True})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值