• Flask实用技巧


    1.模拟请求test_request_context() 环境管理器,搭配url_for可以得到每个路由的路径(好像也没啥用)

    使其好像被一个HTTP请求所调用。HTTP请求上下文是调用url_for所必须的环境

    with app.test_request_context(): # .test_request_context()用于告诉解释器为在其作用域中的代码模拟一个HTTP请求上下文,
        # 使其好像被一个HTTP请求所调用。HTTP请求上下文是调用url_for所必须的环境
        ## 模拟HTTP请求上下文test_request_context();url_for参数是route下方的路由函数名,返回的是路由名称
        print(url_for('f_root'))						#例1,输出:/
        print(url_for('f_industry'))						#例2,输出:/industry
        print(url_for('f_industry', name='web'))				#例3,输出:/industry?name=web
        print(url_for('f_book', book_name='Python Book'))	#例4,输出:/book/Python%20Book
    

    全局变量的使用

    app.secret_key = 'SET_ME_BEFORE_USE_SESSION'
    ## 这里其实就用到了session全局变量
    @app.route('/write_session')
    def writeSession():
        # datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        session['key_time']= datetime.now().strftime('%Y-%m-%d %H:%M:%S')		#将当前时间保存在Session中	
        return session['key_time']  			#返回当前时间
     
    @app.route('/read_session')
    def readSession():
        return session.get('key_time')			#获得上次调用writeSession时写入的时间,并返回
    
    @app.route('/1')
    def f():
        session['key_time'] = time.time() # 重新修改key_time键值为时间戳
        return str(session.modified) # 判断本次请求中是否修改过session键值,若果有,则返回true
    

    在html中使用模板变量

     # 模板变量直接在render_template中传过去
     # html中的模板双{},注释在最外边使用 # 注释
     return render_template("template.html",navigation = ['www.baidu.com', 'www.163.com','www.sina.com'],a_variable="First Jinja2" )
    
  • 相关阅读:
    Jqgrid学习
    【转】SpringMVC 流程图
    【转】spring学习之@SessionAttributes
    【转】HttpSessionListener, HttpSessionAttributeListener的用法
    Java会话(session)管理
    hibernate--一对多xxx.hbm.xm配置
    使用Spring容器
    最简单的hibernate入门、配置
    搭建Struts 2的工作环境
    Struts2的常用标签
  • 原文地址:https://www.cnblogs.com/wkhzwmr/p/16407964.html
Copyright © 2020-2023  润新知