前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Flask—jsonify方式(api接口)「建议收藏」

Flask—jsonify方式(api接口)「建议收藏」

作者头像
全栈程序员站长
发布2022-08-25 13:41:56
4450
发布2022-08-25 13:41:56
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

GET 方法

代码语言:javascript
复制
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://127.0.0.1:5632/blog/api/articles输出如下:

代码语言:javascript
复制
{
  "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输出如下:

代码语言:javascript
复制
{
  "article": { "content": "GET, POST, PUT", "id": 2, "title": "the way to REST" } }

当返回404错误时候,输出

代码语言:javascript
复制
{
  "error": "Not found" }

post方法

代码语言:javascript
复制
from flask import request
from flask import Flask, jsonify, abort, make_response

app = Flask(__name__)

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


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

输出如下:

这里写图片描述
这里写图片描述

PUT 方法

代码语言:javascript
复制
from flask import request
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/<int:article_id>', methods=['PUT'])
def update_article(article_id):
    article = list(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]})


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5632, debug=True)
这里写图片描述
这里写图片描述

DELETE 方法

代码语言:javascript
复制
from flask import request
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/<int:article_id>', methods=['DELETE'])
def delete_article(article_id):
    article = list(filter(lambda t: t['id'] == article_id, articles))
    if len(article) == 0:
        abort(404)
    articles.remove(article[0])
    return jsonify({
  
  'result': True})


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5632, debug=True)
这里写图片描述
这里写图片描述

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/142568.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • GET 方法
  • post方法
  • PUT 方法
  • DELETE 方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档