flask框架实战2

2023-02-27  本文已影响0人  C1R2

1、MTV模型介绍

注意:其中视图View是必须的,其余两项为可选。

2、开发简单网页

使用flask库里的Jinja2模板引擎,调用flask模块里的render_template方法,将静态的html文件传入,同时也可以将数据传输到html文件中显示。此时我们修改一下上述案例代码:

from flask import  Flask,render_template  #导入render_template模块
app=Flask(__name__)

@app.route('/')
def index():    
    return render_template("index.html")   #调用render_template函数,传入html文件参数

if __name__=="__main__":
    app.run(port=2023,host="127.0.0.1",debug=True)

如果这样运行,pycharm终端会提示报错,因为找不到index.html文件。flask框架在使用这个模板函数时,默认去寻找项目文件夹下的templates文件夹里的html文件。因此我们需要先新建一个templates文件夹,然后在里面新建一个html文件,项目结构及内容参考如下:


image.png

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>welcome to 2020</title>
</head>
<body>
   welcome to my webpage
  <hr>
   <p>这是采用render_template模板方法获得的内容:</p>
   <br>
  {{data}}  #显示出传递过来的变量内容
</body>
</html>

如果想通过rendertemplate方法传输数据,在html文件中显示出来,一方面需要在render_template函数中加入数据参数,如data=msg,这里msg为参数值,data为参数名。在html文件中就需要使用jinjia2模板里的数据控制语法:
{% python语句 %}
{{ 变量 }}

上述案例代码修改一下,来测试一下数据传输效果:

from flask import  Flask,render_template
app=Flask(__name__)

@app.route('/')
def index():
    msg="my name is cr!"
    return render_template("index.html",data=msg)  #加入变量传递

if __name__=="__main__":
    app.run(port=2023,host="127.0.0.1",debug=True)
image.png

--参考
https://zhuanlan.zhihu.com/p/104273184

上一篇 下一篇

猜你喜欢

热点阅读