ai
  • index
  • cursor
  • vector
  • crawl
  • crawl-front
  • DrissionPage
  • logging
  • mysql
  • pprint
  • sqlalchemy
  • contextmanager
  • dotenv
  • Flask
  • python
  • job
  • pdfplumber
  • python-docx
  • redbook
  • douyin
  • ffmpeg
  • json
  • numpy
  • opencv-python
  • pypinyin
  • re
  • requests
  • subprocess
  • time
  • uuid
  • watermark
  • milvus
  • pymilvus
  • search
  • Blueprint
  • flash
  • Jinja2
  • secure_filename
  • url_for
  • Werkzeug
  • chroma
  • HNSW
  • pillow
  • pandas
  • beautifulsoup4
  • langchain-community
  • langchain-core
  • langchain
  • langchain_unstructured
  • libreoffice
  • lxml
  • openpyxl
  • pymupdf
  • python-pptx
  • RAGFlow
  • tabulate
  • sentence_transformers
  • jsonl
  • collections
  • jieba
  • rag_optimize
  • rag
  • rank_bm25
  • Hugging_Face
  • modelscope
  • all-MiniLM-L6-v2
  • ollama
  • rag_measure
  • ragas
  • ASGI
  • FastAPI
  • FastChat
  • Jupyter
  • PyTorch
  • serper
  • uvicorn
  • markdownify
  • NormalizedLevenshtein
  • raq-action
  • CrossEncoder
  • Bi-Encoder
  • neo4j
  • neo4j4python
  • matplotlib
  • Plotly
  • Streamlit
  • py2neo
  • abc
  • read_csv
  • neo4jinstall
  • APOC
  • neo4jproject
  • uv
  • GDS
  • heapq
  • 基本用法
  • 主要优点
  • 参数说明
  • 常见使用场景
    • 1. 在模板中使用
    • 2. 在视图函数中使用
    • 3. 生成带查询参数的URL
    • 4. 生成绝对URL
    • 5. 带锚点的URL
  • 注意事项
  • 蓝图中的url_for

url_for()是Flask框架中一个非常有用的函数,用于构建URL。它可以根据视图函数名或端点(endpoint)生成对应的URL,而不是硬编码URL路径。

基本用法 #

from flask import Flask, url_for

app = Flask(__name__)

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

@app.route('/user/<username>')
def profile(username):
    return f"User {username}"

with app.test_request_context():
    print(url_for('index'))  # 输出: /
    print(url_for('profile', username='john'))  # 输出: /user/john

主要优点 #

  1. 动态URL生成:当路由改变时,不需要手动更新所有硬编码的URL
  2. 处理URL参数:自动处理路径参数和查询参数
  3. 支持外部URL:可以生成绝对路径URL(包含域名)
  4. 处理特殊字符:自动进行URL编码

参数说明 #

url_for(endpoint, **values)

  • endpoint:视图函数名或端点名
  • **values:
    • 路径参数:如username='john'
    • 查询参数:如_external=True生成绝对URL,_anchor='section'添加锚点
    • _method:指定HTTP方法(用于url_for()的某些高级用法)

常见使用场景 #

1. 在模板中使用 #

<!-- 生成链接 -->
<a href="{{ url_for('index') }}">Home</a>
<a href="{{ url_for('profile', username=user.name) }}">Profile</a>

<!-- 生成静态文件URL -->
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">

2. 在视图函数中使用 #

@app.route('/redirect_example')
def redirect_example():
    # 重定向到profile页面
    return redirect(url_for('profile', username='admin'))

3. 生成带查询参数的URL #

url_for('index', page=2)  # 生成: /?page=2

4. 生成绝对URL #

url_for('index', _external=True)  # 生成: http://localhost:5000/

5. 带锚点的URL #

url_for('index', _anchor='contact')  # 生成: /#contact

注意事项 #

  1. 在非请求上下文中使用url_for()需要创建测试请求上下文(如上面的例子所示)
  2. 对于蓝图(blueprint)中的视图函数,端点格式为蓝图名.视图函数名
  3. 如果URL构建失败,Flask会抛出BuildError异常

蓝图中的url_for #

在蓝图中使用时,需要包含蓝图名前缀:

from flask import Blueprint

auth = Blueprint('auth', __name__)

@auth.route('/login')
def login():
    pass

# 使用时
url_for('auth.login')  # 而不是仅仅'login'

url_for()是Flask应用中URL管理的推荐方式,它使应用更加灵活和可维护。

访问验证

请输入访问令牌

Token不正确,请重新输入