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

Flask—jsonify方式(api接口)「建议收藏」GET方法post方法PUT方法DELETE方法GET方法fromflaskimportFlask,jsonify,abort,make_responseapp=Flask(__name__)articles=[{‘id’:1,’title’:’thewaytopyt…

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

GET 方法

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输出如下:

{
  "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" } }

当返回404错误时候,输出

{
  "error": "Not found" }

post方法

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 方法

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 方法

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.net/142568.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月10日 下午2:20
下一篇 2022年5月10日 下午2:40


相关推荐

  • 安全帽识别算法

    安全帽识别算法应用背景:安全帽作为一种最常见和实用的个人防护用具,能够有效地防止和减轻外来危险源对头部的伤害。但在现场操作过程中,安全帽的佩戴很容易人为忽略,引发了不少人身伤害事故。为了保证工作人员都能在作业中佩戴安全帽,保障作业人员安全,安全帽识别算法系统应运而生。关键字:安全帽识别算法安全帽识别算法技术原理安全帽识别算法采用最新AI人工智能深度学习技术,基于计算机智能视频物体识别算法,且通过规模化的安全帽数据识别训练,赋予监控系统智能识别能力,从而准确判断识别场景内的作业人员是否佩戴安全帽,若检.

    2022年5月12日
    61
  • IntelliJ Idea 2017 注册码 免费激活方法「建议收藏」

    IntelliJ Idea 2017 注册码 免费激活方法「建议收藏」!!!补充版本信息,博友反馈17.3版本之后的不能用。注:如果为2017.3之后的版本,参考评论中23楼提供的博文,最近比较忙,没能补充新版本激活方法。谢谢23楼博友!!!可使用以下两种

    2022年7月3日
    126
  • linux 编译安装GCC4.9.3(完整版)「建议收藏」

    linux 编译安装GCC4.9.3(完整版)「建议收藏」第一步首先下载gcc源码包wgethttp://ftp.tsukuba.wide.ad.jp/software/gcc/releases/gcc-4.9.3/gcc-4.9.3.tar.bz2第二步将下载好的文件放在非root用户也有读权限的地方,例如/home/myuser或者/usr/gcc-build/下面第四步我会讲为什么要这么做.第三步解压文件,做一些准备工作tar

    2022年5月25日
    37
  • 手把手教你如何玩转消息中间件(ActiveMQ)

    手把手教你如何玩转消息中间件(ActiveMQ)情景引入情景分析基本概念的引导本模块主要讲解关于消息中间件的相关基础知识 也是方便我们后面的学习 什么是中间件 非操作系统软件 非业务应用软件 不是直接给最终用户使用 不能直接给用户带来价值的软件 我们就可以称为中间件 比如 Dubbo Tomcat Jetty Jboss 都是属于的 什么是消息中间件 百度百科解释 消息中间件利用高效可靠的消息传递机制进行平

    2026年3月17日
    2
  • 在Cursor中使用MCP服务图文教程

    在Cursor中使用MCP服务图文教程

    2026年3月16日
    2
  • mysql 建前缀索引_MySQL_前缀索引_建立[通俗易懂]

    mysql 建前缀索引_MySQL_前缀索引_建立[通俗易懂]–查看出现频率selectcount(*)ascnt,cityfromsakila.city_demogroupbycityorderbycntdesclimit10;1.selectcount(distinctcity)/count(*)fromsakila.city_demo;*完整列的选择性2.selectcount(distinctleft(ci…

    2022年5月10日
    40

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号