Flask Quick Start

First, the basic introduction of Flask

Flask is a miniature of the small but excellent Web framework, scalability, built-in components rarely necessary to introduce third-party components to achieve business functions, if you develop a simple project, using Flask relatively quick and easy. If large-scale development projects, the need to introduce a large number of third-party components, then Flask will be more and more like the Django framework. Based wsgi agreement to deploy, use werkzeug module to achieve this agreement, the template system is provided by Jinja2.

"Micro" (micro) does not mean you need to put the entire Web application into a single Python file (although indeed), it does not mean Flask somewhat lacking in features. Micro framework of the "micro" means Flask designed to keep the core simple and easy to expand. Flask will not make too many decisions for you - such as which database to use. Those selected Flask - such as how to use a template engine - it is very easy to replace. By everything other than by your hands. So, Flask can perfect match with you.

By default, the Flask database abstraction layer does not comprise, form validation, or any other variety of libraries capable of existing functions. However, Flask support to add these features to the application with the extension, is the same as Flask itself to achieve. Numerous extensions provide database integration, form validation, upload handling, various open authentication and other functions. Flask may be "tiny", but it is ready to demand complex production environments and put into use.

Second, the initial Flask

1. Start a flask serving three lines of code

from flask import Flask
app = Flask(__name__)
app.run()

Only three lines of code to start a flask services for Django, is completely unable to do.

2. The six lines of code to achieve a "hello world".

from flask import Flask
app = Flask(__name__)

@app.route("/home")
def func():
    return "hello world"
app.run()
# app.route("/home")的源码分析
class Flask(_PackageBoundObject):
    def route(self, rule, **options):
        def decorator(f):
            endpoint = options.pop("endpoint", None)
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator

By looking at flask in the route of the source code examples above also learned that you can write

from flask import Flask

app = Flask(__name__)

def func():
    return "hello world"
# 在flask源码中调用的就是add_url_rule方法,并把url和函数名传进去
app.add_url_rule("/home", view_func=func)
app.run()

3. Request by:

from flask import Flask, request

app = Flask(__name__)

@app.route("/home", methods=("GET", "POST"))
def func():
    if request.method == "GET":
        return "GET请求"
    if request.method == "POST":
        return "POST请求"

app.run()

Django request and is not the same, using by way of introduction
from flask import request

4. Flask response trio

  • return "character string" Response String
  • render_template ( "xx.html", a = b) in response to html pages , parameters need to pass keyword parameters, of course, also possible ** {a: b} break
  • redirect ( "/ index") redirects
from flask import Flask, request, render_template, redirect, Markup

app = Flask(__name__)


@app.route("/home", methods=("GET", "POST"))
def func():
    if request.method == "GET":
        return render_template(
             "./home.html", 
              msg=Markup("<i>我是参数,Markup的作用是不让浏览器转义</i>"))   //响应html页面
    if request.method == "POST":
        return redirect("/index")    //响应重定向


@app.route("/index")
def index():
    return "我是index界面的内容"    //响应字符串

app.run()

home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>我是POST请求</h1>
<h3>我是参数:<br> {{ msg }}</h3>

<form action="" method="post">
    用户:<input type="text" name="username">
    <input type="submit" value="点我提交">
</form>

</body>
</html>

5. Parse request attributes

ps: add knowledge point: _dict_the difference between dir () is:
  • Examples of _dict_stores only instances that are associated with the properties
  • dir () API function is provided Python, dir () function will automatically find all the properties of an object (including inherited from the parent class attributes).
  • One example of a _dict_property is merely a collection of instance attributes of that instance, it does not include all the effective properties of the instance. So if want to get all the valid attributes of an object, use the dir ().
  • dir () function will automatically find all properties of an object, including _dict_attributes. _dict_It is dir () subset, dir () contains _dict_the attributes.
