23

I'm trying to make a simple REST api using the Python bottle app. I'm facing a problem in retrieving the GET variables from the request global object. Any suggestions how to retrieve this from the GET request?

Cœur
  • 32,421
  • 21
  • 173
  • 232
Maanas Royy
  • 1,484
  • 1
  • 15
  • 29

4 Answers4

31

They are stored in the request.query object.

http://bottlepy.org/docs/dev/tutorial.html#query-variables

It looks like you can also access them by treating the request.query attribute like a dictionary:

request.query['city']

So dict(request.query) would create a dictionary of all the query parameters.

As @mklauber notes, this will not work for multi-byte characters. It looks like the best method is:

my_dict = request.query.decode()

or:

dict(request.query.decode())

to have a dict instead of a <bottle.FormsDict object at 0x000000000391B...> object.

Basj
  • 29,668
  • 65
  • 241
  • 451
Nathan Villaescusa
  • 15,601
  • 2
  • 49
  • 54
6

If you want them all:

from urllib.parse import parse_qs

dict = parse_qs(request.query_string)

If you want one:

one = request.GET.get('one', '').strip()
Basj
  • 29,668
  • 65
  • 241
  • 451
f p
  • 2,937
  • 1
  • 24
  • 33
  • or you could just use `request.query.one` – jfs Oct 23 '12 at 21:31
  • 1
    @f p: it returns an empty string as well as your code. The only difference is that request.query.one is always a Unicode string. – jfs Oct 24 '12 at 11:36
3

Can you try this please:

For this example : http://localhost:8080/command?param_name=param_value

In your code:

param_value = request.query.param_name
madkabx
  • 31
  • 2
0

from the docs

name = request.cookies.name
# is a shortcut for:
name = request.cookies.getunicode('name') # encoding='utf-8' (default)
# which basically does this:
try:
    name = request.cookies.get('name', '').decode('utf-8')
except UnicodeError:
    name = u''

So you might prefer using attribute accessor (request.query.variable_name) than request.query.get('variable_name')

Another point is you can use request.params.variable_name which works both for GET and POST methods, than having to swich request.query.variable_name or request.forms.variable_name depending GET/POST.

comte
  • 2,544
  • 2
  • 18
  • 39