写Flask应用时的一些优雅技巧

借助find_modules,import_string优雅地注册蓝图模块

find_modulesimport_string这两个函数包含在werkzeug.utils工具包中,借助着两个工具函数可以帮助我们在更优雅的给应用注册blueprint模块,尤其是当项目中blueprint模块很多的时候,会节省很多行代码,看起来更加的舒服。

import_string(import_name, silent=False)

import_string 可以通过字符串导出需要导入的模块或对象:

参数

  • import_name:要导入的对象的模块或对象名称
  • silent:如果设置为True,则忽略导入错误,相反则返回None

find_modules(import_path, include_packages=False, recursive=False)

找到一个包下面的所有模块,这对于自动导入所有蓝图模块是非常有用的

参数

  • import_path:包路径
  • include_packages:如果设置为True,会返回包内的子包
  • recursive:是否递归搜索子包

示例代码

blueprints/example.py

# 模块部分
# create  blueprint :)
bp = Blueprint('bp_name', __name__)

app.py

# 注册部分
def register_blueprints(app):
    """Register all blueprint modules"""
    for name in find_modules('blueprints'):
        module = import_string(name)
        if hasattr(module, 'bp'):
            app.register_blueprint(module.bp)
    return None

使用Flask中的flash闪存传递反馈信息

flask的闪存系统主要是用来想用户提供反馈信息。内容一般是对用户上一次请求中的操作给出反馈。反馈信息存储在服务端,用户可以在本次(且只能在本次)请求中访问上一次的反馈信息,当用户获得了这些反馈信息以后,就会被服务端删除。Flask为jinja2开放了一个get_flashed_messages(with_categories=False, category_filter=[])函数来获取上一次的闪存信息,这个函数可以直接在模板中使用。

参数

  • with_categories:True返回元祖,False返回消息本身
  • category_filter:过滤分类关键词(字符串或列表)

后台当请求结束准备返回的时候,使用flash(message, category='message')函数来为下次请求保存一条反馈信息。

参数

  • message:信息文本
  • category:自定义分类关键词

官方示例代码">官方示例代码

使用Flask中内置日志系统发送错误日志邮件

Flask使用python内置的日志系统,它实际上可以发送错误邮件。

示例代码:

ADMINS = ['yourname@example.com']
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler('127.0.0.1', #邮件服务器
                               'server-error@example.com', #发件人
                               ADMINS, #收件人
                               'YourApplication Failed') #邮件主题
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)

还可以更进一步,将错误日志格式化,方便阅读:

from logging import Formatter
mail_handler.setFormatter(Formatter('''
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
'''))

关于SMTPHandler的介绍,访问官网SMTPHandler手册

提前中断请求返回错误码,并定制相应错误页面

在Flask中我们能够用redirect()函数重定向用户到其它地方。还能够用 abort() 函数提前中断一个请求并带有一个错误代码。

示例代码

from flask import abort, redirect, url_for

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

@app.route('/login')
def login():
    abort(404)
    this_is_never_executed() # 永远不会被执行到

配合Flask提供的 errorhandler() 装饰器定制自己的相应错误界面

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

注意到 404 是在 render_template() 调用之后。告诉 Flask 该页的错误代码应是 404 , 即没有找到。``

posted on   不要挡着我晒太阳  阅读(363)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示