教你如何使用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> & ...
随机推荐
- GNU C字节对齐__attribute__((aligned(n))) #pragma pack(n)
在阅读gnu软件c源代码时,经常会遇到字节对齐相关操作,比如uboot命令相关的代码中,会遇到__attribute__((aligned(n)))扩展关键字,#pragma pack(n)预处理指令 ...
- JavaScript输出的两种方式
var a="Hello World" document.write(a) //在网页上输出:Hello World var a="Hello World" c ...
- 解决windows下因为防火墙无法通过go get 下载gin的问题
使用: go get -u github.com/gin-gonic/gin 出现以下错误: unrecognized import path "gopkg.in/yaml.v2" ...
- Golang 通过创建临时结构体实现 struct 内 interface struct 的 json 反序列化
原文链接 背景 type AData struct { A string `json:"a"` } type BData struct { B string `json:" ...
- 记录ABAP开发的日常——SAP_PO开发同步接口案例
前言:在项目中遇到任务PO接口,需求是SRM发送采购订单信息给SAP,SAP根据信息调用BAPI同步数据,在此作为案例记录. 本次接口采用的协议是SOAP,当然也有其他的协议比如REST等等,在此不做 ...
- vue学习5-js表达式
三目运算符 <!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <m ...
- StringBuilder类介绍
1 package cn.itcast.p2.stringbuffer.demo; 2 3 public class StringBuilderDemo { 4 public static void ...
- Cobbler批量安装操作系统
1,关闭selinux getenforce 查看selinux状态 Disabled 修改/etc/selinux/config 文件 将SELINUX=enforcing改为SELINUX=di ...
- 【Azure 应用服务】Azure Mobile App (NodeJS) 的服务端部署在App Service for Windows中出现404 Not Found -- The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
问题描述 使用NodeJS的后端应用,开发一个Mobile App的服务端,手机端通过REST API来访问获取后端数据.在本地编译好后,通过npm start启动项目,访问效果如下: 但是,当把项目 ...
- 源码安装gitlab
GitLab服务构成 GitLab由以下服务构成: nginx:静态Web服务器 gitlab-shell:用于处理Git命令和修改authorized keys列表 gitlab-workhor ...