We can handle multiple URLs in our application by defining methods in our class. Suppose we want an application where '<application-name>/' opens the main page '<application-name>/second_page' opens another page. To do this in CherryPy we will define two methods in our class, one index(self) to handle the first page and another second_page(self) to handle the second page.
Save the below code in a file named 'multi_url.py'.
import cherrypy
class application:
def index(self):
return "This is the main page of the application."
def second_page(self):
return "This is the second page of the application."
if __name__ == '__main__':
cherrypy.quickstart(application())
Here we can see the methods and the corresponding return values.
Run the code through the Terminal/Command Line as follows:
python3 multi_url.py
Now, if we enter http://localhost:8080/ in the address bar of a browser, the output will be something like this
And if we enter http://localhost:8080/second_page in the address bar the output will be
The URL contains various parts:
http:// which roughly indicates it's a URL using the HTTP protocol.
localhost:8080 is the server's address. It's made of a hostname and a port number.
/second_page is the path segment of the URL. This is what CherryPy uses to locate an exposed method to respond.
CherryPy uses the index() method to handle / by default.
Comments