-
Notifications
You must be signed in to change notification settings - Fork 2
Using Query Parameters
An example is probably the easiest way to explain a query string.
http://192.168.1.100/gpio/2?state=off
Everything after the question mark is the query string (state=off). You may also see multiple parameters, like this:
http://192.168.1.100/gpio/2?state=off&time=30
There are two parameters in the URL above (state=off and time=30). They're separated by an ampersand.
By now you're hopefully thinking, "Gee, I bet I could use a URL like this to set GPIO 2 to off after 30 minutes." And you'd be correct. But first you'll need to know how to access the query parameters.
Whenever Thimble encounters a URL like the examples above, it automatically parses the query and adds the key-value pairs to the req dictionary variable. You can access them using the example code below.
@route('/gpio/2')
def control_gpio_2(req):
my_future_gpio_state = req['query']['state']
my_wait_time = req['query']['time']
If you're familiar with html forms, you probably know about GET vs. POST in terms of how the data is sent from the web page to the server. You can configure your function to handle a POST request with just a few changes.
With a POST, the query parameters will arrive in the body of the request. This is easily accessed using req['body'], but the parameters will come as one long string. You'll need to use the function Thimble.parse_query_string()
to split them up into individual parameters.
Here's an example:
@route('/gpio/2', methods=['POST'])
def control_gpio_2(req):
query_string = req['body'] # Because html form POST sends the query string in the body.
query_params = Thimble.parse_query_string(query_string)
my_future_gpio_state = query_params['state']
my_wait_time = query_params['time']