Skip to content

Flask Learning Report csd

YagoToasa edited this page Oct 19, 2019 · 1 revision

Debug模式

  • Edit Configuration ⟹ FLASK_DEBUG

Routing

  1. route()`:将函数绑定到URL上

    @app.route('/')
    def index():
        return 'Index'
  2. <converter:variable_name>:在URL中添加变量

    @app.route('/user/<username>')
    def show_user_profile(username):
        # show the user profile for that user
        return "User %s" % username
    • Converter type

      Type Description
      string 任何不包含/的文本
      int 正整数
      float 正浮点数
      path 类似string,可以包含/
      uuid UUID字符串
  3. route('/about/')

    • 使用不带/的URL访问该地址,Flask会自动重定向
    • 可将其看作是一个文件夹
  4. route('/about')

    • 使用带/的URL访问该地址时,会得到一个NOT FOUND错误
    • 可将其看作是一个文件
  5. url_for()

    • 参数1:函数名
    • 关键字参数:任意数目,关键字对应URL中的变量
    • 未知变量将添加到URL中作为查询参数
    • 优点:
      • 便于修改
      • 便于处理特殊字符的转义及Unicode数据
      • 绝对路径,避免相对路径的副作用
  6. HTTP

    • 默认:路由只回应GET请求
    • route('/', methods=['GET', 'POST']):处理不同的HTTP方法

静态文件

  • 一般是CSS和JavaScript文件,通常存放在/static中;
  • 相应的URL:url_for('static', filename='<file-name>')

Rendering Templates

render_template():Flask会在templates文件夹中寻找指定模版

Redirects and Errors

  • redirect()

  • abort()

    • errorhandler()装饰器可以自定义出错页面

      @app.errorhandler(404)
      def page_not_found(error):
        	return render_template('page_not_found.html'), 404  # 404:页面不存在;Default-200:一切正常

Responses

  • 转换规则
返回值 响应
响应对象 --------
字符串 字符串+ 省缺参数
字典 jsonify
元组 (response,status)/(response,headers)/(response, status,headers)
  • Make_response()

    包裹返回表达式,获取响应对象,可以对响应对象进行修改后再返回

Session

  • 允许在不同请求间存储信息;

  • 相当于用密钥签名加密的cookie;

  • 使用session前,必须设置一个密钥,可以使用os.urandom()生成密钥。

Message Flashing

  • 记录请求结束时的消息,并仅允许下一个请求访问。
  • 一般会结合Templates来使用
  • 浏览器及网络服务器对cookie的限制,可能会导致消息闪现失败。

Logging

  • logger

    app.logger.debug('debug-message')
    app.logger.warning('warning-message')
    app.logger.error('error-message')