教你如何使用flask实现ajax数据入库

x33g5p2x  于2022-03-01 转载在 其他  
字(2.9k)|赞(0)|评价(0)|浏览(461)

本文分享自华为云社区《【首发】flask 实现ajax 数据入库,并掌握文件上传》,作者:梦想橡皮擦。

flask 实现ajax 数据入库

在正式编写前需要了解一下如何在 python 函数中去判断,一个请求是 get 还是 post。

python 文件代码如此所示:

  1. # route()方法用于设定路由;
  2. @app.route('/hello.html', methods=['GET', 'POST'])
  3. def hello_world():
  4. if request.method == 'GET':
  5. # args = request.args
  6. return render_template('hello.html')
  7. if request.method == "POST":
  8. print("POST请求")

上述代码通过 requests.method 属性判断当前请求类型,然后实现相应的逻辑。
注意上述内容中的 @app.route('/hello.html', methods=['GET', 'POST']) ,绑定的方法由参数 methods 决定。

HTML 页面代码如下所示:

  1. <!DOCTYPE html>
  2. <html lang="zh-cn">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>这是第一个HTML页面</title>
  6. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
  7. </head>
  8. <body>
  9. {{name}}
  10. <input type="button" value="点击发送请求" id="btn" />
  11. <script>
  12. $(function() {
  13. $('#btn').on('click', function() {
  14. alert($(this).val());
  15. });
  16. })
  17. </script>
  18. </body>
  19. </html>

在 HTML 页面中提前导入 jquery 的 CDN 配置,便于后续实现模拟请求操作。

再次完善一些 POST 请求的相关参数判断,通过 requests.form 获取表单参数。

  1. # route()方法用于设定路由;
  2. @app.route('/hello.html', methods=['GET', 'POST'])
  3. def hello_world():
  4. if request.method == 'GET':
  5. args = request.args
  6. name = args.get('name')
  7. return render_template('hello.html',name=name)
  8. if request.method == "POST":
  9. print("POST请求")
  10. arges = request.form
  11. print(arges)
  12. return "PPP"

同步修改一下前端请求部分,这里改造主要需要的是前端知识。

  1. <body>
  2. {{name}}
  3. <input type="button" value="点击发送请求" id="btn" />
  4. <script>
  5. $(function() {
  6. $('#btn').on('click', function() {
  7. //alert($(this).val());
  8. $.post('./hello.html', function(result) {
  9. console.log(result);
  10. })
  11. });
  12. })
  13. </script>
  14. </body>

测试的时候同步开启浏览器的开发者工具,并且切换到网络请求视图,查看请求与返回数据。

数据传递到后台之后,通过将将 flask 与 mysql 实现对接,完成一个入库操作,然后将数据存储到 MySQL 中。

实现文件上传

了解了POST请求之后,就可以通过该模式实现文件上传操作了。
优先修改 HTML 页面,实现一个文件选择按钮。

  1. <input type="file" id="file" />
  2. <script type="text/javascript">
  3. $(function() {
  4. $('#btn').on('click', function() {
  5. //alert($(this).val());
  6. $.post('./hello.html', function(result) {
  7. console.log(result);
  8. })
  9. });
  10. var get_file = document.getElementById("file");
  11. get_file.onchange = function(e) {
  12. file = e.currentTarget.files[0]; //所有文件,返回一个数组
  13. var form_data = new FormData();
  14. form_data.append("file", file);
  15. console.log(form_data);
  16. form_data.append("file_name", e.currentTarget.files[0].name);
  17. $.ajax({
  18. url: '/upload',
  19. type: 'post',
  20. data: form_data,
  21. contentType: false,
  22. processData: false,
  23. success: function(res) {
  24. console.log(res.data);
  25. }
  26. });
  27. }
  28. })
  29. </script>

服务端处理文件的代码如下所示

  1. @app.route('/upload', methods=['POST'], strict_slashes=False)
  2. def upload():
  3. if request.method == "POST":
  4. print("POST请求")
  5. file = request.files.get('file')
  6. name = request.form.get('file_name')
  7. print(name)
  8. file.save("./"+name)
  9. # print(name)
  10. return "PPP"

这里需要注意的是如果 Python 端存在BUG,前端的AJAX请求会出现 400或者500错误。
文件名通过前端传递 file_name 参数获取。
本案例可以扩展上传成功之后,返回JSON数据到前端进行后续处理。

项目在实测的过程中发现一个问题,在读取前台传递的文件流时,需要使用 request.files.get() 方法实现,而不能用 request.form['参数名'] 。

 点击关注,第一时间了解华为云新鲜技术~​

相关文章