简体   繁体   中英

How to split body from a post request

I am trying to split the body from a post request, and i am wondering what is the best way to do it. I was thinking on splitting by "&" to extract each parameter, and then by "=" to extract the pair field/value

data1=value&data2=value2

It will split as follows:

data1 value
data2 value2

However, if the data received contains an "&" or an "=", it will not work: the split method interprets that character in the value as a separator, removing it and creating another field. The best example here is a value received in base64. For example, "value" is represented in base64 as dmFsdWU=

data1=dmFsdWU=&data2=value2

It will split as:

data1 dmFsdWU 
data2 value2

Any suggestion on what could i do here? I was thinking on encode the value of the data, so dmFsdWU= is received as dmFsdWU%3D, but i dont know if there is a better solution

Thanks

Use the second parameter of split to limit the splitting:

in_str = "data1=dmFsdWU=&data2=value2"
param_list = [param_expr.split('=', 1) for param_expr in in_str.split('&')]

Result:

[['data1', 'dmFsdWU='], ['data2', 'value2']]

Deficiency

You haven't described your full interpretation grammar: what to do if the first value contains a & . For instance, change your example to

data1=dmFsd&WU&data2=value2

Where you intend

data1 dmFsd&WU
data2 value2

What parsing rules obtain here? Are there restrictions on the field name that will disambiguate this? For instance, if the field name must be alphanumeric, then your parsing job is possible, but becomes a little trickier:

  • Find the first = ; this determines the first field name
  • Find the next & ...
  • Find the next = ; this is the end of the second field name
  • Locate the alphanumeric sequence ending at that latter = ; use this as the second field name.

    You have now determined the two field names; the remaining two strings are the values.


HOWEVER

Note that there are pathological strings the cannot be parsed uniquely into a pair of field/value pairs. Most simply, let's take your given example:

data1=value&data2=value2

Why is this not a single field/value pair?

data1 value&data2=value2

You will run into this any time a value is allowed to contain both & and = .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM