32. Flask 32nd Day: Optimizing the return of JSON data

Source: Internet
Author: User

Then the previous section, we return JSON data via jsonify very convenient

return jsonify ({"code""message": Message})

What data is returned is the specification written by the company interface

Specification of the return value (even if the value is NULL, we must also return the following fields)

{  "code": $,   # status code  "message"  "" ",  # information hint  "data" : {},  # returned data, such as a list of articles, etc. }

Specification of status Codes

£ º Success 401: No authorizations :parameter Error 500: Server error

In front of us, each time we return JSON data we need to write a string "Jsonify ({" Code ": +," message ": Message})" This is a hassle, and there may be a lot of time to return JSON in the late two project. So we can extract it and encapsulate it as a tool.

1, first build a Python package under the project named Utils (Toolkit, the tools of the Future project are written in this area)

2, the new restful.py under the utils.py

 fromFlaskImportjsonifyclassHttpcode (object): OK= 200, Unauth_error= 401Param_error= 400Server_error= 500defResetful_result (code, message, data):returnJsonify ({"Code": Code,"message": Message,"Data":d ATAor{}})

In this way, we can use this when the view returns JSON:

 from Import restful ... return Restful.resetful_result (code=200, message=", data={})

But this is still not convenient, we still need to add 3 parameters. So we continue to transform resetful.py.

 fromFlaskImportjsonifyclassHttpcode (object): OK= 200, Unauth_error= 401Param_error= 400Server_error= 500defResetful_result (code, message, data):returnJsonify ({"Code": Code,"message": Message,"Data":d ATAor {}})defSuccess (message="", Data=None):returnResetful_result (Code=httpcode.ok, Message=message, data=data)defUnauth_error (message="", Data=None):returnResetful_result (Code=httpcode.param_error, Message=message, data=data)defParam_error (message="", Data=None):returnResetful_result (Code=httpcode.param_error, Message=message, data=data)defServer_error (message="", Data=None):returnResetful_result (Code=httpcode.server_error, Message=message, Data=data)

In this way, we just need to use the defined function according to different situations.

Parameters: Code (no longer self-transmitting), message (the success of the state can not be passed, the default is empty), data (not pass this parameter, will automatically be empty dictionary))

The code for the previous section can be written as follows:

 fromUtilsImportrestful ...classResetpwdview (views. Methodview): Decorators= [Login_required]#Change Password also must first login, this is Class View use adorner    defGet (self):returnRender_template ('cms/cms_resetpwd.html')    defpost (self): Resetpwd_form=resetpwdform (Request.Form)ifresetpwd_form.validate (): Oldpwd=Resetpwd_form.oldpwd.data newpwd=Resetpwd_form.newpwd.data User=G.cms_userifUser.check_password (oldpwd): User.password=newpwd db.session.commit ()returnRestful.success ()#you can never preach anything .            Else:                returnRestful.unauth_error ('Original Password Error')#only the first parameter of message        Else: Message=Resetpwd_form.get_error ()returnRestful.param_error (Message)#only the first parameter of message

32. Flask 32nd Day: Optimizing the return of JSON data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.