Flask Quick Start (1) - Flask Introduction and simple to use

Introduction 1. Flask

Flask is based on a micro and relies Python developer frame and template jinja2 Werkzeug the WSGI and services, essentially for Werkzeug Socket server for receiving a request for http requests and pretreated, then triggers Flask frame, based on the developer frame Flask It provides functionality to request the appropriate treatment, and returned to the user, if you want to return complex content to the user, it needs jinja2 templates to implement processing template, namely: the template and data rendering, character after rendering string is returned to the user's browser.

"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

2. wsgiref simple application of

The simplest Web application is the first HTML file is saved with the good, with an existing HTTP server software, the user receives the request, reads from the HTML file and returns.

If you want to dynamically generate HTML, you need to put these steps to achieve their own. However, acceptance of the HTTP request, parse HTTP request, the HTTP response is sent coolies live, if we ourselves write these underlying code, it has not yet begun to write dynamic HTML, you have to spend a month to read the HTTP specification.

The correct approach is the underlying code is implemented by a dedicated server software, we focus on Python generate an HTML document. Because we do not want access to TCP connections, HTTP request and response format of the original, so the need for a unified interface to implement such a protocol server software, let us concentrate on writing Web services using Python. This interface is WSGI: Web Server Gateway Interface. The wsgiref python module is developed based on wsgi protocol service module

from wsgiref.simple_server import make_server


def mya(environ, start_response):
    print(environ)
    start_response('200 OK', [('Content-Type', 'text/html')])
    if environ.get('PATH_INFO') == '/index':
        with open('index.html', 'rb') as f:
            data = f.read()

    elif environ.get('PATH_INFO') == '/login':
        with open('login.html', 'rb') as f:
            data = f.read()

    else:
        data = b'<h1>Hello Web</h1>'
    return [data]


if __name__ == '__main__':
    myserver = make_server('127.0.0.1', 4000, mya)
    print('监听4000')
    myserver.serve_forever()

3. Flask installation

pip install flask

4. werkzeug Profile

Werkzeug WSGI is a tool kit, he can serve as a low-level libraries Web framework. Here a little talk about, werkzeug not a web server, nor is it a web framework, but rather a tool kit, the official said WSGI is a toolkit that can be used as a low-level libraries Web framework, because it encapsulates a lot better Web what framework, such as Request, Response, etc.

Code Example:

from werkzeug.wrappers import Request,Response

@Request.application
def hello(request):
    return Response('Hello World!')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost',4000,hello)  # 调用run_simple起服务,参数为ip、端口、要执行的对象

5. flask Quick

from flask import Flask
# 实例化产生一个Flask对象
app = Flask(__name__)
# 将‘/’和视图函数index的对应关系添加到路由中
@app.route('/')
def index():
    return 'ok'

if __name__ == '__main__':
    app.run()  # 调用run()方法

Why app.run () method can play services? ? ? In fact, essentially based werkzeug called run_simple ()

app.run () Source

def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
    if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
        from .debughelpers import explain_ignored_app_run
        explain_ignored_app_run()
        return
    if get_load_dotenv(load_dotenv):
        cli.load_dotenv()
        if "FLASK_ENV" in os.environ:
            self.env = get_env()
            self.debug = get_debug_flag()
        elif "FLASK_DEBUG" in os.environ:
            self.debug = get_debug_flag()
    if debug is not None:
        self.debug = bool(debug)
    _host = "127.0.0.1"
    _port = 5000
    server_name = self.config.get("SERVER_NAME")
    sn_host, sn_port = None, None
    if server_name:
        sn_host, _, sn_port = server_name.partition(":")
    host = host or sn_host or _host
    port = int(next((p for p in (port, sn_port) if p is not None), _port))
    options.setdefault("use_reloader", self.debug)
    options.setdefault("use_debugger", self.debug)
    options.setdefault("threaded", True)
    cli.show_server_banner(self.env, self.debug, self.name, False)
    
    from werkzeug.serving import run_simple
    try:
        # 在这里导入并调用了 run_simple 来起服务
        run_simple(host, port, self, **options)  # host、端口
    finally:
        self._got_first_request = False

Guess you like

Origin www.cnblogs.com/863652104kai/p/11599807.html