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字符串替换示例
Apr 24 Python
python基础教程之自定义函数介绍
Aug 29 Python
使用Python生成随机密码的示例分享
Feb 18 Python
python实现感知器算法详解
Dec 19 Python
python全栈知识点总结
Jul 01 Python
Python generator生成器和yield表达式详解
Aug 08 Python
python3反转字符串的3种方法(小结)
Nov 07 Python
双向RNN:bidirectional_dynamic_rnn()函数的使用详解
Jan 20 Python
Python基于类路径字符串获取静态属性
Mar 12 Python
pycharm远程连接vagrant虚拟机中mariadb数据库
Jun 05 Python
Python正则表达式高级使用方法汇总
Jun 18 Python
Python如何创建装饰器时保留函数元信息
Aug 07 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
基于数据库的在线人数,日访问量等统计
2006/10/09 PHP
Php图像处理类代码分享
2012/01/19 PHP
ThinkPHP中url隐藏入口文件后接收alipay传值的方法
2014/12/09 PHP
PHP生成静态HTML文档实现代码
2016/06/23 PHP
浅谈PHP实现大流量下抢购方案
2017/12/15 PHP
一步一步制作jquery插件Tabs实现过程
2010/07/06 Javascript
JavaScript定时器详解及实例
2013/08/01 Javascript
JSON序列化与解析原生JS方法且IE6和chrome测试通过
2013/09/05 Javascript
jquery插件推荐浏览器嗅探userAgent
2014/11/09 Javascript
jquery控制页面部分刷新的方法
2015/06/24 Javascript
js实现Form栏显示全格式时间时钟效果代码
2015/08/19 Javascript
基于JS判断iframe是否加载成功的方法(多种浏览器)
2016/05/13 Javascript
jQuery仿写百度百科的目录树
2017/01/03 Javascript
谈谈vue中mixin的一点理解
2017/12/12 Javascript
JavaScript执行环境及作用域链实例分析
2018/08/01 Javascript
Angular2 自定义表单验证器的实现方法
2018/12/14 Javascript
微信小程序tab切换可滑动切换导航栏跟随滚动实现代码
2019/09/04 Javascript
Jquery Fade用法详解
2020/11/06 jQuery
Python基于twisted实现简单的web服务器
2014/09/29 Python
浅谈Python程序与C++程序的联合使用
2015/04/07 Python
Python使用getpass库读取密码的示例
2017/10/10 Python
Python读取excel指定列生成指定sql脚本的方法
2018/11/28 Python
python实现根据文件关键字进行切分为多个文件的示例
2018/12/10 Python
对Python3中dict.keys()转换成list类型的方法详解
2019/02/03 Python
计算机二级python学习教程(3) python语言基本数据类型
2019/05/16 Python
Python3 itchat实现微信定时发送群消息的实例代码
2019/07/12 Python
详解Python流程控制语句
2020/10/28 Python
python软件测试Jmeter性能测试JDBC Request(结合数据库)的使用详解
2021/01/26 Python
浅谈HTML5 Web Worker的使用
2018/01/05 HTML / CSS
商务经理岗位职责
2014/07/30 职场文书
三好学生先进事迹材料
2014/08/28 职场文书
工作疏忽、懈怠的检讨书
2014/09/11 职场文书
党的群众路线教育实践活动对照检查材料思想汇报
2014/09/19 职场文书
2015年部门工作总结范文
2015/03/31 职场文书
婚宴新娘致辞
2015/07/28 职场文书
护士岗位竞聘书
2015/09/15 职场文书