当前位置:网站首页>Flask Framework - Sijax
Flask Framework - Sijax
2022-07-30 14:10:00 【White Chocolate LIN】
目录
上篇文章我们学习了Flask框架——Flask-SQLite数据库,这篇文章我们学习Flask框架——Flask-Sijax.
简单地了解webSynchronous and asynchronous interactions in applications:
同步交互:The user triggers a certainHTTP请求到服务器,The server returns a new one after processing itHTMLThe web page responds to the client,before the server returns a response,The client can only wait idle,Even a small interaction、Just return a very simple data from the server side,都要返回一个完整的HTMLweb page to display,And the user wastes time reading the entire page every time.
异步交互:The browser does not have to wait for the server to return the result,within the server response time,The client can still continue to do other things.
AJAX全名为:Asynchronous Javascript And XML(异步JavaScript和XML)是与服务器交换数据的技术,It does not need to refresh the entire page,Implemented data update for some web pages,Respond quickly to user actions.
Flask-Sijax
通过Flask-Sijax可以将Sijax添加到我们的Flask程序中,Flask-Sijax安装方法很简单,执行如下代码:
pip install flask-sijax
Sijax代表’Simple Ajax’,它是一个Python/jQuery库,可以通过Sijax将Ajax引入到web应用程序. 它使用jQuery.ajax来发出AJAX请求.
在SijaxThe most important and most commonly used of the Sijax.request(),其语法格式为:
Sijax.request('function_name',[参数列表],{jQuery.ajax附加参数})
其中:
function_name:必填,Specifies the function to call;
参数列表:可填,传递的参数;
jQuery.ajax附加参数:允许覆盖Sijax用来调用jQuery.ajax的一些参数.
例如:
Sijax.request('function_name'); #调用不带参数的函数
Sijax.request('function_name',['arg1,....,argn']); #调用带参数的函数
Sijax.request('function_name',[],{'timeout':1500}); #调用不带参数的函数,告诉底层jQuery.ajax使用1.5秒的超时时间
接下来我们通过Flaskprogram to demonstrate how to use itFlask-Sijax.
初始化配置
在安装Flask-Sijax的过程中,json2.jswill be installed by defaultFlask项目目录中的static/js/sijax中,如下图所示:

