Python编程在flask中模拟进行Restful的CRUD操作
作者:liumiaocn 发布时间:2021-03-11 18:44:39
标签:python,flask,restful,crud
这篇文章中我们将通过对HelloWorld的message进行操作,介绍一下如何使用flask进行Restful的CRUD。
概要信息
事前准备:flask
liumiaocn:flask liumiao$ which flask
/usr/local/bin/flask
liumiaocn:flask liumiao$ flask --version
Flask 1.0.2
Python 2.7.10 (default, Jul 15 2017, 17:16:57)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]
liumiaocn:flask liumiao$
代码示例:HTTP谓词(GET)
就像angular的插值表达式在模版中的作用一样,在flask中也可以一样使用,如果不熟悉angular的插值表达式的话也不要紧,看完下面的例子,基本上就会有一个大致的印象。
代码示例
liumiaocn:flask liumiao$ cat flask_4.py
#!/usr/bin/python
from flask import Flask
from flask import render_template
app = Flask(__name__)
greeting_messages=["Hello World", "Hello Python"]
@app.route("/api/messages",methods=['GET'])
def get_messages():
return render_template("resttest.html",messages=greeting_messages)
if __name__ == "__main__":
app.debug=True
app.run(host='0.0.0.0',port=7000)
liumiaocn:flask liumiao$
模版文件
liumiaocn:flask liumiao$ cat templates/resttest.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Restful</title>
</head>
<body>
{% for message in messages %}
<h1>{{ message }}</h1>
{% endfor %}
</body>
</html>
liumiaocn:flask liumiao$
代码解析:app.route中指定了HTTP谓词GET,缺省GET可以省略,如果一个方法对应多个谓词动作,通过request.method来分离时,可以写成methods=[‘GET','POST']的形式
执行&确认
liumiaocn:flask liumiao$ ./flask_4.py
* Serving Flask app "flask_4" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:7000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 131-533-062
页面确认
代码示例:HTTP谓词(DELETE|PUT|POST)
liumiaocn:flask liumiao$ cat flask_4.py
#!/usr/bin/python
from flask import Flask
from flask import render_template
from flask import request
import json
app = Flask(__name__)
greeting_messages=["Hello World", "Hello Python"]
#HTTP: GET: Retrieve operation
@app.route("/api/messages",methods=['GET'])
def get_messages():
return render_template("resttest.html",messages=greeting_messages)
#HTTP: DELETE: Delete operation
@app.route("/api/messages/<messageid>",methods=['DELETE'])
def delete_message(messageid):
global greeting_messages
del greeting_messages[int(messageid)]
return render_template("resttest.html",messages=greeting_messages)
#HTTP: PUT: Update operation
#HTTP: POST: Create operation
@app.route("/api/messages/<messageid>",methods=['PUT','POST'])
def update_message(messageid):
global greeting_message
msg_info=json.loads(request.get_data(True,True,False))
#msg_info=request.args.get('message_info')
#msg_info=request.form.get('message_info','default value')
#msg_info=request.values.get('message_info','hello...')
greeting_messages.append("Hello " + msg_info["message_info"])
return render_template("resttest.html",messages=greeting_messages)
if __name__ == "__main__":
app.debug=True
app.run(host='0.0.0.0',port=7000)
liumiaocn:flask liumiao$
执行&结果确认
执行日志
liumiaocn:flask liumiao$ ./flask_4.py
* Serving Flask app "flask_4" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:7000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 131-533-062
结果确认:Delete
liumiaocn:flask liumiao$ curl -X DELETE http://localhost:7000/api/messages/1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Restful</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>liumiaocn:flask liumiao$
可以看到执行一次DELETE之后,两条消息现在只剩下一条消息了,接下来使用POST添加再添加一条
liumiaocn:flask liumiao$ curl -X POST -d '{"message_info":"LiuMiaoPost"}' http://localhost:7000/api/messages/3
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Restful</title>
</head>
<body>
<h1>Hello World</h1>
<h1>Hello LiuMiaoPost</h1>
</body>
</html>liumiaocn:flask liumiao$
再执行一次PUT操作
liumiaocn:flask liumiao$ curl -X PUT -d '{"message_info":"LiuMiaoPut"}' http://localhost:7000/api/messages/4
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Restful</title>
</head>
<body>
<h1>Hello World</h1>
<h1>Hello LiuMiaoPost</h1>
<h1>Hello LiuMiaoPut</h1>
</body>
</html>liumiaocn:flask liumiao$
小结
这篇文章中,使用最简单的方式在flask中模拟了一下如何进行Restful的CRUD操作,当然,实际的做法有很多种,在接下来的文章中还会介绍另外一种非常常见的轮子flask-restful.
来源:https://blog.csdn.net/liumiaocn/article/details/80728020


猜你喜欢
- 问题你想实现一个服务器,通过TCP协议和客户端通信。解决方案创建一个TCP服务器的一个简单方法是使用 socketserver 库。例如,下
- 好久都没有写博客了,主要是太懒了,尤其是在阳春三月,风和日丽的日子,太阳暖暖的照在身上,真想美美的睡上一觉。就导致了这篇博客拖到现在才开始动
- 1 回表的性能消耗无论单列索引 还是 联合索引,一个索引就对应一个独立的B+索引树,索引树节点仅包含:索引里的字段值主键值即使根据索引树按条
- MySQL内外连接表的连接分为内连接和外连接。内连接内连接内连接的SQL如下:SELECT ... FROM t1 INNER JOIN t
- 本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。以下文章来源于Pyth
- Python 编程语言已经成为 IT 中使用的最流行的语言之一。成功的一个原因是它可以用来解决各种问题。从网站开发到数据科学、机器学习到任务
- 爱如风过 问:js如何能知道浏览者计算机或者浏览器使用的语言是繁体还是简体?如题,我想用jS检测到浏览者使用的是繁体还是简体中文,以便设置页
- 1.delete不能使自动编号返回为起始值。但是truncate能使自动增长的列的值返回为默认的种子 2.truncate只能一次清空,不能
- 一、Pylint 是什么Pylint 是一个 Python 代码分析工具,它分析 Python 代码中的错误,查找不符合代码风格标准和有潜在
- 选择排序算法步骤:找到数组中最小的那个元素中,将它和数组的第一个元素交换位置,在剩下的元素中找到最小的元素,将它和数组的第二个元素交换位置,
- 一、python中进程间通信业务场景:在当前遇到的业务场景中,我们需要启一个间隔任务,这个间隔任务跑一个算法,然后把算法的结果进行一些处理,
- 前言最小二乘 * east Square Method,做为分类回归算法的基础,有着悠久的历史(由马里·勒让德于1806年提出)。它通过最小化
- 1 蚂蚁森林简介蚂蚁森林是一项旨在带动公众低碳减排的公益项目,每个人的低碳行为在蚂蚁森林里可计为"绿色能量"。"
- 前言:有些时候,为了设定手机铃声或者发抖音视频,我们会耗费大量时间在剪辑音乐高潮部分上。那么这个音乐高潮的提取能不能自动化呢?当然可以。先来
- 本文实例讲述了python函数局部变量用法。分享给大家供大家参考。具体分析如下:当你在函数定义内声明变量的时候,它们与函数外具有相同名称的其
- 描述sorted() 函数对所有可迭代的对象进行排序操作。语法sorted(iterable, key=None, reverse=Fals
- 本文实例为大家分享了mysql 5.6.17 安装教程简单版,供大家参考,具体内容如下1.linux版mysql下载(建议不要下5.7,安装
- 最近在一个项目中遇到一个查询页面,其中一个查询条件是根据选择的年份、月以及周数显示选择的该周从几号到几号,这样一个需求。在网上搜
- 一、基本数据类型前缀数据类型数据类型简写ArrayarrBooleanblnBytebytCharchrDateTimedtmDecimal
- 数据集数据集为Barcelona某段时间内的气象数据,其中包括温度、湿度以及风速等。本文将简单搭建来对风速进行预测。特征构造对于风速的预测,