Python编程在flask中模拟进行Restful的CRUD操作


Posted in Python onDecember 28, 2018

这篇文章中我们将通过对HelloWorld的message进行操作,介绍一下如何使用flask进行Restful的CRUD。

概要信息

Python编程在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

页面确认

Python编程在flask中模拟进行Restful的CRUD操作

代码示例: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.

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
python encode和decode的妙用
Sep 02 Python
python k-近邻算法实例分享
Jun 11 Python
python中range()与xrange()用法分析
Sep 21 Python
Python实现学校管理系统
Jan 11 Python
Python使用matplotlib绘图无法显示中文问题的解决方法
Mar 14 Python
Python3 列表,数组,矩阵的相互转换的方法示例
Aug 05 Python
基于Python安装pyecharts所遇的问题及解决方法
Aug 12 Python
Python远程开发环境部署与调试过程图解
Dec 09 Python
Python实现i人事自动打卡的示例代码
Jan 09 Python
python退出循环的方法
Jun 18 Python
python中用Scrapy实现定时爬虫的实例讲解
Jan 18 Python
python实现学员管理系统(面向对象版)
Jun 05 Python
python获取服务器响应cookie的实例
Dec 28 #Python
基于Python在MacOS上安装robotframework-ride
Dec 28 #Python
Python3爬虫之urllib携带cookie爬取网页的方法
Dec 28 #Python
Python编程图形库之Pillow使用方法讲解
Dec 28 #Python
对python中大文件的导入与导出方法详解
Dec 28 #Python
Python编程深度学习计算库之numpy
Dec 28 #Python
python将txt文档每行内容循环插入数据库的方法
Dec 28 #Python
You might like
老照片 - 几十年前的收音机与人
2021/03/02 无线电
PHP的PSR规范中文版
2013/09/28 PHP
PHP实现自动发送邮件功能代码(qq 邮箱)
2017/08/18 PHP
Laravel框架中VerifyCsrfToken报错问题的解决
2017/08/30 PHP
ThinkPHP5.0框架使用build 自动生成模块操作示例
2019/04/11 PHP
ThinkPHP 框架实现的读取excel导入数据库操作示例
2020/04/14 PHP
PHP+MySql实现一个简单的留言板
2020/07/19 PHP
打开超链需要“确认”对话框的方法
2007/03/08 Javascript
JS中Iframe之间传值及子页面与父页面应用
2013/03/11 Javascript
基于JavaScript实现继承机制之构造函数方法对象冒充的使用详解
2013/05/07 Javascript
textarea 控制输入字符字节数(示例代码)
2013/12/27 Javascript
JavaScript 获取任一float型小数点后两位的小数
2014/06/30 Javascript
javascript实现页面刷新时自动清空表单并选中的方法
2015/07/18 Javascript
基于nodejs+express(4.x+)实现文件上传功能
2015/11/23 NodeJs
Javascript基于jQuery UI实现选中区域拖拽效果
2016/11/25 Javascript
vue-cli V3.0版本的使用详解
2018/10/24 Javascript
详解用场景去理解函数柯里化(入门篇)
2019/04/11 Javascript
小程序根据手机机型设置自定义底部导航距离
2019/06/04 Javascript
在vue-cli 3中给stylus、sass样式传入共享的全局变量
2019/08/12 Javascript
小程序实现左滑删除的效果的实例代码
2020/10/19 Javascript
python读取html中指定元素生成excle文件示例
2014/04/03 Python
django使用图片延时加载引起后台404错误
2017/04/18 Python
Python利用递归实现文件的复制方法
2018/10/27 Python
使用Python 正则匹配两个特定字符之间的字符方法
2018/12/24 Python
详解python-图像处理(映射变换)
2019/03/22 Python
使用python判断jpeg图片的完整性实例
2019/06/10 Python
Python shelve模块实现解析
2019/08/28 Python
python中matplotlib条件背景颜色的实现
2019/09/02 Python
Jupyter notebook 启动闪退问题的解决
2020/04/13 Python
Html5 APP中监听返回事件处理的方法示例
2018/03/15 HTML / CSS
可持续未来的时尚基础:Alternative Apparel
2019/05/06 全球购物
标准毕业生自荐信范文
2013/11/04 职场文书
司机工作自我鉴定
2014/09/19 职场文书
goland设置颜色和字体的操作
2021/05/05 Golang
python 如何将两个实数矩阵合并为一个复数矩阵
2021/05/19 Python
MySQL下载安装配置详细教程 附下载资源
2022/09/23 MySQL