• Flask简单学习


    一:安装

    直接 pip install Flask,就可以安装好了

    二:hello world

    编写一个hello.py

    # coding: utf-8
    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello world'
    
    if __name__ == '__main__':
        app.run()

    然后在python解析器下运行
    $ python hello.py
    * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
    在浏览器上访问 http://127.0.0.1:5000/
    然后就会出现 Hello world

    1:上面有一个route的装饰器告诉Flask什么样的URL访问能触发这个函数
    2: app.run() 这个也可以绑定具体的host和port

    三:路由

    如上面的程序,route() 装饰器把一个函数绑定到了对应的URL上了
    基本用法:

    # coding: utf-8
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_wold():
        return 'Hello world'
    
    if __name__ == '__main__':
        app.run()

    变量规则:
    要给 URL 添加变量部分,你可以把这些特殊的字段标记为 <variable_name> , 这个部分将会作为命名参数传递到你的函数。规则可以用 <converter:variable_name> 指定一个可选的转换器

    # coding: utf-8
    @app.route('/user/<username>')
    def show_user_profile(username):
        # show the user profile for that user
        return 'User %s' % username
    
    @app.route('/post/<int:post_id>')
    def show_post(post_id):
        # show the post with the given id, the id is an integer
        return 'Post %d' % post_id

    构造URL:

    编写一个名为 cons_url.py的程序

    # coding: utf-8
    from flask import Flask, url_for
    app = Flask(__name__)
    @app.route('/')
    def index(): pass
    
    @app.route('/login')
    def login(): pass
    
    @app.route('/user/<username>')
    def profile(username): pass
    
    with app.test_request_context():
        print url_for('index')
        print url_for('login')
        print url_for('login', next='/')
        print url_for('profile', username='John Doe')

    在命令行下运行程序,输出

    $ python cons_url.py
    /
    /login
    /login?next=%2F
    /user/John%20Doe

    HTTP方法:
    默认情况下,路由只回应 GET 请求,但是通过 route() 装饰器传递 methods 参数可以改变这个行为

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            do_the_login()
        else:
            show_the_login_form()

    四:模板渲染

    Flask 配备了 Jinja2 模板引擎
    你可以使用 render_template() 方法来渲染模板

    # coding: utf-8
    from flask import render_template
    
    @app.route('/hello/')
    @app.route('/hello/<name>')
    def hello(name=None):
        return render_template('hello.html', name=name)

    Flask 会在 templates 文件夹里寻找模板。所以,如果你的应用是个模块,这个文件夹应该与模块同级;如果它是一个包,那么这个文件夹作为包的子目录:

    情况 1: 模块:
    /application.py
    /templates
        /hello.html
    
    情况 2: 包:
    /application
        /__init__.py
        /templates
            /hello.html

    更多模板请到:http://docs.jinkan.org/docs/jinja2/

    五:重定向:

    # coding:utf-8
    from flask import Flask, redirect, url_for
    app = Flask(__name__)
    
    @app.route('/index/', methods=['GET', 'POST'])
    def index():
        # return redirect('/login/')
        return redirect(url_for('login'))
    
    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        return "LOGIN"
    
    app.run()

    用  redirect() 函数来进行url重定向

    六:定义错误页面:

    # coding:utf-8
    from flask import Flask, abort, render_template
    app = Flask(__name__)
    
    @app.route('/index/', methods=['GET', 'POST'])
    def index():
        return "OK"
    
    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('page_not_found.html'), 404
    
    app.run()

    用@app.errorhandler(http错误码) 来触发一个函数

    参考:

       http://docs.jinkan.org/docs/flask/
       http://flask.pocoo.org/

  • 相关阅读:
    [資料]VS2008技巧
    [資料]MarshalAs的用法
    MS SQL Server 2000安装不成功的原因
    Zend產品線
    [轉]Flex 开发必备10武器
    [轉]C#中的XML注释
    [轉]onpropertychange事件
    [轉]fckeditor添加自定义按钮
    [資源]Web設計資源以及线框工具
    [轉]JS中showModalDialog 详细使用
  • 原文地址:https://www.cnblogs.com/jiujuan/p/9038982.html
Copyright © 2020-2023  润新知