zoukankan      html  css  js  c++  java
  • Python之Flask笔记

    在这里先说一下最开始所经历的一些错误app=Flask(_name_),当初拼写的时候怎么都报错后来发现此处是两个'_'

    配置文件

    app.config.from_object(__name__)  在当前文件中查询配置项

    app.config.from_envvar('FLASKR_SETTINGS', silent=True)    在文件中查询配置现,其中FLASKR_SETTINGS代表环境变量,silent=True代表Flask不关心该环境变量键值是否存在

    @app.route('/')
    def index():
        return 'This is index'
    此处route修饰器把一个函数绑定到一个URL上,@app.route('hello'),这个意思就是http://127.0.0.1/hello

    @app.route('/user<username>')

    def show_user(username):

      return 'My name is %s'%username

    此处route中<username>代表一个参数,在地址栏中输入http://127.0.0.1/user/Sky,网页则会返回My name is Sky

    from flask import url_for

    @app.route('/login')

    def index():return '这是一个新的url'

    print url_for('login')

    此处url_for()来针对一个特定的函数构建一个 URL,在时运行则会print出所构造好的地址地址栏中输入http://127.0.0.1/login即可访问
    为什么你要构建 URLs 而不是在模版中硬编码?这里有三个好的理由:
       1. 反向构建通常比硬编码更具备描述性。更重要的是,它允许你一次性修改 URL, 而不是到处找 URL 修改。
       2.构建 URL 能够显式地处理特殊字符和Unicode转义,因此你不必去处理这些。
       3.如果你的应用不在 URL 根目录下(比如,在 /myapplication 而不在 /),url_for()将会适当地替你处理好。

    放置静态文件时给静态文件生成URL

    url_for('static',filename='style.css')

    这个文件是应该存储在文件系统上的static/style.css

    渲染文件

    from flask import render_template

    @app.route('/hello/')

    @app.route('/hello<name>')

    def hello(name=None):

      return render_template('hello.html',name=name)

    此处将会从templates处查找模版文件hello.html

     请求对象

    from flask import request

    request.method==['GET','POST']

    文件上传

    在HTML表单中设置属性enctype="multipart/form-data",否则浏览器不会传送文件

    from flask import request

    @app.route('/upload',methods=['GET','POST'])

    def upload_file():

      if request.method=='POST'

      f=request.files['file']

      f.save('/uploads'+secure_filename(f.filename))      因为客户端的名称可能会被伪造,所以永远不要相信,传递给secure_filename来打到效果

    COOKIE操作

    读取cookie:

      username=request.cookies.get('username')

    存储cookie:

      from flask import make_response,render_template

      loadc=make_response(render_template())

      loadc.set_cookie('usernmae','the username')

    重定向

    错误重定向

    如果出现出错的话可以定义一个装饰器

    @app.errorhandler(404)    代表没有该文件

    def page_not_found(error):

      return render_tamplater('**.html'),404      此处404是在render_tamplate调用,告诉Flask该页的错误代码是404

    未完待续...

  • 相关阅读:
    数组分割成多个数组
    node-inspector调试工具
    6.17周六随写
    JavaScript设计模式
    JavaScript设计模式
    async源码学习
    Linux信号列表
    php常用Stream函数集介绍
    php进程控制
    php 单例模式与常驻服务
  • 原文地址:https://www.cnblogs.com/lonenysky/p/5073297.html
Copyright © 2011-2022 走看看