Flask实践:计时器
source link: https://greyli.com/flask-practice-timer/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Flask实践:计时器
Demo体验:计时器 – Hello, Flask!
难度:1
涉及知识点:URL变量
– – – – –
我们经常在一些网站上看到倒计时,比如购物网站上的秒杀倒计时,或是考试网站上的距离高考还剩多少天……
我们今天就用Flask和JavaScript(jQuery)来实现一个在线计时器,具体的User Strory:
- 可以在首页点击不同的时间按钮进入计时
- 计时结束后会有弹窗和铃声提示
- 可以在输入框里输入参数进入相应的计时,比如“34、23s、20m、2h”
可以通过在url里传入时间来开始计时,比如:
项目结构
实现代码
主程序:app.py
计时的功能主要用JavaScript(jQuery)实现,在index.html,传递变量给JavaScript:
另外,在这个APP里,因为表单很小,所以没有使用Flask-WTF。表单部分:
然后在视图函数里,我使用request来获取数据,使用正则表达式验证数据:
下一次会谈一下表单的几种不同的验证方式和一些处理技巧。
完整的实现见源码(链接在底部),欢迎fork和patch(或是star:)。
相关知识点
- URL变量
大部分现代的网站(app)都会有一个美观简洁的URL,比如http://www.example.com/user/kitty。在Flask里,我们通过在URL里设置变量来实现这个功能,比如说上面的URL,对应的路由就是:
这个<variable_name>可以作为参数传递到视图函数里,我们还可以使用Flask提供的转换器,以<converter:variable_name>的形式来转换变量:
下面是Flask支持的转换器:
string accepts any text without a slash (the default) int accepts integers float like int but for floating point values path like the default but also accepts slashes any matches one of the items provided uuid accepts UUID strings使用这个特性,计时器实现了在地址后填入参数就可以进入相应的计时。
相关链接
DEMO:http://timertimer.herokuapp.com/
源码:https://github.com/helloflask/timer-flask
– – – – –
更多关于Flask的优质内容,欢迎关注Hello, Flask! – 知乎专栏。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK