Flask学习笔记

    技术2023-09-29  89

    文章目录

    安装运行访问@app.routeapp.rundebugport render_templatejinja过滤器嵌套

    安装

    创建环境(这个环境讲和同一台机器上的其他python环境隔离)

    conda create -n web python=3.6 #输入y继续 conda activate web pip install flask

    运行

    安装完成后会有一个hello.py文件

    from flask import Flask app=Flask(__name__) @app.route('/') def hello_world(): return 'Hello,World!' app.run()

    然后执行下列命令启动web服务

    python hello.py

    然后会打印一堆日志,并在最后一行显示端口号

    访问

    在浏览器访问时控制台会打印信息

    @app.route

    通过用<和>来将url中变量括起来(和SpringMVC的{}类似)

    @app.route('personinfo/<name>/<birthday>&<gender>') def persioninfo(name,birthday,gender): return '{name},您好!您的生日是{birthday},性别是{gender}.'.format(name=name,birthday=birthday,gender=gender)

    然后通过localhost:5000/personinfo/Bob/19980101&男来访问,所有入参数据类型为字符串

    app.run

    debug

    当debug为True时py文件保存后服务同步更新

    port

    render_template

    通过该函数可以渲染模板并返回,样例如下

    from flask import Flask,render_template app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.errorhandler(404) def page_not_found(error): return render_template('404.html'),404 app.run(debug=True,port=5005)

    上面的模板文件都放在与py文件平级的template目录内

    jinja

    jinja是默认的模板引擎

    控制结构 {% %}赋值结构 {{ }}

    过滤器

    {{ ‘gooD’ | lower}} 将输出good

    safecapitializeloweruppertrimstriptags 去掉HTML标签join 拼接字符串replaceroundint

    嵌套

    在父模板parent中写入

    {% block name %} {% endblock %}

    然后子模版先引入

    {% extends ‘parent’ %}

    然后implement super template里的abstract block

    {% block name %} context {% endblock %}

    这样…的介绍就结束了,今天我们学习了…基本使用,相信大家已经能…,但是…如何才能… 请大家关注…老师的介绍

    Processed: 0.015, SQL: 9