• flask实现session开发


    要在Flask应用中实现会话(session)开发,你可以使用Flask内置的session模块。以下是一个示例代码,演示在Flask应用中启用和使用会话功能:

    from flask import Flask, session, redirect, url_for, request
    
    app = Flask(__name__)
    app.secret_key = 'your-secret-key'
    
    @app.route('/')
    def index():
        if 'username' in session:
            return f"Hello, {session['username']}! You are logged in."
        else:
            return 'You are not logged in.'
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            session['username'] = request.form['username']
            return redirect(url_for('index'))
        return '''
            
    '''
    @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=True)
    • 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

    在上述示例中,我们首先导入了必要的模块。然后,创建了一个Flask应用实例,并设置了一个密钥作为��话的加密密钥,使用app.secret_key属性进行设置。

    接下来,我们定义了三个路由:

    • /:主页路由,检查会话中是否存在username键。如果存在,欢迎用户并显示其用户名,否则显示用户��登录的消息。

    • /login:登录页面路由,支持GET和POST请求。如果是POST请求,则将用户输入的用户名存储到会话中,并重定向至主页。如果是GET请求,则显示登录表单。

    • request.method == 'POST':用于检查当前请求是否是POST请求。只有在用户提交登录表单时,请求方法才会是POST。

    • session['username'] = request.form['username']:将从登录表单中提交的用户名存储到会话的"username"键中。request.form用于访问POST请求的表单数据,"username"是表单中的输入字段名。

    • return redirect(url_for('index')):重定向至主页路由(“index”)。这里使用redirect()函数来指定重定向的路径,url_for()函数根据路由函数的名称生成该路由的URL。

    • /logout:登出路由,从会话中移除username键,并重定向至主页。

    • def logout()::函数名为logout,它没有参数。

    • session.pop('username', None):这行代码从会话(session)中移除键为"username"的值。session.pop(key, default)用于移除会话中指定键的项,并返回对应的值。如果键不存在,则返回默认值None。

    • return redirect(url_for('index')):重定向到主页路由(“index”)。用户登出后,重定向到主页以展示未登录状态。

    需要注意的是,会话数据默认存储在客户端的cookie中。为了安全起见,您可能会考虑将会话数据保存在服务器端或使用其他加密手段。您可以进一步对会话进行自定义设置以符合您的项目需求。

  • 相关阅读:
    Ubuntu中设置代理的方式
    AI绘画逆着玩火了,敢不敢发自拍看AI如何用文字形容你?
    LLVM(5)ORC实例分析
    GBDT 算法【python,机器学习,算法】
    C#中List、Dictionary、HashSet用法以及区别
    【小巧玲珑】文件太大,怎么办?分卷压缩技术了解下,这才是压缩技术
    版本控制 | 如何有效管理SVN服务器上的多个储存库
    操作系统考研笔记
    【数据结构】关于字典之类的东西
    LeetCode 2760. 最长奇偶子数组:模拟(使用一个变量记录状态)
  • 原文地址:https://blog.csdn.net/weixin_45764245/article/details/134522595