Daniel will take you 5 minutes to create a Flask project!

Keywords: Python JSON Lambda pip JQuery

Get ready

Install: pip install flaskFlask

Quick start: http://docs.jinkan.org/docs/flash/quickstart.html "QuickStart"


Rapid construction

Build in the project root directory:

  • webapp package directory, where the flash code is stored. There is a "init. Py" file in the package

  • templates directory to store template files

  • Static directory to store js,css and other static files. Set up the js directory under it and put it into the js files of jquery and echarts

  • app.py entry file


  • Basic composition

  • The directory structure is as follows:


1.#/ webapp /. Py file contents
2.from flask import Flask,jsonify 
3.#Create app
4.app = Flask("myweb") 
5..#Routing and view functions
6.@app.route("/") 
7.def index(): 
8.return "hello flask" 
9. 
10.@app.route("/json",methods=["GET"]) #Multiple methods specified in the list
11.def getjson():     
12.d = {"a":1,"b":2,"c":3}    
13.return jsonify(d) #Mime is application/json
14. 
15.#Print important properties
16.print(*filter(lambda x: not x[0].startswith("__") and x[1],app.__dict__.items()),sep="\n") 
17.print("- "*30) 
18.print(app.url_map) 
19.print(app.template_folder) 
20.print(app.static_folder) 
21.print("- "*30)
  1. Application: create an instance to provide WEB services, which is also the entry of wsgi

  2. View functions: executing the contents of an internal code output response

  3. Route: creating a path to view function mapping through the route decorator

1.#/main.py file
2.from webapp import app 
3. 
4.if __name__ == "__main__": 
5.      app.run("127.0.0.1",port=8080,debug=True)
  • Start the main.py file



blueprint


In Flask, it is basically the mapping between route decorator and view function. If there are many functions, the code structure will be very messy. Blueprint is the modular technology in Flask.

  • New / web/app/books.py blueprint file

1.#/webapp/books.py file
2. 
3.from flask import Blueprint,jsonify,render_template 
4. 
5.bpbooks = Blueprint("booksapp",__name__,url_prefix="/books") 
6.# bpbooks = Blueprint("booksapp",__name__) 
7.@bpbooks.route("/",methods=["GET","POST"]) 
8.def getall():     
9.       books = [         
10.(1,"java",20),        
11.(2,"python",40),         
12.(3,"linux",50)  
13.      ]     
14.return jsonify(books) 
15.# print("= "*30) 
16.# for x in bpbooks.__dict__.items(): 
17.#     print(x)
  • Modify the / webapp / init.py file as follows: register the new blueprint file in the app

1.#/webapp/__init__.py 
2.from flask import Flask,jsonify 
3.from .books import bpbooks 
4. 
5.#Create app
6..app = Flask("myweb") 
7.#Routing and view functions
8.@app.route("/") 
9.def index():    
10.return "hello flask" 
11. 
12.@app.route("/json",methods=["GET"]) #Multiple methods specified in the list
13.def getjson():    
14.d = {"a":1,"b":2,"c":3}     
15.return jsonify(d) #Mime is application/json
16.# Registration blueprint#  
17.app.register_blueprint(bpbooks) 
18.#If the URL "prefix" is given when registering the blueprint in the app, the customized URL "prefix in the blueprint will be invalid
19.app.register_blueprint(bpbooks,url_prefix="/bookss") 
20.#Print important properties
21.print(*filter(lambda x: not x[0].startswith("__") and x[1],app.__dict__.items()),sep="\n") 
22.print("- "*30) 
23.print(app.url_map) 
24.print(app.template_folder)
25.print(app.static_folder) 
26.print("- "*30)
  • After registration, start the / main.py file

Blueprint construction parameters

  • Name, blueprint name, the key registered in the blueprint Dictionary of app

  • import_name, which is used to calculate the path of the blueprint module. It is generally written as _name__

  • Root? Path, specify the path of the blueprint module. If None, use import? Name to calculate it

  • template_folder

  • URL "prefix" specifies the path prefix of the blueprint module. When app.register "blueprint is registered, you can also specify URL" prefix "for the current blueprint, which will overwrite the definition in the blueprint

In particular, the output root path indicates that the blueprint has its own path. Finally, app.register_blueprint(bpbooks,url_prefix="/bookss"),url_prefix must start with / or an error will be reported. The final path is subject to the registered url_prefix


Template


Flask uses the jinja2 template. For an application app, its template is templates under the root directory. The contents of the new index.html/templates/index.html file are as follows

1.<!DOCTYPE html> 
2.<html> 
3.<head>    
4.<meta charset="UTF-8"> 
5.<title>xdd web</title> 
6.</head> 
7.<body> 
8.<h2>Welcome to use flask frame</h2> 
9.<hr> 
10.{% for x in userlist  %} 
11.{{x}} 
12.{% endfor %} 
13.</body> 
14.</html>

Modify the index view function in the / webapp /. Py file, and use the template rendering function

1.from flask import Flask,jsonify,render_template 
2. 
3..#Create app
4.app = Flask("myweb") 
5. 
6.#Routing and view functions
7.@app.route("/index.html") 
8.def index():    
9.return render_template("index.html", userlist=[   
10.    (1, "tom", 20),     
11.    (1, "json", 30),   
12.   ])

The syntax of jinja2 and Django templates are the same. It is not explained here that in the app.jinja ABCD loader property, there are the following statements

1.@locked_cached_property 
2.def jinja_loader(self):   
3.     """The Jinja loader for this package bound object. 
4. 
5.   .. versionadded:: 0.5    
6.         """    
7.if self.template_folder is not None:      
8.      return FileSystemLoader(os.path.join(self.root_path, self.template_folder))

Note: whether it is an app or a bluepoint, it uses its own root path and template path to splice into template path.


You can view the search path of the app.jinja [loader. Searchpath template through app or bluepoint.






Posted by blueman on Fri, 03 Jan 2020 12:51:48 -0800