1. Introduction Flask Question one: The process of visiting Baidu? A. Client: Send request message, request line, request header, request body B. Server: Parse request message, resolve domain name, route matching distribution find corresponding view function, package, send to client, response header, Response body, Response c. Client: Received a response message, parsed, displayed in the browser 2. Framework: Definition: Encapsulates the core of a code framework for some method functions: jinja2 (Template engine), werkzeug (routing) 3. Virtual Environment thinking: Why build a virtual environment? In practice, in order to not affect the normal operation of two items, the virtual environment is used. How do I create a virtual environment? mkvirtualenv Virtual environment name into the virtual environment? Workon Virtual environment name exits the virtual environment deactivate4. The first program HelloWorld implementation step A. Import module FLASKB. Create Instance Object C. View function D. Bind route, establish contact with view function E. Call the Run method Demo1 hello Worldfrom Flask Import flask# Importing the module app = Flask (__name__, Static_path = "/static", &nbs p;# static access path Static_url_path = "/static", # static access path &NBS P Static_folder = "", # static Access file Template_folder = "" # Template Access folder ) # Create instance Object @app.route ("/") def index (): return "Hello World" # defines a view function associated with a route? If __name__ = "__ main__ ": app.run () # Call the Run method, run the function three ways to load debugging: Remember under the instance objectMake configuration # 1. Configure Class Config (object) with objects: debug = true# for the associated instance object. Config.form_object (Config) # 2. Configure the instance object with a file. Config.from_pyfile ("Config.ini") # 3. The instance object is configured through an environment variable. Config.from_envvar ("Envconfig")? Some of the commonly used can be created directly after the instance object: Instance object. Debug = True Instance object. config["Debug"] = True?? Note: Calling the Run method is a way to pass parameters instance objects. Run (host, post, Debug) 5. How do I set up a route? demo1# implements the route, specifying the path to/index@app.route ("/index") def Index (): return index Adorner parameter # Reference instance note: When routing parameters are passed by default, the string type will be passing, or other type @app.route ("/user/<user_id>") can be specified Def user_info (): return "%s"% user_id think: How do i specify a request mode? By methods to specify the request method, the default is GET request @app.route ("/index", methods=["POST", "GET"]) def index (): return "index" extension: Put: Modify server data pash: Modify the difference between server data two: Put one of the changes after all sent, Pash is the transfer of the modified content delete: Delete server data option: Just go back to head and do not return HEADER6. View Common Logic A. Return JSON data B. Redirect: Url_for Note: If you return a fixed URL, you can not adapt to url_ Forc. Custom status Code #demofrom flask Import Flask, jsonifyfrom flask import jsonfrom flask import redirectfrom flask Import REQUESTF Rom flask import Url_for?app = FlAsk (__name__)? @app. Route ("/") def index (): return "index" @app. Route ("/demo1") def demo1 (): Return "Demo1"? # to add parameters to the route, the format is the < parameter name ># and the view function needs to receive this parameter @app.route ("/user/<int:user_id>") def Demo2 (user_id): return "Demo2%s"% user_id? @app. Route ("/demo3", methods=["POST", "GET"]) def DEMO3 (): return " Demo3%s "% Request.method? @app. Route ("/json ") def Demo4 (): json_dict = { ' name ': "Laowang", "age": + } # using Json.dumps to convert a dictionary to a JSON string # result = Json.dumps (json_dict) # return result # use JSON to convert a string to json.dumps dictionary # result = JSON.L OADs (json_dict) # return result # jsonify specifies the data format of the response content (tell the client what data format I return to you) return Jsonify (json_dict)? @app. Route ('/redirect ') def demo5 (): # redirect back to its own page # Url_ For: takes the route URL corresponding to the specified view function, and can carry parameters # return Redirect (URl_for (' Demo2 ', user_id=123)) # Redirect to Baidu, this time you do not have to write url_for return redirect ('/HTTP/ Www.baidu.com ')? @app. Route ('/demo6 ') def demo6 (): return "Demo6", 3456 # 3456?if __name__ = = ' __main__ ': app.run (port=1245, debug=true)? 7. Regular matching route code implementation Step # import Baseconverterfrom in werkzeug.routing Werkzeug.routing Import baseconverterfrom flask Import flask# Custom Converter # custom Regular converter Class Regexconverter (Baseconverter): def __init__ (self, Url_map, *args): super (Regexconverter, self). __init__ (Url_ MAP) # saves the 1th parameter accepted as a matching rule self.regex = args[0]# adds the converter to the default converter dictionary and specifies The converter uses the name: Reapp = Flask (__name__)? # Add the custom converter to the converter dictionary and specify that the converter uses the name: reapp.url_map.converters[' re '] = regexconverter# Using converters to implement custom matching rules # The rules currently defined here are: 3-digit @app.route ('/user/<re ("[0-9]{3}"):user_id> ') def user_info (user_id): return "user_id is%s"% User_idto_python and To_urlclass listconverter (baseconverter): &NBsp # own definition converter regex = "(\\d+,?) +\\d$ " def To_python (self, value): " "" when farts are assigned to parameters, further processing of parameters is returned to the attempted function "" " & nbsp return value.split (",")? def To_url (self, value): "" "when using Url_for, the parameters passed on the view function are processed and processed so that the route matches" "" result = ', '. Join (str (v) for V in value) return result system comes with 6 kinds of converter DEFA Ult_converters = { ' default ': unicodeconverter, ' string ': &nbs P Unicodeconverter, ' any ': anyconve Rter, ' path ': Pathconverter, ' int ': &NBS P integerconverter, ' float ': floatconverte R, ' uuid ':   Uuidconverter,}8. Exception capture A. Actively throws exception abort (status code) B. ErrorHandler adorner decorate demofrom flask import flaskfrom flask Import Abort?app = Flask (__name__)? App.route ('/') def index (): return ' index '? @app. Route ('/demo1 ') def demo1 (): # abort (404) # Note the error code should be noted at this time the incoming parameters a = 0 b = b/a return "Demo1"? @app. ErrorHandler (404) def Page_not_f Ound (Error): return "pro, page missing"? @app. ErrorHandler (Zerodivisionerror) def zero_division_error (Error): # must pass in a parameter return ' divisor cannot be 0 '? if __name__ = = ' __main__ ': app.run (port=1111, DEBUG=TR UE) 9. Hook function demo1from flask Import Flask?app = Flask (__name__)? @app. Before_first_requestdef before_first_request ( Response): "" "first accesses the function and accepts a parameter inside the function: the response, and the response needs to be returned" "" print (' before_first_request ') return response? @app. Before_requestdef before_request (): "" "" "is called before each request" "" print (' Before_request ')? @app. Teardown_requestdef TeardOwn_request (Error): "" will be executed after the request, if the requested function reported an exception, the specific exception will be passed to the function "" " print (" Teardown_request ")? App.route ('/') def index (): return ' index '? If __name__ = = ' __main__ ': app.run (port=1456)
A preliminary understanding of Python flask