Method Analysis of Data Transfer to js by python flask Framework

  • 2021-06-28 12:59:09
  • OfStack

This paper gives an example of how the python flask framework implements data transfer to js.Share it for your reference, as follows:

The first step is to understand the data format used for background and front-end interaction.

1 Select JSON as it fits perfectly with js.

Data returned in the background is serialized

Returns serialized data in the view method of the/homepageRecommend route


dict = {"a":1, "b":2}<br data-filtered="filtered">
import json
json.dumps(dict)

2)


from flask import jsonify
jsonify(dict) # In call jsonfiy  Sometimes errors occur because jsonify  Object must be dict

The main difference between the two serialization methods is that the jsonify format is more beautiful.

Deserialize json using jquary at the front end


$.getJSON('/homepageRecommend'
    , function(data) {          //  from Flask Data returned 
      alert(data.a)           //  Browser Pop-up Display   Backend returned dict["a"] Value of, this time is 1
  }
)
//getJSON  Functions have 3 Parameters 
// No. 1 Is the data returned by the backend url
// No. 2 Is to be returned to the server data  Is optional 
// No. 3 Is to deserialize the data obtained   Functions to continue 

Front End Pass Through .get() perhaps .get() perhaps .post() Method sends request, backend uses json.dumps(dict) Returns json data for use in js eval() Method, convert the json data to an js object, then do other processing


$.post("{{ url_for('statistics.HomeRecommend') }}",{"id":a},function(reco_list){
 var reco_list = eval(reco_list)
//do others
})

Another way to transfer data has recently been found in drawing with icharts, which is used in view

return render_template('statistics/numberofuserlogin/login_number.html', result_json = json.dumps(result))

Direct use in js js_object = eval('{{result_json|safe }}') Note 1 | safe filter must be added or the string will be escaped resulting in parsing errors Use this method to transfer data, can render the template at the same time, avoid defining new url to take data

Summary: flask background data to front-end js requires attention to serialization and deserialization

More information refers to https://www.ofstack.com/article/162815.htm

I hope that the description in this paper will be helpful to everyone's Python program design based on the Flask framework.


Related articles: