Flask---jsonify方式(api接口)

2024-08-31 22:18
文章标签 接口 方式 api flask jsonify

本文主要是介绍Flask---jsonify方式(api接口),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      • GET 方法
      • post方法
      • PUT 方法
      • DELETE 方法

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_responseapp = 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_responseapp = 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_responseapp = 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)

这里写图片描述

这篇关于Flask---jsonify方式(api接口)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125143

相关文章

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

SpringBoot实现不同接口指定上传文件大小的具体步骤

《SpringBoot实现不同接口指定上传文件大小的具体步骤》:本文主要介绍在SpringBoot中通过自定义注解、AOP拦截和配置文件实现不同接口上传文件大小限制的方法,强调需设置全局阈值远大于... 目录一  springboot实现不同接口指定文件大小1.1 思路说明1.2 工程启动说明二 具体实施2

HTTP 与 SpringBoot 参数提交与接收协议方式

《HTTP与SpringBoot参数提交与接收协议方式》HTTP参数提交方式包括URL查询、表单、JSON/XML、路径变量、头部、Cookie、GraphQL、WebSocket和SSE,依据... 目录HTTP 协议支持多种参数提交方式,主要取决于请求方法(Method)和内容类型(Content-Ty

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

Linux系统管理与进程任务管理方式

《Linux系统管理与进程任务管理方式》本文系统讲解Linux管理核心技能,涵盖引导流程、服务控制(Systemd与GRUB2)、进程管理(前台/后台运行、工具使用)、计划任务(at/cron)及常用... 目录引言一、linux系统引导过程与服务控制1.1 系统引导的五个关键阶段1.2 GRUB2的进化优

IDEA与MyEclipse代码量统计方式

《IDEA与MyEclipse代码量统计方式》文章介绍在项目中不安装第三方工具统计代码行数的方法,分别说明MyEclipse通过正则搜索(排除空行和注释)及IDEA使用Statistic插件或调整搜索... 目录项目场景MyEclipse代码量统计IDEA代码量统计总结项目场景在项目中,有时候我们需要统计