the1
the1

Reputation: 47

Passing URL query strings into a function to be added

How would I go about grabbing the values from the URL, a and b, then passing them to the add function? The result should come out to be: {"c": x}, where x is the sum of a and b.

The code:

op = 'add'
a = random.randint(0,10)
b = random.randint(0,10)
/%s?a=%s&b=%s' % (op, a, b)

result = res.json()

if op=='add':
    assert a+b == result['c']

The function:

def add():
    import json
    return json.dumps({'c': ???})

Upvotes: 0

Views: 93

Answers (3)

the1
the1

Reputation: 47

I figured out how to solve my problem! I appreciate all the help, but none of the solutions provided here applied to my question. This is entirely my fault because I worded the question totally different.

Upvotes: 0

Mani
Mani

Reputation: 949

from urlparse import parse_qs, urlparse
import json

def add(a, b):
    return json.dumps({'c': a+b})

url = 'add?a=1&b=1'

q_dict = parse_qs(urlparse(url).query, keep_blank_values=True)
# q_dict = {'a': ['1'], 'b': ['1']}

print add(a=q_dict['a'][0], b=q_dict['b'][0])

Upvotes: 0

Akshat Mahajan
Akshat Mahajan

Reputation: 9846

Use urlparse, a standard library module designed for tasks like these!

urlparse.parse_qs(qs[, keep_blank_values[, strict_parsing]])

Parse a query string given as a string argument (data of type application/x-www-form-urlencoded). Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

The optional argument keep_blank_values is a flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included.

The optional argument strict_parsing is a flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception.

Example:

>>> urlparse.parse_qs('a=1&b=1') # raw query string
{'a': ['1'], 'b': ['1']}

Note that you can parse an entire URL into its components (including a query string) using other functions in urlparse as well.

Upvotes: 1

Related Questions