Sijax使用JSON在浏览器和服务器之间传递数据,因此,浏览器需要本地支持JSON或从json2.js文件获得JSON支持,FlaskThe program configuration is shown below:
import flask_sijax
from flask import Flask, g, render_template
import os
from flask_sijax import sijax
app = Flask(__name__)
path=os.path.join('.',os.path.dirname(__file__),'static/js/sijax') #json2.js文件路径
app.config['SIJAX_STATIC_PATH']=path #配置sijax静态文件路径
app.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js' #加载json2.js静态文件的url
flask_sijax.Sijax(app) #添加Sijax
if __name__ == '__main__':
app.run(debug=True)
首先配置sijax静态文件的路径,Then the configuration is loadedjson2.js静态文件,为了Flask程序能够使用Sijax,所以需要使用flask_sijax添加Sijax到我们的Flask程序.
处理Sijax请求
If the view function can handle itSijax请求,有两种方法:
1、in the route decorator,添加POST请求方法:
@app.route('/url',methods = ['GET','POST'])
2、Use helper decorators:
@flask_sijax.route(app,'视图函数名')
The sample code of the view function is shown below:
@flask_sijax.route(app,'/hello') #Use a helper decorator to handle thisSijax请求
def hello():
def say_hi(response): #定义say_hi函数
response.alert('成功使用Sijax!') #弹出警示框
if g.sijax.is_sijax_request: #Determine whether the request issijax请求
g.sijax.register_callback('say_hi',say_hi) #是sijax请求就调用say_hi函数
return g.sijax.process_request() #Sijax执行hello函数并将响应返回给浏览器
return render_template('my.html') #使用render_template()方法渲染my.html
First we make the view function through the helper decoratorhello能够处理sijax请求,再自定义say_hi函数,Its role is to pop up an alert box.通过sijax.is_sijax_requestmethod to determine whether the request issijax请求,是sijax请求通过sijax.register_callback()方法调用say_hi函数,使用sijax.process_request()方法执行hellofunction and return the response to the browser.
注意:gEquivalent to a single request“全局变量”,Can be called in a single request,But it is isolated from other requests,Destroyed with the end of this request;
my.htmlThe template file code is shown below:
<html>
<head>
{# 调用百度的jQuery加速 #}
<script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
{# 安装Flask-sijax时默认安装的sijax.js #}
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
{# 使用过滤器safe禁止转译sijax.get_js()值 #}
<script type="text/javascript"> {
{ g.sijax.get_js()|safe }} </script>
</head>
<body>
<a href="javascript://" onclick="Sijax.request('say_hi');">点击</a>
</body>
</html>
这里我们调用了百度的jQuery加速,and called the static foldersijax.js文件,使用过滤器safeprofessional bansijax.get_js()值.
在超链接a标签中,添加了点击事件,When clicked it will be used without parametersSijax.request()方法调用say_hi函数发出Sijax请求.
启动Flask程序,访问http://127.0.0.1:5000/hello,如下图所示:

其中:jquery.min.jsIt was we who called BaidujQuery产生的;sijax.jsis what we call the local static filesijax.js产生的;
当我们点击后,A warning box will pop up,如下图所示:

查看最后一个hello请求,如下图所示:


其中sijax_rqThe function requested for us,sijax_argsParameters passed for our request,Since we call without parametersSijax.request()方法.
This succeeds without a request to refresh the web page,发送了sijaxRequested and got a response.
获取表单数据
Then when we need to request without refreshing the web page,Get the data sent from the formsijax请求时,可以使用sijax中的Sijax.getFormValues()方法,其语法格式为:
Sijax.getFormValues(jQuery_selector)
Here we use the above view function code,而my.htmlThe template file code is modified to:
<html>
<head>
{# 调用百度的jQuery加速 #}
<script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
{# 安装Flask-sijax时默认安装的sijax.js #}
<script type="text/javascript" src="/static/js/sijax/sijax.js"></script>
{# 使用过滤器safe禁止转译sijax_get_js() #}
<script type="text/javascript"> {
{ g.sijax.get_js()|safe }} </script>
</head>
<body>
{# 创建id为my_form的表单 #}
<form id="my_form">
<input type="text" name="textbox" value="textbox 1" />
<input type="text" name="tbx[nested]" value="tbx 2" />
<input type="checkbox" name="cbx" checked="checked" />
</form>
{# 使用Sijax.getFormValues方法获取id为my_form的表单数据 #}
<script type="text/javascript">
var values = Sijax.getFormValues('#my_form');
</script>
{# 使用带参数Sijax.request()方法传递values值 #}
<a href="javascript://" onclick="Sijax.request('say_hi',values);">点击</a>
</body>
</html>
修改my.html模板文件后,启动Flask程序,访问http://127.0.0.1:5000/hello点击后,如下图所示:

这时sijax_argsParameters have data.
注意:When a field in the form is missingnamename or disabled,sijax.getFormValues是无法获取到的.
好了,Flask框架——Flask-Sijax的知识就讲到这里了,感谢观看,下篇文章学习Flask框架——项目可安装化.
公众号:白巧克力LIN
该公众号发布Python、数据库、Linux、Flask、自动化测试、Git等相关文章!
- END -
边栏推荐
猜你喜欢

mongodb打破原则引入SQL,它到底想要干啥?

LeetCode二叉树系列——145.二叉树的后序遍历
![[Advanced ROS] Lecture 11 Robot co-simulation based on Gazebo and Rviz (motion control and sensors)](/img/65/7bd87794ebde510ecfd1b0e4bd4c94.png)
[Advanced ROS] Lecture 11 Robot co-simulation based on Gazebo and Rviz (motion control and sensors)

创意loadingjs特效小点跳跃动画

LeetCode二叉树系列——116.填充每个节点的下一个右侧指针

jsArray array copy method performance test 2207300040

LeetCode二叉树系列——515.最每个树行中找最大值

What is the level of Ali P7?

【VMware虚拟机安装mysql5.7教程】

如何判断自己是否适合IT行业?方法很简单
随机推荐
新一代开源免费的终端工具,太酷了
The path to uniting the programmer: "titles bucket" to the highest state of pragmatic
eclipse连接SQL server数据库「建议收藏」
TaskDispatcher源码解析
cpu / CS 和 IP
cpu/CS and IP
群晖系统安装相关文件分享
ARC117E Zero-Sum Ranges 2
Synology system installation related file sharing
BI-SQL丨WHILE
Flask框架——Sijax
接口自动化框架,lm-easytest内测版发布,赶紧用起来~
jsArray array copy method performance test 2207300040
CF780G Andryusha and Nervous Barriers
简单理解精确率(Precision),召回率(Recall),准确率(Accuracy),TP,TN,FP,FN
UPC2022暑期个人训练赛第19场(B,P)
LeetCode二叉树系列——116.填充每个节点的下一个右侧指针
[论文翻译] Unpaired Image-To-Image Translation Using Cycle-Consistent Adversarial Networks
创意loadingjs特效小点跳跃动画
Flask框架——Flask-Mail邮件