教你如何使用flask实现ajax数据入库
摘要:在正式编写前需要了解一下如何在 python 函数中去判断,一个请求是 get 还是 post。
本文分享自华为云社区《【首发】flask 实现ajax 数据入库,并掌握文件上传》,作者:梦想橡皮擦。
flask 实现ajax 数据入库
在正式编写前需要了解一下如何在 python 函数中去判断,一个请求是 get 还是 post。
python 文件代码如此所示:
# route()方法用于设定路由;
@app.route('/hello.html', methods=['GET', 'POST'])
def hello_world():
if request.method == 'GET':
# args = request.args
return render_template('hello.html') if request.method == "POST":
print("POST请求")
上述代码通过 requests.method 属性判断当前请求类型,然后实现相应的逻辑。
注意上述内容中的 @app.route('/hello.html', methods=['GET', 'POST']) ,绑定的方法由参数 methods 决定。
HTML 页面代码如下所示:
<!DOCTYPE html>
<html lang="zh-cn"> <head>
<meta charset="UTF-8">
<title>这是第一个HTML页面</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head> <body>
{{name}}
<input type="button" value="点击发送请求" id="btn" />
<script>
$(function() {
$('#btn').on('click', function() {
alert($(this).val()); });
})
</script>
</body> </html>
在 HTML 页面中提前导入 jquery 的 CDN 配置,便于后续实现模拟请求操作。
再次完善一些 POST 请求的相关参数判断,通过 requests.form 获取表单参数。
# route()方法用于设定路由;
@app.route('/hello.html', methods=['GET', 'POST'])
def hello_world():
if request.method == 'GET':
args = request.args
name = args.get('name')
return render_template('hello.html',name=name) if request.method == "POST":
print("POST请求")
arges = request.form
print(arges)
return "PPP"
同步修改一下前端请求部分,这里改造主要需要的是前端知识。
<body>
{{name}}
<input type="button" value="点击发送请求" id="btn" />
<script>
$(function() {
$('#btn').on('click', function() {
//alert($(this).val());
$.post('./hello.html', function(result) {
console.log(result);
})
});
})
</script>
</body>
测试的时候同步开启浏览器的开发者工具,并且切换到网络请求视图,查看请求与返回数据。
数据传递到后台之后,通过将 flask 与 mysql 实现对接,完成一个入库操作,然后将数据存储到 MySQL 中。
实现文件上传
了解了POST请求之后,就可以通过该模式实现文件上传操作了。
优先修改 HTML 页面,实现一个文件选择按钮。
<input type="file" id="file" />
<script type="text/javascript">
$(function() {
$('#btn').on('click', function() {
//alert($(this).val()); $.post('./hello.html', function(result) {
console.log(result);
})
});
var get_file = document.getElementById("file");
get_file.onchange = function(e) { file = e.currentTarget.files[0]; //所有文件,返回一个数组
var form_data = new FormData(); form_data.append("file", file);
console.log(form_data); form_data.append("file_name", e.currentTarget.files[0].name);
$.ajax({
url: '/upload',
type: 'post',
data: form_data,
contentType: false,
processData: false,
success: function(res) {
console.log(res.data);
}
});
}
})
</script>
服务端处理文件的代码如下所示
@app.route('/upload', methods=['POST'], strict_slashes=False)
def upload():
if request.method == "POST":
print("POST请求")
file = request.files.get('file')
name = request.form.get('file_name')
print(name)
file.save("./"+name)
# print(name)
return "PPP"
这里需要注意的是如果 Python 端存在BUG,前端的AJAX请求会出现 400或者500错误。文件名通过前端传递 file_name 参数获取。本案例可以扩展上传成功之后,返回JSON数据到前端进行后续处理。
项目在实测的过程中发现一个问题,在读取前台传递的文件流时,需要使用 request.files.get() 方法实现,而不能用 request.form['参数名'] 。
教你如何使用flask实现ajax数据入库的更多相关文章
- flask+sqlite3+echarts2+ajax数据可视化报错:UnicodeDecodeError: 'utf8' codec can't decode byte解决方法
flask+sqlite3+echarts2+ajax数据可视化报错: UnicodeDecodeError: 'utf8' codec can't decode byte 解决方法: 将 py文件和 ...
- Ajax --- 数据请求
下面主要介绍(JS原生)数据请求的主要步骤: Ajax 数据请求步骤: 1.创建XMLHttpRequest对象 2.准备数据发送 3.执行发送 4.指定回掉函数 第一步:创建XMLHttpReque ...
- 弹出层和ajax数据交互
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs& ...
- VueJS搭建简单后台管理系统框架 (二) 模拟Ajax数据请求
开发过程中,免不了需要前台与后台的交互,大部分的交互都是通过Ajax请求来完成,在服务端未完成开发时,前端需要有一个可以模拟Ajax请求的服务器. 在NodeJs环境下,通过配置express可访问的 ...
- ajax数据请求5(php格式)
ajax数据请求5(php格式): <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...
- ajax数据请求4(xml格式)
ajax数据请求4(xml格式): <!doctype html> <html> <head> <meta charset="utf-8" ...
- ajax数据请求3(数组json格式)
ajax数据请求3(数组json格式) <!doctype html> <html> <head> <meta charset="utf-8&quo ...
- ajax数据请求2(json格式)
ajax数据请求2(json格式) <!DOCTYPE html> <html> <head> <meta charset="UTF-8" ...
- AJAX数据请求
ajax数据请求需要四个步骤:(请求文本内容) 1.创建XMLHttpRequest对象: 2.打开与服务起的链接: 3.发送给服务器: 4.响应就绪. <!DOCTYPE html> & ...
随机推荐
- 《剑指offer》面试题10- I. 斐波那契数列
问题描述 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项.斐波那契数列的定义如下: F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - ...
- leetcode 718. 最长重复子数组
问题描述 给两个整数数组 A 和 B ,返回两个数组中公共的.长度最长的子数组的长度. 示例: 输入: A: [1,2,3,2,1] B: [3,2,1,4,7] 输出:3 解释: 长度最长的公共子数 ...
- Cesium中文网——如何开发一款地图下载工具[一]
Cesium中文网:http://cesiumcn.org/ | 国内快速访问:http://cesium.coinidea.com/ Cesium中文网的朋友们的其中一个主题是:自己独立开发一款地图 ...
- 论文解读GALA《Symmetric Graph Convolutional Autoencoder for Unsupervised Graph Representation Learning》
论文信息 Title:<Symmetric Graph Convolutional Autoencoder for Unsupervised Graph Representation Learn ...
- 009 Linux 文件大小统计与排序( du于df和sort)
@ 目录 01 du 与 df 作用与区别? du(disk usage) df(disk free) 02 du 常用命令示例 03 sort 常用参数 04 常用组合 du + sort + he ...
- plsql 带参数的游标
-- 带参数的游标 -- cursor c(no emp.deptno%type) is select * from emp where deptno=no; 参数的起名 不要和表中的列名相同! -- ...
- CKKS Part5: CKKS的重缩放
本文翻译于 CKKS EXPLAINED, PART 5: RESCALING,主要介绍CKKS方案中最重要的技术- rescaling,重缩放技术 介绍 在CKKS的前一篇文章 CKKS Part4 ...
- vue+element ui中select组件选择失效问题原因与解决方法
codejing 2020-07-10 09:13:31 652 收藏 分类专栏: Web Vue Element UI 版权 .当表单form赋完值后,如果后续又对form中某一属性值进行操作如 ...
- 前端开发Grunt工具的安装使用
随着前端开发效果越来越丰富,前端的结构也越来越复杂,这个时候就需要一个工具来进行管理,可以帮你做语法校验,文件拼接,代码压缩,文件清理等等琐事,Grunt就是这么一个不错的工具. 安装并不复杂,只要先 ...
- 自定义的类实现copy操作
1.自定义类实现copy操作 让类遵守NSCopying协议 实现 copyWithZone:方法,在该方法中返回一个对象的副本即可. 在copyWithZone方法中,创建一个新的对象,并设置该对象 ...