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 相关文章推荐
Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
Dec 04 Python
常用python数据类型转换函数总结
Mar 11 Python
在Python中处理字符串之ljust()方法的使用简介
May 19 Python
不要用强制方法杀掉python线程
Feb 26 Python
详解Python map函数及Python map()函数的用法
Nov 16 Python
python中将字典形式的数据循环插入Excel
Jan 16 Python
python2.7到3.x迁移指南
Feb 01 Python
python多线程共享变量的使用和效率方法
Jul 16 Python
Python3 批量扫描端口的例子
Jul 25 Python
python如何写出表白程序
Jun 01 Python
Python 3.9的到来到底是意味着什么
Oct 14 Python
Python中Selenium对Cookie的操作方法
Jul 09 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
DC动画电影《黑暗正义联盟》曝预告 5月5日上线数字平台
2020/04/09 欧美动漫
NT IIS下用ODBC连接数据库
2006/10/09 PHP
Javascript 构造函数 实例分析
2008/11/26 Javascript
js 创建快捷方式的代码(fso)
2010/11/19 Javascript
解决IE6的PNG透明JS插件使用介绍
2013/04/17 Javascript
node.js中的dns.getServers方法使用说明
2014/12/08 Javascript
JavaScript 浏览器对象模型BOM使用介绍
2015/04/13 Javascript
使用Raygun对Node.js应用进行错误处理的方法
2015/06/23 Javascript
基于BootstrapValidator的Form表单验证(24)
2016/12/12 Javascript
js select下拉联动 更具级联性!
2020/04/17 Javascript
vue.js组件vue-waterfall-easy实现瀑布流效果
2017/08/22 Javascript
node 利用进程通信实现Cluster共享内存
2017/10/27 Javascript
JQ图片文件上传之前预览功能的简单实例(分享)
2017/11/12 Javascript
详解webpack3编译兼容IE8的正确姿势
2017/12/21 Javascript
React-native桥接Android原生开发详解
2018/01/17 Javascript
JavaScript中常见内置函数用法示例
2018/05/14 Javascript
js中获取URL参数的共用方法getRequest()方法实例详解
2018/10/24 Javascript
Vue中this.$nextTick的作用及用法
2020/02/04 Javascript
Javascript表单序列化原理及实现代码详解
2020/10/30 Javascript
安装PyInstaller失败问题解决
2019/12/14 Python
Pytorch Tensor基本数学运算详解
2019/12/30 Python
Python中socket网络通信是干嘛的
2020/05/27 Python
QML实现钟表效果
2020/06/02 Python
Pycharm配置autopep8实现流程解析
2020/11/28 Python
如何开发一款堪比APP的微信小程序(腾讯内部团队分享)
2016/12/22 HTML / CSS
孕妇装中的著名品牌:Isabella Oliver(伊莎贝拉·奥利弗)
2016/10/31 全球购物
Ivory Isle Designs美国/加拿大:婚礼和活动文具公司
2018/08/21 全球购物
中国文明网签名寄语
2014/01/18 职场文书
煤矿机修工岗位职责
2014/02/07 职场文书
《谁的本领大》教后反思
2014/04/25 职场文书
爱岗敬业演讲稿
2014/05/05 职场文书
庆元旦演讲稿
2014/09/15 职场文书
KTV门卫岗位职责
2014/10/09 职场文书
护理实习生带教计划
2015/01/16 职场文书
保外就医申请书范文
2015/08/06 职场文书
孩子满月酒答谢词
2015/09/30 职场文书