初识Flask

摆上中文版官方文档网站:https://flask.github.net.cn/quickstart.html

开启实验之路~~~~~~~~~~~~~

python3 复制代码
from flask import Flask


app = Flask(__name__)
# 使用修饰器告诉flask触发函数的URL,绑定URL,后面的函数用于返回用户在浏览器上看到的内容
# 注意 route() 内的URL后面带`/`和不带`/`是有区别的,Flask是可以区分的,不能混用,否则访问网页时返回是错的
@app.route('/12/')
def helloWorld():
    return 'Hello World!'
    
@app.route('/12')
def test():
    return 'test 12!'


if __name__ == '__main__':
    # run 参数 host="0.0.0.0"代表服务器被公开访问,port=5000设定访问的接口
    app.run(host="0.0.0.0", port=5000)

引入URL变量

通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 converter:variable_name ,可以 选择性的加上一个转换器,为变量指定规则

python3 复制代码
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

转换器的类型:

string (缺省值)接受任何不包含斜杠的文本
int 接受正整数
float 接受正浮点数
path 类似string,但可以包含斜杠
uuid 接受UUID字符串

动态构建URL, url_for()

python3 复制代码
from flask import Flask, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(username)

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

这个只是打印出URL而已,并不会发起请求

使用 HTTP方法

缺省情况下,一个路由只回应 GET 请求。 可以使用 route() 装饰器的 methods 参数来处理不同的 HTTP 方法:

python3 复制代码
from flask import request, Flask

app = Flask(__name__)

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()
    
def do_the_login():
    return "do the loging"

def show_the_login_form():
    return "show the login from"
    
app.run()

静态文件:

动态的 web 应用也需要静态文件,一般是 CSS 和 JavaScript 文件。理想情况下你的 服务器已经配置好了为你的提供静态文件的服务。但是在开发过程中, Flask 也能做好 这项工作。只要在你的包或模块旁边创建一个名为 static 的文件夹就行了。 静态文件位于应用的 /static 中。

使用特定的 'static' 端点就可以生成相应的 URL
url_for('static', filename='style.css')

这个静态文件在文件系统中的位置应该是 static/style.css 。

渲染模板:

使用 render_template() 方法可以渲染模板,你只要提供模板名称和需要 作为参数传递给模板的变量就行了。Flask 会在 templates 文件夹内寻找模板。因此,如果你的应用是一个模块, 那么模板文件夹应该在模块旁边;如果是一个包,那么就应该在包里面(模板参考 Jinja2,https://jinja.palletsprojects.com/en/3.1.x/templates/)

python3 复制代码
from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
相关推荐
happylifetree3 分钟前
Python70:核心语法-函数进阶-案例2
python
王中阳Go32 分钟前
两个入口答案不一致先别调模型:6 行入口口径对账表(附脚本)
人工智能·后端·python·大语言模型·1024程序员节
BK贝壳43 分钟前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节
Sakura_j_h_1 小时前
Python 在定时任务里输出 emoji,UnicodeEncodeError 从哪来
开发语言·字符编码·windows·python·定时任务
码事漫谈2 小时前
消除AI幻觉,普通人能做的五件事
后端
supabc1233 小时前
欧盟电子发票(XRechnung/Peppol/ZUGFeRD)踩坑记:用 Python 不装 Java 跑官方校验规则
xml·python·开源·电子发票·1024程序员节
ZhengEnCi3 小时前
AI Agent工具调用防护层怎么写-一份能直接跑的Python四层拦截实现
python·llm·agent
ZhengEnCi3 小时前
AI Agent工具误调用怎么解决-从参数校验到高危二次确认的四层工程防线
python·llm·agent
金銀銅鐵4 小时前
[Java] 用 GUI 展示 EnumSet 增减元素时的内部变化(下)
java·后端·ai编程
镜子AI4 小时前
镜子AI工程教程:用Python实现关键词布局检查器与语义改写查重(附完整代码)
人工智能·python·microsoft