Web Framework Routing Instance
Different pages are called depending on the user's input URL
Login,logout,home Three page functions are stored in the account.py module
#/user/bin/env python__author__='Wenchong'deflogin ():Print('This is a landing page')deflogout ():Print('This is an exit page')defHome ():Print('This is the homepage')
The web.py file is a framework entry file that implements Web routing through If...elif...else
#/user/bin/env python__author__='Wenchong' fromAccountImportlogin, logout, homedefmain (): URL= Input ("Please enter a URL:") ifURL = ='Login': Login ()elifURL = ='Logout': Logout ()elifURL = ='Home': Home ()Else: Print('404')if __name__=='__main__': Main ()Implementing Web Routing through Reflection
Through web.py can realize user input different content return different page, but if account.py has a lot of page function, then we need to write more elif in web.py, it is obviously unrealistic.
Modify the contents of a web.py
#/user/bin/env python__author__='Wenchong'ImportLogindefmain (): URL= Input ("Please enter a URL:") ifHasattr (Account,'URL'): Func= GetAttr (Account,'URL') func ()Else: Print('404')if __name__=='__main__': Main ()
Hasattr () Checks if there is a zodiac in the account for the corresponding value of the URL variable, and if so, gets the property and executes it, otherwise returns 404
If the URL entered is Account/login, and account.py and web.py are in the same sibling directory
#/user/bin/env python__author__='Wenchong'defmain (): URL= Input ("Please enter a URL:") M,f= Url.split ("/") obj=__import__(m)ifhasattr (obj,f): Func=getattr (Obj,f) func ()Else: Print('404')if __name__=='__main__': Main ()
If account.py and web.py are not in a sibling directory, account.py is in the Lib subdirectory
#/user/bin/env python__author__='Wenchong'defmain (): URL= Input ("Please enter a URL:") M,f= Url.split ("/") #The fromlist parameter is set to True, otherwise only the LIB will be imported and the account will not be importedobj =__import__('lib.'+m, fromlist=True)ifhasattr (obj,f): Func=getattr (Obj,f) func ()Else: Print('404')if __name__=='__main__': Main ()Add
GetAttr (Object,name,default) Gets a property of an object through a string, and returns the default if no Name property is in object
Hasattr (object,name) checks if there is a name attribute in the object, returns True, otherwise False
SetAttr (X,Y,V) is an object that adds an attribute equal to x.y = V
Delattr (x, y) deletes a property of an object, equal to Del x.y
__import__ (name,fromlist= ()) Imports the name module, when name is ' x.y ' and if FromList is empty, only the X is imported
Python Learning-Reflection