flask study notes 1

Flask is a micro framework developed based on Python and relying on jinja2 templates and Werkzeug WSGI services. For Werkzeug, it is essentially a Socket server, which is used to receive http requests and preprocess them, and then trigger the Flask framework. Developers are based on the Flask framework. The provided function processes the request accordingly and returns it to the user. If you want to return complex content to the user, you need to use the jinja2 template to process the template, that is: render the template and data, and render the rendered characters. The string is returned to the user's browser.

"Micro" doesn't mean you need to cram your entire web application into a single Python file (though you can), nor does it mean that Flask is lacking in functionality. The "micro" in microframework means that Flask aims to keep the core simple and easy to extend. Flask doesn't make many decisions for you - like what database to use. And those that Flask chooses—such as which template engine to use—are easy to replace. Everything beyond that is up to you. In this way, Flask can work perfectly with you.

By default, Flask doesn't include a database abstraction layer, form validation, or any other functionality that many libraries already do. However, Flask supports extensions to add these features to applications, just as Flask itself does. Numerous extensions provide database integration, form validation, upload handling, various open authentication technologies, and more. Flask may be "tiny", but it's ready for production in demanding environments.

 

tool

"""
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple

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

if __name__ == '__main__':
    # When the request is called, automatically execute: hello()
    run_simple('localhost', 4000, hello)
"""


from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple

class Foo(object):
    def __call__(self, *args, **kwargs):
        return Response('Hello World!')

if __name__ == '__main__':
    # When the request is called, automatically execute: hello()
    obj = Foo()
    run_simple('localhost', 4000, obj)

 install flask

pip3 install flask

basic use

  

"""
pip install flask
pip3 install flask
"""

from flask import Flask
# 1. Instantiate the Flask object
app = Flask('xxxx')

"""
1. Execute app.route('/index') and get the return value xx
2.
    @xx
    def index():
        return 'Hello World'
3. Execute index = xx(index)
Nature:
    {
        '/index': index
    }
"""
@app.route('/index')
def index():
    return 'Hello World'


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

1 The use of decorators, the definition of template template template_folder='templates' static_folder='static' The default path is also this template file and static file

2 methods=["GET","POST"]

3 The use of the default session is to store secret_key='****asdasds**' in the encrypted cookie of the browser and write one end of the string 

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

app = Flask('xxxx',template_folder="templates")
app.secret_key = 'as923lrjks9d8fwlkxlduf'


def auth(func):
    @functools.wraps(func)
    def inner(*args,**kwargs):
        user_info = session.get('user_info')
        if not user_info:
            return redirect('/login')
        return func(*args,**kwargs)
    return inner


"""
{
    /order: inner函数, name: order
    /index: inner function, name: index
}
"""

@app.route('/order',methods=['GET'])
@auth
def order():
    user_info = session.get('user_info')
    if not user_info:
        return redirect('/login')

    return render_template('index.html')


@app.route('/index',methods=['GET'])
@auth
def index():
    return render_template('index.html')


@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == "GET":
        return render_template('login.html')
    else:
        user = request.form.get('user')
        pwd = request.form.get('pwd')
        if user == 'alex' and pwd == '123':
            session['user_info'] = user
            return redirect('/index')
        # return render_template('login.html',msg = "Incorrect username or password",x = 123)
        return render_template('login.html',**{'msg':'username or password is incorrect'})

@app.route('/logout',methods=['GET'])
def logout():
    del session['user_info']
    return redirect('/login')
if __name__ == '__main__':
    app.run()

flask preparation stage

   app = Flask(__name__)

    Instantiate the Flask object

  @app.route('/index')

  

 

    Save the routing rules to the Map class

 

 

  The run() method is executed, the server side of the socket starts to run, waiting for the user to connect

flask run phase

  The entry point of flask's operation is the __call__ method

  

 

   Then start executing the view function

 configure

s1.py
	app.config.from_object('settings.TestingConfig')

settings.py
	class BaseConfig(object):
		DEBUG = False
		SESSION_REFRESH_EACH_REQUEST = True

	class ProConfig(BaseConfig):
		pass

	class DevConfig(BaseConfig):
		DEBUG = True

	class TestingConfig(BaseConfig):

 routing system

    - Add the essence of routing
@app.route('/index')
def index():
    return "index"


def order():
    return 'Order'
app.add_url_rule('/order', None, order)



FBV:
    @app.route('/index')
    def index():
        if 
        return "index"
        
    def order():
        return 'Order'
    app.add_url_rule('/order', None, order)
CBV:
    class X1View(views.MethodView):
        methods = ['GET','POST']
        decorators = [auth, ]

        def get(self):
            return 'x1.GET'

        def post(self):
            return 'x1.POST'


    app.add_url_rule('/x1', view_func=X1View.as_view(name='x1'))  # name=endpoint

 

 

    

Source code process
    a. Generate routing relationship
        [
            Rule('index', function),
            Rule('index', function),
            Rule('index', function),
            Rule('index', function),
        ]

    b. User request comes
        - Get user U request and match it
         - place ctx (the object that encapsulates all data related to the request) to a "special location"
        
    c. Execute the view function

    d. Respond to the function return value to the user

    e. Remove ctx in "special position".

 template file

 1 import functools
 2 from flask import Flask,render_template,request,redirect,session,Markup
 3 
 4 app = Flask('xxxx',template_folder="templates")
 5 app.secret_key = 'as923lrjks9d8fwlkxlduf'
 6 
 7 @app.template_global()
 8 def sb(a1,a2):
 9     return a1+a2
10 @app.template_filter()
11 def db(a1,a2,a3):
12     return  a1+a2+a3
13 def fffff(value):
14     return Markup("<input type='text' value=%s>"%(value))
15 
16 @app.route('/index',methods=['GET'])
17 def index():
18     context = {
19         'k1': 'v1',
20         'k2': [11, 22, 33],
21         'k3':{
22             'name': 'oldboy',
23             'age': 56
24         },
25         'k4': fffff
26     }
27     return render_template('index.html',**context)
28 
29 
30 if __name__ == '__main__':
31     app.run()
template app

 

{%extends 'layout.html'%}
{%block content%}
<h2>index</h2>
    <div>
        {%include 'sakula.html'%}
    </div>
    <div>
       {{k4 ('hebe')}}
   </div>
   <div>
       {{k1}}
   </div>
   <div>{{k2}}</div>
   <div>
       {% for k,v in k3.items()%}
            {{k}} - {{v}}
       {%endfor%}
   </div>
   <div>
       {{k3.name}}
       {{k3['name']}}
       {{k3.get('name')}}
   </div>
   <div>
       Global function: {{sb(1,2)}}
       Global function 2: {{1|db(2,3)}}
   </div>
{%endblock%}
template html

 


  

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324653516&siteId=291194637