本文首发于个人博客https://kezunlin.me/post/1e37a6/,欢迎阅读最新内容!

tutorial to use python flask jinja templates and a realtime video demo

Guide

Jinja delimiters

The default Jinja delimiters are configured as follows:

{% ... %} for Statements
{{ ... }} for Expressions to print to the template output
{# ... #} for Comments not included in the template output
# ... ## for Line Statements

url_for static(css+image)

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

<img src="{{ url_for('static', filename='images/1.PNG') }}" height="{{query_img_height}}" width="{{query_img_width}}">

You have by default the static endpoint for static files.

will be converted to

<link rel="stylesheet" type="text/css" href="/static/bootstrap/bootstrap.min.css">
<img src="/static/images/1.PNG" height="1799" width="896">

url for static(pass image path)

<h1>Image  {{image_filename}}</h1>
<img src="{{ url_for('static', filename = image_filename) }}" height="{{query_img_height}}" width="{{query_img_width}}">

notice we do't use

filename = {{image_filename}}

image_filename will be passed to html with value images/1.PNG

will be converted to

<h1>Image  images/1.PNG </h1>
<img src="/static/images/1.PNG" height="1799" width="896">

filter

{% set result_count = result_list | length %}

{{ index | string ) }}

filter: length, string

debug html

url_for with params

python code

@app.route('/index')
@app.route('/')
def index():
return 'you are in the index page' @app.route('/questions/<int:question_id>'):
#int has been used as a filter that only integer will be passed
# in the url otherwise it will give a 404 error def find_question(question_id):
return ('you asked for question {0}'.format(question_id))

html page

<a href={{ url_for('index') }}>Index</a>
<a href = {{ url_for('find_question' ,question_id=1) }}>Question 1</a> {% if kline_chart %}
<div class="chart">{{ kline_chart | safe }}</div>
{% endif %}

Realtime Video

index.html

<img src="{{ url_for('video_feed') }}" height="480" width="640">

main.py

#===================================================
outputFrame = None
lock = threading.Lock() # initialize a flask object
app = Flask(__name__) @app.route("/")
def index():
# return the rendered template
return render_template("index.html") def generate():
# grab global references to the output frame and lock variables
global outputFrame, lock # loop over frames from the output stream
while True:
# wait until the lock is acquired
with lock:
# check if the output frame is available, otherwise skip
# the iteration of the loop
if outputFrame is None:
continue # encode the frame in JPEG format
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame) # ensure the frame was successfully encoded
if not flag:
continue # yield the output frame in the byte format
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encodedImage) + b'\r\n') @app.route("/video_feed")
def video_feed():
# return the response generated along with the specific media
# type (mime type)
return Response(generate(),
mimetype = "multipart/x-mixed-replace; boundary=frame")
#=================================================== # start the flask app
args = {"ip":"0.0.0.0","port":8888}
app.run(host=args["ip"], port=args["port"], debug=True,
threaded=True, use_reloader=False)

Example

index

# for web
from flask import Flask,Response,render_template web_params = {
"query_key":"",
"query_segimg_filepath":"",
"query_segmask_filepath":"",
"query_img_height":0,
"query_img_width":0,
"result_list": []
} # initialize a flask object
app = Flask(__name__) @app.route("/")
def index():
global web_params
return render_template("search.html",**web_params) # start the flask app
args = {"ip":"0.0.0.0","port":8888}
app.run(host=args["ip"], port=args["port"], debug=True,threaded=True, use_reloader=False)

index.html

<html>
<head>
<title>Query {{query_key}}</title>
</head>
<body>
<h1>Query Image {{ query_segimg_filepath }} </h1> {#
<img src="{{ url_for('static', filename='images/1.PNG') }}"
height="30"
width="30">
#} <img src="{{ url_for('static', filename = query_segimg_filepath) }}"
height="{{query_img_height}}"
width="{{query_img_width}}">
{#
<img src="{{ url_for('static', filename = query_segmask_filepath) }}"
height="{{query_img_height}}"
width="{{query_img_width}}">
#} {% set result_count = result_list | length %}
<h1>Search Results #{{result_count}}</h1> {% for i in range(0,result_count) %}
{% set item = result_list[i] %}
{% set segimg_filepath = item["segimg_filepath"] %}
{% set segmask_filepath = item["segmask_filepath"] %} {% set img_height = item["height"] %}
{% set img_width = item["width"] %} <h2>Top # {{i}} {{ segimg_filepath }}</h2> <img src="{{ url_for('static', filename = segimg_filepath) }}" height="{{img_height}}" width="{{img_width}}">
{#
<img src="{{ url_for('static', filename = segmask_filepath) }}" height="{{img_height}}" width="{{img_width}}">
#}
{% endfor %} </body>
</html>

Reference

History

  • 20191005: created.

Copyright

最新文章

  1. SQL参数化查询自动生成SqlParameter列表
  2. iOS越狱开发(一)
  3. Atitit.提升语言可读性原理与实践
  4. ceph calamari 监控系统安装 on ubuntu 14.04
  5. 【转】Java-----jar反编译修改重新打包
  6. open(/dev/ietctl, O_RDWR) 参数含义(转载)
  7. 【HTML5】表单属性
  8. Codeforces Round #280 (Div. 2) A B C 暴力 水 贪心
  9. struts2标签详解
  10. struts采用JavaServlet/JSP技术,实现了基于Java EEWeb应用的MVC设计模式的应用框架
  11. js经验1
  12. POJ 3104 Drying(二分答案)
  13. smartforms换页,
  14. Fragment 设置主题
  15. python 在大文件里面删除某一行,比较有效率的方法
  16. thinkpad E480 用户初体验
  17. asp.net core系列 51 Identity 授权(下)
  18. vue项目 使用Hbuilder打包app 设置沉浸式状态栏
  19. 设置sde表空间为自动增长
  20. python3 邮件发送

热门文章

  1. 输出错误long类型
  2. ASP.NET Core开发者指南()
  3. MySQL高级查询之索引创建、删除、增加、修改、慢sql、explain解释sql
  4. C# WPF实用的注册窗体
  5. Python批量更新模块的方法【面试必学】
  6. python单元测试unittest、setUp、tearDown()
  7. .net core控制台程序中使用原生依赖注入
  8. SpringCloud Zuul2.X网关实现服务熔断降级(复制即用)
  9. VSC 创建 Net Core 3.0 版本 WebAPI
  10. ubutu tornado python3.7.5 nginx supervisor 部署web api