Suppose, we have an application which performs mathematical operations. So, we need some way to provide operands to those operations and one way to do this is to give parameters in the URL and CherryPy will handle those parameters as arguments for the method being called.
We will write a simple application where '<application-name>/' opens the main page in which the description of mathematical operations in our application is provided, '<application-name>/square' calls the square method and gives square of num and '<application-name>/power' calls the power method and gives num raised to the pow as answer.
Save the below code in a file named 'url_param.py'.
import cherrypy
class application:
def index(self):
return """Method 'square' will take one parameter 'num' and give square of num.<br><br>
Method 'power' will take two parameters 'num' and 'pow' and give num raised to the power pow as answer."""
def square(self, num=2):
return "The value of {} square is {}".format(num, int(num)**2)
def power(self, num=2, pow=2):
return "The value of {} to the power {} is {}".format(num, pow, int(num)**int(pow))
if __name__ == '__main__':
cherrypy.quickstart(application())
Here we can see the methods and the corresponding return values. All parameters are also given a default value in case parameters are provided explicitly.
Notice that here we are first converting the parameters to integers using the int() function. This is because the parameter values sent from the client to our server are strings.
Run the code through the Terminal/Command Line as follows:
python3 url_param.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/square without any parameter in the address bar the output will be
And if we enter http://localhost:8080/square?num=11 with one parameter in the address bar the output will be
Similarly, we can also call our power method with no parameters, one parameter or two parameters. To call the power method with two parameters enter http://localhost:8080/power?num=11&pow=4 in address bar we get output as
In a URL the section after ? is called a query-string. Traditionally, the query-string is used to contextualize the URL by passing a set of (key, value) pairs. The format for those pairs is key=value. Each pair being separated by a & character.
Comments