Detailed Python recursive query menu and converted to JSON instance code

Source: Internet
Author: User
This article mainly introduced Python recursive query menu and converted to JSON instance, with a certain reference value, interested in small partners can refer to.

Recently need to write a menu in Python, tossing for two or three days to fix, now recorded here, the need for friends can draw on.

Note: The article refers to the non-executable complete code, just extracts the key part of the code

Environment

    • Database: MySQL

    • python:3.6

Table structure


CREATE TABLE ' Tb_menu ' (' id ' varchar (+) NOT NULL COMMENT ' unique identifier ', ' menu_name ' varchar (+) ' DEFAULT NULL COMMENT ' menu name ', ' m Enu_url ' varchar ' default null COMMENT ' menu link ', ' type ' varchar (1) default null COMMENT ' type ', ' parent ' varchar (+) Defau LT null COMMENT ' parent directory id ', ' del_flag ' varchar (1) Not NULL DEFAULT ' 0 ' COMMENT ' Remove flag 0: Do not delete ' 1: ', ' Create_time ' datetime DE FAULT current_timestamp COMMENT ' creation time ', ' update_time ' TIMESTAMP not NULL DEFAULT current_timestamp on update current_times Tamp COMMENT ' Update Time ', PRIMARY KEY (' id ') USING BTREE) engine=innodb DEFAULT charset=utf8 comment= ' Menu table ';

Python code

A Menu object that has a list of submenu references "submenus", type list

Core code


def set_submenus (ID, menus): "" "  according to the parent menu ID passed in, recursively sets the submenu list for each hierarchy parent menu  :p Aram ID: Parent ID  :p Aram menus: submenu list  : Return: If this menu does not have a submenu, returns none; if there is a submenu, return to the submenu list  "" "  # Record submenu list  submenus = []  # Traversing submenu for  m in menus :    if m.parent = = ID:      submenus.append (M)  # submenu of the handle menu cycle again for  Sub in submenus:    MENUS2 = Querybyparent (sub.id)    # There are also submenus    if Len (menus):      Sub.submenus = Set_submenus (sub.id, Menus2)  # submenu list is not empty  if Len (submenus):    return submenus  else: # No submenu gone    return None

Test method


  def test_set_submenus (self):    # level menu    Rootmenus = Querybyparent (") for    menu in Rootmenus:      submenus = Querybyparent (menu.id)      Menu.submenus = Set_submenus (menu.id, submenus)

Note: The basic process is: First Query one-level menu, and then respectively, the ID of the level menu, and the submenu list of this level menu into the Set_submenus method, Recursive submenu list sub-menu settings;

The pass-through menu ID is supported and all sub-menus below the menu are queried. Pass a null character, start the query from the root directory

In the "Rootmenus" object, you can see the complete menu tree structure

Go to JSON

I used the ORM framework is: SQLAlchemy, directly from the database query the menu object, to the JSON will be error. A DTO class needs to be redefined to turn the menu object into a Dto object.

Menudto


Class Menudto ():  def __init__ (self, id, menu_name, Menu_url, type, parent, submenus):    super (). __init__ (    ) self.id = id    self.menu_name = menu_name    self.menu_url = menu_url    self.type = type    self.parent = parent< C9/>self.submenus = submenus  def __str__ (self):    return '%s (id=%s,menu_name=%s,menu_url=%s,type=%s,parent =%s) '% (      self.__class__.__name__, Self.id, Self.menu_name, Self.menu_url, Self.type, self.parent)  __repr = _ _str__

The method of recursively setting a submenu is redefined.


def set_submenudtos (ID, Menudtos): "" "  according to the parent menu ID passed in, recursively sets the submenu list for each hierarchy parent menu  :p Aram ID: Parent ID  :p Aram Menudtos: Submenu list  : return: If this menu does not have a submenu, returns none; if there is a submenu, return to the submenu list  "" "  # Record submenu list  submenudtos = []  # Traversing submenu for  m in Menudtos:    m.name = To_pinyin (m.menu_name)    if m.parent = = ID:      submenudtos.append (m) c13/># the submenu of the handle menu and cycle it again for the  sub in Submenudtos:    menus2 = querybyparent (sub.id)    MenusDto2 = model_list_2_ Dto_list (Menus2, "Menudto (id=", menu_name= ", menu_url=", type= "                     , parent=", submenus= ")")    # and a submenu    If Len (menudtos):      If Len (menusDto2):        Sub.submenus = Set_submenudtos (sub.id, MenusDto2)      else: # No submenu, delete the node        sub.__delattr__ (' submenus ')  # submenu list is not empty  if Len (submenudtos):    return Submenudtos  Else: # No submenu gone    return None

Note:

    1. When a menu does not have a submenu, delete the "submenus" property, otherwise a null value will appear when you go to JSON

    2. The Model_list_2_dto_list method can turn the menu list into a menudto list

    3. To_pinyin is the method of turning Chinese characters into pinyin, so there is no need to pay attention

How the View layer returns JSON


  def get (self): param = Request.args id = param[' id ') # If the ID is empty, the query is from the root directory at the start of the menu Rootmenus = querybyparent (ID) Rootmenudtos = Model_list_2_dto_list (Rootmenus, "Menudto (id=", menu_name= ", menu_url=", type= " ', parent= ', submenus= ') # Sets the submenu for the menu in rootMenuDtos:menu.name = To_pinyin (menu.menu_name) Sub                          Menus = Querybyparent (menu.id) If Len (submenus): Submenudtos = Model_list_2_dto_list (submenus, "Menudto (id=", menu_name= ", menu_url=", type= ", parent=", submenus= ")") Menu.submenus = Set_submenu Dtos (Menu.id, Submenudtos) else:menu.__delattr__ (' submenus ') Menus_json = Json.dumps (Rootmenudtos, default =lambda o:o.__dict__, Sort_keys=true, Allow_nan=false, skipkeys=true) # need to go to the dictionary, otherwise the returned string will have "\" Menus_d ICT = json_dict (Menus_json) return Fullresponse (menus_dict) fullresponsefrom flask import Jsonifydef fullresponse (data= ", msg=", code=0): ifmsg = = ": Return jsonify ({' Code ': Code, ' Data ': Data}) elif data = =": Return jsonify ({' Code ': Code, ' msg ': Msg}) Else:return jsonify ({' Code ': Code, ' msg ': MSG, ' Data ': Data})

Note: The JSON and dictionary meanings in Python are similar, and when the last JSON is returned to the page, it needs to be converted to the Dict type using the Json_dict method, otherwise the returned string will have "\"

Query results

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.