Flask快速入门

Posted zhang_derek

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask快速入门相关的知识,希望对你有一定的参考价值。

flask快速入门

1.1.三种框架比较

Django: 重武器,内部包含了非常多组件:ORM、Form、ModelForm、缓存、Session、中间件、信号等

Flask:短小精悍,内部没有太多组件,第三方组件非常丰富。路由比较特殊,是基于装饰器来实现,但是本质还是通过add_url_rule来实现的

Tornado:异步非阻塞

 

1.2.安装和运行

(1)安装

创建虚拟环境,然后直接安装

mkvirtualenv flask_project

pip install -i https://pypi.douban.com/simple flask

(2)运行

基本使用

from flask import Flask

#实例化flask对象
app = Flask(__name__)

#将\'/\'和函数index的对应关系加到路由中
@app.route(\'/\')
def index():
    return \'Hello World!\'

if __name__ == \'__main__\':
    #监听用户请求
    #如果有用户请求到来,则执行app的__call__方法,app.__call__
    app.run()

浏览器访问:http://127.0.0.1:5000/

 

1.3.快速入门实例

(1)view.py

from flask import Flask,render_template,request,redirect,session,url_for

app = Flask(__name__)
app.debug = True
app.secret_key = \'abcdef\' USERS
= { 1:{\'name\':\'derek\',\'age\':18}, 2:{\'name\':\'tom\',\'age\':20}, 3:{\'name\':\'jack\',\'age\':22}, } @app.route(\'/detail/<int:nid>\',methods=[\'GET\']) def detail(nid): # 没登录不能访问 user = session.get(\'user_info\') if not user: return redirect(\'/login\') info = USERS.get(nid) return render_template(\'detail.html\',info=info) @app.route(\'/index\',methods=[\'GET\']) def index(): #没登录不能访问 user = session.get(\'user_info\') if not user: # return redirect(\'/login\') #根据设置的别名反向生成url url = url_for(\'login11\') return redirect(url) return render_template(\'index.html\',user_dict=USERS) @app.route(\'/login\',methods=[\'GET\',\'POST\'],endpoint=\'login11\') #endpoint起别名 def login(): if request.method == \'GET\': return render_template(\'login.html\') else: user = request.form.get(\'user\') pwd = request.form.get(\'pwd\') if user == \'derek\' and pwd == \'123\': #添加session值 user = session[\'user_info\'] = user return redirect(\'/index\') return render_template(\'login.html\',error=\'用户名或密码错误\') if __name__ == \'__main__\': app.run()

 

(2)templates/login.html

   <h1>用户登录</h1>
    <form method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="登录">
        {{error}}
    </form>

 

(3)templates/index.html

   <h1>用户登录</h1>
<table>
    {% for k,v in user_dict.items() %}
    <tr>
        <td>{{k}}</td>
        <td>{{v.name}}</td>
        <td>{{v[\'name\']}}</td>
        <td>{{v.get(\'name\')}}</td>
        <td><a href="/detail/{{k}}">查看详细</a></td>
    </tr>
    {% endfor %}
</table>

(4)templates/detail.html

    {{info.name}}
    {{info.age}}

 

1.4.配置文件

flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
    {
        \'DEBUG\':                                get_debug_flag(default=False),  是否开启Debug模式
        \'TESTING\':                              False,                          是否开启测试模式
        \'PROPAGATE_EXCEPTIONS\':                 None,                          
        \'PRESERVE_CONTEXT_ON_EXCEPTION\':        None,
        \'SECRET_KEY\':                           None,
        \'PERMANENT_SESSION_LIFETIME\':           timedelta(days=31),
        \'USE_X_SENDFILE\':                       False,
        \'LOGGER_NAME\':                          None,
        \'LOGGER_HANDLER_POLICY\':               \'always\',
        \'SERVER_NAME\':                          None,
        \'APPLICATION_ROOT\':                     None,
        \'SESSION_COOKIE_NAME\':                  \'session\',
        \'SESSION_COOKIE_DOMAIN\':                None,
        \'SESSION_COOKIE_PATH\':                  None,
        \'SESSION_COOKIE_HTTPONLY\':              True,
        \'SESSION_COOKIE_SECURE\':                False,
        \'SESSION_REFRESH_EACH_REQUEST\':         True,
        \'MAX_CONTENT_LENGTH\':                   None,
        \'SEND_FILE_MAX_AGE_DEFAULT\':            timedelta(hours=12),
        \'TRAP_BAD_REQUEST_ERRORS\':              False,
        \'TRAP_HTTP_EXCEPTIONS\':                 False,
        \'EXPLAIN_TEMPLATE_LOADING\':             False,
        \'PREFERRED_URL_SCHEME\':                 \'http\',
        \'JSON_AS_ASCII\':                        True,
        \'JSON_SORT_KEYS\':                       True,
        \'JSONIFY_PRETTYPRINT_REGULAR\':          True,
        \'JSONIFY_MIMETYPE\':                     \'application/json\',
        \'TEMPLATES_AUTO_RELOAD\':                None,
    }
flask配置文件

(1)方式一

app.debug = True

(2)方式二

app.config[\'DEBUG\'] = True

(3)方式三(最常用)

app.config.from_object("settings.DevelopmentConfig")

settings.py

一个父类,其它子类继承,重写父类的某个方法     

class Config(object):
    DEBUG = False
    TESTING = False
    DATABASE_URI = \'sqlite://:memory:\'


class ProductionConfig(Config):
    DATABASE_URI = \'mysql://user@localhost/foo\'


class DevelopmentConfig(Config):
    DEBUG = True


class TestingConfig(Config):
    TESTING = True

 

1.5.路由系统本质

(1)常用路由系统有以下五种

@app.route(\'/user/<username>\')
@app.route(\'/post/<int:post_id>\')
@app.route(\'/post/<float:post_id>\')
@app.route(\'/post/<path:path>\')
@app.route(\'/login\', methods=[\'GET\', \'POST\'])

基本上这五种方式满足大多数需求,还可以自定制正则路由

from flask import Flask, views, url_for
            from werkzeug.routing import BaseConverter

            app = Flask(import_name=__name__)


            class RegexConverter(BaseConverter):
                """
                自定义URL匹配正则表达式
                """
                def __init__(self, map, regex):
                    super(RegexConverter, self).__init__(map)
                    self.regex = regex

                def to_python(self, value):
                    """
                    路由匹配时,匹配成功后传递给视图函数中参数的值
                    :param value: 
                    :return: 
                    """
                    return int(value)

                def to_url(self, value):
                    """
                    使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
                    :param value: 
                    :return: 
                    """
                    val = super(RegexConverter, self).to_url(value)
                    return val

            # 添加到flask中
            app.url_map.converters[\'regex\'] = RegexConverter


            @app.route(\'/index/<regex("\\d+"):nid>\')
            def index(nid):
                print(url_for(\'index\', nid=\'888\'))
                return \'Index\'


            if __name__ == \'__main__\':
                app.run()

b. 自定制正则路由匹配
自定制正则路由

(2)路由系统的本质

from flask import Flask,render_template,request,redirect,session,url_for

app = Flask(__name__)
app.debug = True
app.secret_key = \'abcdef\'

#源码分析
\'\'\'
路由本质,通过看源码分析得出,其本质是通过add_url_rule来实现的

1.decorator = app.route(\'/\',methods=[\'GET\',\'POST\'],endpoint=\'index\')

    def route(self, rule, **options):
        #app对象(即self)
        #rule=/
        #option = methods=[\'GET\',\'POST\'],endpoint=\'index\'
        def decorator(f):
            endpoint = options.pop(\'endpoint\', None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator

2.@decorator
    decorator(index)
\'\'\'

@app.route(\'/\',methods=[\'GET\',\'POST\'],endpoint=\'index\')
def index():
    return \'Hello word\'

def login():
    return \'登录\'

#通过分析源码,路由可以用下面这种方式实现
app.add_url_rule(\'/login\',\'login11\',login,methods=[\'GET\',\'POST\'],)   #第二个参数是别名,第三个参数是视图函数,如果endpoint不写,则默认endpoint=\'视图函数名\'


if __name__ == \'__main__\':
    app.run()

 

1.6.flask之CBV

from flask import Flask,render_template,request,redirect,session,url_for,views

app = Flask(__name__)
app.debug = True
app.secret_key = \'abcdef\'


def auth(func):
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return inner


class IndexView(views.MethodView):
    methods = [\'GET\']
    decorators = [auth, ]

    def get(self):
        return \'Index.GET\'

    def post(self):
        return \'Index.POST\'


app.add_url_rule(\'/index\', view_func=IndexView.as_view(name=\'index\'))  # name=endpoint

if __name__ == \'__main__\':
    app.run()

 

1.7.add_url_role参数介绍

@app.route和app.add_url_rule参数:
            rule,                       URL规则
            view_func,                  视图函数名称
            defaults=None,              默认值,当URL中无参数,函数需要参数时,使用defaults={\'k\':\'v\'}为函数提供参数
            endpoint=None,              名称,用于反向生成URL,即: url_for(\'名称\')
            methods=None,               允许的请求方式,如:["GET","POST"]
            

            strict_slashes=None,        对URL最后的 / 符号是否严格要求,
                                        如:
                                            @app.route(\'/index\',strict_slashes=False),
                                                访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
                                            @app.route(\'/index\',strict_slashes=True)
                                                仅访问 http://www.xx.com/index 
            redirect_to=None,           重定向到指定地址
                                        如:
                                            @app.route(\'/index/<int:nid>\', redirect_to=\'/home/<nid>\')
                                            或
                                            def func(adapter, nid):
                                                return "/home/888"
                                            @app.route(\'/index/<int:nid>\', redirect_to=func)
            subdomain=None,             子域名访问
                                                from flask import Flask, views, url_for

                                                app = Flask(import_name=__name__)
                                                app.config[\'SERVER_NAME\'] = \'wupeiqi.com:5000\'


                                                @app.route("/", subdomain="admin")
                                                def static_index():
                                                    """Flask supports static subdomains
                                                    This is available at static.your-domain.tld"""
                                                    return "static.your-domain.tld"


                                                @app.route("/dynamic", subdomain="<username>")
                                                def username_index(username):
                                                    """Dynamic subdomains are also supported
                                                    Try going to user1.your-domain.tld/dynamic"""
                                                    return username + ".your-domain.tld"


                                                if __name__ == \'__main__\':
                                                    app.run()
        
所有参数

(1)最基本的url几种方式

from flask import Flask,views
app = Flask(__name__)
app.debug = True
app.secret_key = \'abcdef\'


#第一种
@app.route(\'/\',methods=[\'GET\',\'POST\'],endpoint=\'index\')
def index():
    return \'Hello World!\'

def login():
    return \'登录\'

#第二种
app.add_url_rule(\'/login\',\'login\',login,methods=[\'GET\',\'POST\'])




def auth(func):
    def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return inner

#CBV的模式
class DetailView(views.MethodView):
    methods = [\'GET\']
    decorators = [auth, ]

    def get(self):
        return \'Detail.GET\'

    def post(self):
        return \'Detail.POST\'

#第三种
app.add_url_rule(\'/detail\', view_func=DetailView.as_view(name=\'detail\'))  # name=endpoint


if __name__ == \'__main__\':
    app.run()

 

(2)参数defaults

默认值,当URL中无参数,函数需要参数时,使用defaults={\'k\':\'v\'}为函数提供参数

 

 (3)参数strict_slashes=None

#对URL最后的 / 符号是否严格要求,默认为False,如:
@app.route(\'/index\', strict_slashes=False)

#下面两种方式都可以访问
http: // www.xx.com / index / 
http: // www.xx.com / index


#如果设为True
@app.route(\'/index\', strict_slashes=True)

#只能这样访问
http: // www.xx.com / index 

 

(4)redirect_to=None

重定向到指定地址

@app.route(\'/index\',methods=[\'GET\',\'POST\'],endpoint=\'index1\',redirect_to="/index2")
def index():
    return \'公司旧网页\'

@app.route(\'/index2\',methods=[\'GET\',\'POST\'],endpoint=\'index2\',)
def index():
    return \'公司新网页\'

访问:http://127.0.0.1:5000/index会直接重定向到http://127.0.0.1:5000/index2

 

1.8.模板语言

flask的模板语法和Django的语法差不多,下面一个简单实例

Markup等价于Django的mark_safe

前端也是用 |safe

from flask import Flask,render_template,Markup

app = Flask(__name__)
app.debug = True
app.secret_key = \'abcdef\'


def func1(arg):
    return Markup("<input type=\'text\' value=\'%s\' />"%arg)

@app.route(\'/\')
def index():
    return render_template(\'index.html\',func1=func1)

if __name__ == \'__main__\':

    app.run()

index.html

{{func1(\'zhang \')}}     <!--传参数arg  -->

 

 1.9.请求与响应

from flask import Flask
    from flask import request
    from flask import render_template
    from flask import redirect
    from flask import make_response

    app = Flask(__name__)


    @app.route(\'/login.html\', methods=[\'GET\', "POST"])
    def login():

        # 请求相关信息
        # request.method
        # request.args
        # request.form
        # request.values
        # request.cookies
        # request.headers
        # request.path
        # request.full_path
        

以上是关于Flask快速入门的主要内容,如果未能解决你的问题,请参考以下文章

程序猿哥哥带你快速入门Flask框架

基于flask进行微信开发第一部分-flask快速入门

二 Flask快速入门

Flask快速入门(17) — flask_session

Flask快速入门(18) — 信号

Flask之快速入门