By printing the request object _dict_() or dir () method, we can get all the attributes of the request object class and its parent
request-----> ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', 
'__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 
'__weakref__', '_cached_json', '_get_data_for_json', '_get_file_stream', 
'_get_stream_for_parsing', '_load_form_data', '_parse_content_type', 'accept_charsets', 
'accept_encodings', 'accept_languages', 'accept_mimetypes', 'access_route', 'application', 
'args', 'authorization', 'base_url', 'blueprint', 'cache_control', 'charset', 'close', 
'content_encoding', 'content_length', 'content_md5', 'content_type', 'cookies', 'data', 'date', 
'dict_storage_class', 'disable_data_descriptor', 'encoding_errors', 'endpoint', 'environ', 'files', 
'form', 'form_data_parser_class', 'from_values', 'full_path', 'get_data', 'get_json', 'headers', 
'host', 'host_url', 'if_match', 'if_modified_since', 'if_none_match', 'if_range', 
'if_unmodified_since', 'input_stream', 'is_json', 'is_multiprocess', 'is_multithread', 'is_run_once', 
'is_secure', 'is_xhr', 'json', 'list_storage_class', 'make_form_data_parser', 
'max_content_length', 'max_form_memory_size', 'max_forwards', 'method', 'mimetype', 
'mimetype_params', 'on_json_loading_failed', 'parameter_storage_class', 'path', 'pragma', 
'query_string', 'range', 'referrer', 'remote_addr', 'remote_user', 'routing_exception', 'scheme', 
'script_root', 'shallow', 'stream', 'trusted_hosts', 'url', 'url_charset', 'url_root', 'url_rule', 
'user_agent', 'values', 'view_args', 'want_form_data_parsed']

So many attribute Do not we all need to remember it? ? ? Of course not, it's important to choose one!
request.path // route("/home")
request.url // 全url("http://127.0.0.1:5000/home")
request.data //request解不了的数据全放这里
request.json //传过来的数据是application/json时放在这里
request.form //form表单传过来的数据
request.args //获取url上的参数
request.values //request.form和request.args的数据组,常用于测试

6. Jinja2 use

jinjia2 with the Django template is very similar to the syntax more closely Python, it is very simple to learn

  • {{}} Reference variables and functions
  • %}% {Logic Code
  • Transfer html code to prevent browser -> backend: Markup () front-end: | safe
  • @ App.template_global () function is used to define global
@app.template_global()
def add_sum(*args):
    return sum(args)


@app.route("/home")
def home():
    return render_template("./home.html")

@app.route("/index")
def index():
    return render_template("./index.html") 

# 有了加了@app.template_global()装饰器的函数就相当于给home和index函数的render_template传了一个关键字传参add_sum=add_sum,
# 如果在app中就相当于 它给所有的视图(包括蓝图中的蓝图)都加了add_sum=add_sum
# 如果是在蓝图中,就相当于给当前的蓝图的所有视图加 add_sum=add_sum
# 蓝图的概念在后面的博客会介绍
  • @ App.template_filter () filter
@app.template_filter()
def even(sum,zcy):
    """sum是'|'符号前传过来的值,zcy是':'符号后面传过来的值 """
    if not sum % 2:
        return "偶数"
    else:
        return "奇数"
    print(zcy)

Example front-end:

<p>{{ add_sum(23,6,1234,523,567,34136,132,6,25) | even:'就想告诉你还可以给过滤器传参数' }}</p>
  • extends inherited master
  • Master block defined in the block
  • Components include

Related use as the template and using django jianja2 and not tired

  • macro is used (to know)
{% macro create_tag(na,ty) %}
    <input type="{{ ty }}" name="{{ na }}" value="{{ na }}">
{% endmacro %}
<h1>你往下看</h1>
{{ create_tag("pppssssss","submit") }}

7. session of Use

The flask was stored in the session in the session browser cookies, encrypted session value is serialized string

  • Also requires the use of import Session Flask
    from flask import session

  • When used to store data session if the following error message, the instantiated keys can be provided Flask

    app.secret_key = "encrypted string"

    OK! ! !

    img

  • session values
    session["key"] = value

Guess you like

Origin www.cnblogs.com/zhangchaoyin/p/11917946.html