python flask倒计时_Flask实践:计时器
Demo體驗:計時器 - Hello, Flask!
難度:1
涉及知識點:URL變量
- - - - -
我們經常在一些網站上看到倒計時,比如購物網站上的秒殺倒計時,或是考試網站上的距離高考還剩多少天……
我們今天就用Flask和JavaScript(jQuery)來實現一個在線計時器,具體的User Story:可以在首頁點擊不同的時間按鈕進入計時
計時結束后會有彈窗和鈴聲提示
可以在輸入框里輸入參數進入相應的計時,比如“34、23s、20m、2h”
可以通過在url里傳入時間來開始計時,比如:
項目結構
|-Timer-Flask 項目名稱
|-app.py
|-templates/ 模板文件夾
|-index.html
|-static/
|-beep.mp3 計時結束鈴聲
|-favicon.ico 站點圖標
|-style.css
|-js/
|-progressbar.js
|-jquery.min.js
|-venv/ 虛擬環境
實現代碼
主程序:app.py
import re
from flask import Flask, render_template, url_for, redirect, request, flash
app = Flask(__name__)
app.config['SECRET_KEY'] = 'a very secret string'
@app.route('/')
def index():
return redirect(url_for('timer', num=11*60+11))
@app.route('/s')
@app.route('/')
def timer(num):
return render_template('index.html', num=num)
@app.route('/custom', methods=['GET', 'POST'])
def custom():
time = request.form.get('time', 180)
# 使用正則表達式來驗證輸入的字符
m = re.match('\d+[smh]?$', time)
if m is None:
flash(u'請輸入一個有效的時間,例如34、20s、15m、2h')
return redirect(url_for('index'))
if time[-1] not in 'smh':
return redirect(url_for('timer', num=int(time)))
else:
type = {'s': 'timer', 'm': 'minutes', 'h': 'hours'}
return redirect(url_for(type[time[-1]], num=int(time[:-1])))
@app.route('/m')
def minutes(num):
return redirect(url_for('timer', num=num*60))
@app.route('/h')
def hours(num):
return redirect(url_for('timer', num=num*3600))
@app.errorhandler(404)
def page_not_fouond(e):
flash(u'訪問地址出錯了,鼠標放在問號上了解更多: )')
return redirect(url_for('timer', num=244))
計時的功能主要用JavaScript(jQuery)實現,在index.html,傳遞變量給JavaScript:
{% block scripts %}
var Minutes = {{ num }};
{% endblock %}
另外,在這個APP里,因為表單很小,所以沒有使用Flask-WTF。表單部分:
然后在視圖函數里,我使用request來獲取數據,使用正則表達式驗證數據:
@app.route('/custom', methods=['GET', 'POST'])
def custom():
# 設置180為默認值,避免提交空白表單產生400錯誤
time = request.form.get('time', 180)
# 使用正則表達式驗證數據
m = re.match('\d+[smh]?$', time)
if m is None:
flash(u'請輸入一個有效的時間,例如34、20s、15m、2h')
return redirect(url_for('index'))
if time[-1] not in 'smh':
return redirect(url_for('timer', num=int(time)))
else:
type = {'s': 'timer', 'm': 'minutes', 'h': 'hours'}
return redirect(url_for(type[time[-1]], num=int(time[:-1])))
下一次會談一下表單的幾種不同的驗證方式和一些處理技巧。
完整的實現見源碼(鏈接在底部),歡迎fork和patch(或是star:)。
相關知識點URL變量
大部分現代的網站(app)都會有一個美觀簡潔的URL,比如http://www.example.com/user/kitty。在Flask里,我們通過在URL里設置變量來實現這個功能,比如說上面的URL,對應的路由就是:
app.route('/user/')
這個可以作為參數傳遞到視圖函數里,我們還可以使用Flask提供的轉換器,以的形式來轉換變量:
@app.route('/user/')
def show_user_profile(username):
# show the user profile for that user
return 'User%s' % username
@app.route('/post/')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post%d' % post_id
使用這個特性,計時器實現了在地址后填入參數就可以進入相應的計時。
最終效果
- - - - -
更多關于Flask的優質內容,歡迎關注Hello, Flask! - 知乎專欄。
總結
以上是生活随笔為你收集整理的python flask倒计时_Flask实践:计时器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 渐进式框架Vue
- 下一篇: 如何在集群上运行Shark