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

 更新时间:2018年12月28日 14:43:03   作者:liumiaocn  
今天小编就为大家分享一篇关于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.

总结

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

相关文章

  • python实现碑帖图片横向拼接

    python实现碑帖图片横向拼接

    这篇文章主要为大家详细介绍了python实现碑帖图片横向拼接,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • Python中logging日志记录到文件及自动分割的操作代码

    Python中logging日志记录到文件及自动分割的操作代码

    这篇文章主要介绍了Python中logging日志记录到文件及自动分割,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • Python使用修饰器进行异常日志记录操作示例

    Python使用修饰器进行异常日志记录操作示例

    这篇文章主要介绍了Python使用修饰器进行异常日志记录操作,结合实例形式分析了Python基于修饰器的log日志文件操作的相关实现技巧,需要的朋友可以参考下
    2019-03-03
  • python requests抓取one推送文字和图片代码实例

    python requests抓取one推送文字和图片代码实例

    这篇文章主要介绍了python requests抓取one推送文字和图片代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • python interpolate插值实例

    python interpolate插值实例

    这篇文章主要介绍了python interpolate插值实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-07-07
  • python神经网络slim常用函数训练保存模型

    python神经网络slim常用函数训练保存模型

    这篇文章主要为大家介绍了python神经网络使用slim函数进行模型的训练及保存模型示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • 说一说Python logging

    说一说Python logging

    这篇文章主要和大家聊一聊Python logging,Python logging是什么,Python logging的作用是什么,感兴趣的小伙伴们可以参考一下
    2016-04-04
  • python发送多人邮件没有展示收件人问题的解决方法

    python发送多人邮件没有展示收件人问题的解决方法

    这篇文章主要为大家详细介绍了python发送多人邮件没有展示收件人问题的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-06-06
  • Python正则表达式re.findall()几种方法示例

    Python正则表达式re.findall()几种方法示例

    这篇文章主要介绍了Python正则表达式re.findall()几种方法示例,文中介绍了如何使用正则表达式在字符串中查找匹配的字符,并将它们返回为一个列表,示例展示了如何匹配数字并处理没有匹配到的情况,需要的朋友可以参考下
    2024-12-12
  • Python中的数据标准化与反标准化全面指南

    Python中的数据标准化与反标准化全面指南

    在数据处理和机器学习中,数据标准化是一项至关重要的预处理步骤,标准化能够将不同尺度和范围的数据转换为相同的标准,有助于提高模型的性能和稳定性,Python提供了多种库和函数来执行数据标准化和反标准化,如Scikit-learn和TensorFlow
    2024-01-01

最新评论