In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
1. Pain point
With the rapid development of business, there are more and more API interfaces, routing management files from dozens of numbers to hundreds of lines, and every time on the new service, it is necessary to modify the routing file code, which brings a certain risk.
two。 The solution is that since the routing file becomes larger and larger as the business expands, remove the routing file.
The corresponding rules are made, and the route corresponds to the class name according to certain rules through the API file name, and then the corresponding implementation class is automatically imported and registered in the Web framework.
2.1 making rules
The following set of rules is only one of the solutions, you can develop the corresponding rules for the project situation, and then implement the relevant code, but the overall idea is basically the same.
The code directory structure, listing the simple project file directory, takes the flask framework as an example:
App.py is the startup file.
Resources is the API interface code folder.
Services is a function wrapper folder that serves the API interface.
If the project also has dependent files, you can also create other folders separately.
The API interface code of the project is placed under the resources folder, and this folder can only write interface API service code.
The interface name is named with the _ connection word, and the word corresponding to the file name of the class name in the file is written in hump instead.
The import of the class corresponds to the class name through the file name, which automatically maps and registers to the web framework.
Examples of rules are as follows:
As shown in the figure above, there is a hello_world interface and an ab project folder under resources, a hello_world_python interface and a subproject folder testab under ab, and a hello_world_python under testab.
Naming convention for the file name of the interface file:
File names are all lowercase, and multiple words are separated by'_', for example, hello_world.py is named correctly and helloWorld.py is incorrectly named.
The interface class Class in the interface file is named after the file name to hump format, and the first letter is capitalized. For example, the corresponding interface class of hello_world.py is HelloWorld.
For example: hello_world.py
Hello_world_python.py
The route entry file is automatically mapped, and the mapping rules are:
Prefix / project folder [.] / file name
The prefix is the routing prefix of the entire project, which can be defined or not defined. For example, the api-ab project can define the routing prefix of the entire project as ab/.
If there is a project folder under resource, it will be spliced automatically, if not, it will not be read.
For example:
The prefix is empty, and the routes for the three interfaces in the resources above are:
Hello_world.py = > / hello_worldab/hello_world_python.py = = > / ab/hello_world_pythonab/testab/hello_world_python.py = = > / ab/testab/hello_world_python
The routes for the three interfaces in the figure resources above prefixed with ab/, are:
Hello_world.py = > ab/hello_worldab/hello_world_python.py = = > ab/ab/hello_world_pythonab/testab/hello_world_python.py = > ab/ab/testab/hello_world_python about the directory structure in resources, N layers are allowed in the code, but it is recommended that no more than 3 layers are allowed, which is not easy to manage. 2.2 Code implementation
The startup and routing management of many frameworks of python are very similar, so this set of rules is suitable for many frameworks, including flask, tornado, sanic, and japronto. The old web.py is also supported.
Full code address:
Https://github.com/CrystalSkyZ/PyAutoApiRoute
To achieve the underscore naming hump naming function, code demonstration:
Def underline_to_hump (underline_str):''the underlined string is converted to hump form with the initials' 'sub = re.sub (r' (_\ w)', lambda x: x.group (1) [1] .upper (), underline_str) if len (sub) > 1: return sub [0] .upper () + sub[ 1:] upper ()
According to the implementation of string import module functions, code demonstration:
Load the class through the python built-in function _ _ import__ function
Def import_object (name): "Imports an object by name. Import_object ('x') is equivalent to 'import xroom.import_object (' x.y.z') is equivalent to 'from x.y import zoning." If not isinstance (name, str): name = name.encode ('utf-8') if name.count ('.') = 0: return _ import__ (name, None, None) parts = name.split ('.') Obj = _ _ import__ ('. '.join (parts [:-1]), None, None, [parts [- 1]], 0) try: return getattr (obj, parts [- 1]) except AttributeError: raise ImportError ("No module named% s"% parts [- 1]) implements importlib.import_module (name) through importlib module
Both of the above methods are fine, and both methods are tested in the code on github.
Retrieve the resources folder, generate the route map, and import the corresponding implementation class. The code is shown below:
Def route (route_file_path, resources_name= "resources", route_prefix= ", existing_route=None): route_list = [] def get_route_tuple (file_name, route_pre) Resource_module_name): ": param file_name: API file name: param route_pre: route prefix: param resource_module_name: resource module"nonlocal route_list nonlocal existing_route route_endpoint = file_name.split (" .py ") [0] # module = importlib.import_module ('{}. {} '.format (# resource_module_name Route_endpoint)) module = import_object ('{}. {} '.format (resource_module_name, route_endpoint)) route_class = underline_to_hump (route_endpoint) real_route_endpoint = route_pre / {}' .format (route_pre, route_endpoint) format (existing_route) Dict): if real_route_endpoint in existing_route: real_route_endpoint = existing_ route [real _ route_endpoint] route_list.append ((real_route_endpoint, getattr (module) ) def check_file_right (file_name): if file_name.startswith ("_"): return False if not file_name.endswith (".py"): return False if file_name.startswith ("."): return False return True def recursive_find_route (route_path, sub_resource) Route_pre= "): nonlocal route_prefix nonlocal resources_name file_list = os.listdir (route_path) if config.DEBUG: print (" FileList: " File_list) for file_item in file_list: if file_item.startswith ("_"): continue if file_item.startswith ("."): continue if os.path.isdir (route_path + "/ {}" .format (file_item)): recursive_find_route (route_path + "/ {}" .format (file_item)) Sub_resource + ". {}" .format (file_item), "{} {} /" .format (route_pre, file_item) continue if not check_file_right (file_item): continue get_route_tuple (file_item, route_prefix + route_pre, sub_resource) recursive_find_route (route_file_path, resources_name) if config.DEBUG: print ("RouteList:" Route_list) the return route_listget_route_tuple function is used to import a class through a string Routes and classes are added to the array as tuples. The check_file_right function filters illegal files in a folder. The recursive_find_route function uses recursion to find files in resources. The existing_route parameter is to replace the route generated by the new rule with the route that already exists online, so that the old project can also optimize the use of this set of rules. 3. Apply to the project
Take the flask framework as an example, and see the code demonstration in github for the rest of the framework.
Code in app.py
App = Flask (_ _ name__) api = Api (app) # APi route and processing functions exist_route = {"/ flask/hello_world": "/ hello_world"} route_path = ". / resources" route_list = route (route_path, resources_name= "resources", route_prefix= "flask/", existing_route=exist_route) for item in route_list: api.add_resource (item [1]) Item [0]) if _ _ name__ = "_ _ main__": app.run (host= "0.0.0.0", port=int (parse_args.port), debug=config.DEBUG)
After running app.py, the route prints as follows:
RouteList: [('/ hello_world',), ('/ flask/ab/testab/hello_world_python_test',\), ('/ flask/ab/hello_world_python',)]
The first element of the tuple is the route, and the second element is the corresponding implementation class.
Summary:
At this point, through the formulation of certain rules, the liberation route management file scheme is completed. You are welcome to discuss the rest of the better proposals. For more discussion, please follow the technical notes on the official account of Wechat: Tiancheng.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.