flask基础

发布于:2025-02-11 ⋅ 阅读:(42) ⋅ 点赞:(0)
from flask import Flask, request

app = Flask(__name__)


# @app.route('/')
# def hello_world():  # put application's code here
#     return 'Hello World!'

@app.route('/')     # 路由 当用户访问特定 URL 时,Flask 会调用对应的视图函数来处理请求
def index():
    return 'Welcome to index!'


@app.route('/about')
def about():
    return 'Welcome to about!'


@app.route('/greet/<name>')  # 括号里可以接收URL中的参数 http://127.0.0.1:5000/greet/wxh  Hello, wxh!
def greet(name):
    return f'Hello, {name}!'


@app.route('/submit',methods=['POST'])
def submit():
    username = request.form.get('username')
    return f'Hello,{username}!'

if __name__ == '__main__':
    app.run(debug=True)

前面几个都比较简单,直接在浏览器输出URL就行,如:

127.0.0.1:5000        显示:Welcome to index!

127.0.0.1:5000/about        显示:Welcome to about!

127.0.0.1:5000/greet/WXH     显示:Hello, WXH!

POST请求这个,可以使用Postman创建POST请求,具体步骤如下:

1.点击“+”

2.选择POST方式

3.在URL 输入框中输入Flask 应用地址,例如 http://127.0.0.1:5000/submit

4.配置请求体,选择x-www-form-urlencoded(x-www-form-urlencoded 是 HTML 表单的默认编码类型,这样配置可以模拟浏览器提交表单的行为)

5.输入key username   value WXH

6.点击右侧 send  按钮 即可看到结果 Hello,WXH!

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')     # 路由 当用户访问特定 URL 时,Flask 会调用对应的视图函数来处理请求
def index():
    return render_template('index.html')    # 展示index.html


if __name__ == '__main__':
    app.run(debug=True)

访问 5000 看到的是 index.html


网站公告

今日签到

点亮在社区的每一天
去签到