Python Flask 返回函数 、带值的函数

发布时间 2024-01-11 13:28:30作者: 悟透

前言全局说明


一、安装flask模块

官方源:

pip3 install flask==2.3.2

国内源:

pip3 install flask==2.3.2 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

以上二选一,哪个安装快用哪个
flask 安装时间 2023-11

更多国内源: https://www.cnblogs.com/wutou/p/17949398


二、引用模块

from flask import Flask

三、启动服务

https://www.cnblogs.com/wutou/p/17949220


四、返回函数

4.1.1文件名:index.py
from flask import Flask, render_template, request

app=Flask(__name__)

def func():
    return '你好'

@app.route('/')
def index():
    if request.method == 'GET':
        ## GET请求
        return render_template('index.html', content = 'Hello Flask', f = func)

if __name__ == '__main__':
    # app.debug = True
    # app.run(host='127.0.0.1',port = 5000)
    app.run(host='0.0.0.0',port = 5000)
4.1.2 文件名:index.html
<html lang="zh-cn">
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    </head>
    <body>
        <h2>{{ content }}</h2>
        {{ f() }}
    </body>
</html>
4.2 访问连接:

http://127.0.0.1:5000

4.3 效果:

image


五、返回函数 带参数

5.1.1 文件名:index.py
from flask import Flask, render_template, request

app=Flask(__name__)

def func(args):
    return '你好' + ' ' + args

@app.route('/')
def index():
    if request.method == 'GET':
        ## GET请求
        return render_template('index.html', content = 'Hello Flask', f = func)

if __name__ == '__main__':
    # app.debug = True
    # app.run(host='127.0.0.1',port = 5000)
    app.run(host='0.0.0.0',port = 5000)
5.1.2 文件名:index.html
<html lang="zh-cn">
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="content-type" />
    </head>
    <body>
        <h2>{{ content }}</h2>
        {{ f("Flask") }}
    </body>
</html>

{{ f("Flask") }} html 里给函数传值 Flask

5.2 访问连接:

http://127.0.0.1:5000

5.3 效果:

image





免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果自负。




参考、来源:
https://www.bilibili.com/video/BV11Y411h71J?p=31