python 发送带有多个同名参数的http请求

标签 python forms dictionary post request

我需要使用 Python 的 POST 方法将一个简单的表单发送到远程服务器。 这种形式有点奇怪...有些字段名称重复而不使用 [],而只传递 key=value 对(这是必需的,否则服务器端的过程将无法工作!)。

下面是原始表单的示例:

  <form method="post" action="/remote/test.php">
    <input type=hidden name="value01" value="7777" size="12" maxlength=20>
    <input type="text" name="value02" value="123456789">
    <input type="text" name="value03" value="A1234">
    <input type="text" name="value04" value="B5678">
    <input type=submit value="value05 " class="button">
    <input type="hidden" name="VALUE00" value="9999">
    <input type=hidden name="VALUE99"value="09.01.2015 14:52:40">
    <input type="hidden" name="LIST" value="D0000000033039">
    <input type="hidden" name="LIST" value="D0000000033039">
    <input type="hidden" name="LIST" value="C0000000032032">
    <input type="hidden" name="LIST" value="X0000000031820">    
  </form>

我使用“请求”,根据文档,我可以传递一个字典来发送帖子参数。 所以我实现了下面的代码。填充 sourceDataList 变量的实际数据是从带有 Windows EOL (CR+LF) 的文本文件中读取的,因此为了“模拟”本示例的文件,我编译了一个列表,其中包含一些与存在于中的实际值类似的值。文件

import re

sourceDataList = [
 '2017-12-20 08:59:17;Value01\r\n',
 '2017-12-20 08:59:18;Value02\r\n', 
 '2017-12-20 08:59:20;Value03\r\n',
 '2017-12-20 08:59:21;Value04\r\n'
]
dataList = [];
for line in sourceDataList:
  dataList.append({'RESULT' , re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())});

print dataList;

问题从这里开始..当我打印 dataList 时,我发现数据以一种奇怪的方式“混合”..有时键和值之间存在交换!

例如,上面的代码产生以下结果:

[
 set(['Value01', 'RESULT']), 
 set(['RESULT', 'Value02']), 
 set(['RESULT', 'Value03']), 
 set(['Value04', 'RESULT'])
]

我哪里出错了?

- 更新 1 -

我的目的是创建一个可以与“请求”一起使用的字典。 如果我使用上面设置的调用按预期工作并将数据发送到服务器,但顺序错误(某些键和值颠倒)

如果我使用像这样的真正的字典(请注意,现在我使用 : 代替 , ):

  for line in sourceDataList:
      dataList.append({'RESULT' : re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())});

并将其用作“请求”的参数:

r = requests.post(url, data=dataToSend);

我收到错误:

  File "test.py", line 46, in <module>
    r = requests.post(url, data=dataToSend);
  File "C:\Python27\lib\site-packages\requests\api.py", line 112, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 58, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 494, in request
    prep = self.prepare_request(req)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 437, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python27\lib\site-packages\requests\models.py", line 308, in prepare
    self.prepare_body(data, files, json)
  File "C:\Python27\lib\site-packages\requests\models.py", line 499, in prepare_body
    body = self._encode_params(data)
  File "C:\Python27\lib\site-packages\requests\models.py", line 97, in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: need more than 1 value to unpack

最佳答案

在这里,您将数据存储为 setPython 中的集合本质上是无序的。 {a, b}(注意此处的逗号 ,)是 set< 的语法。也许您想将其存储为 dict (如果您希望它作为键值对),其语法为 {a: b} (请注意此处的冒号 : 而不是 , )。或者,也许您可​​以将其存储为 tuple也是。

例如:

import re

sourceDataList = [
     '2017-12-20 08:59:17;Value01\r\n',
      '2017-12-20 08:59:18;Value02\r\n',
      '2017-12-20 08:59:20;Value03\r\n',
      '2017-12-20 08:59:21;Value04\r\n'
]

# --- Using Dictionary ---
dataList = []
for line in sourceDataList:
    dataList.append({'RESULT' : re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())})

# --- Using tuple ---
dataList = []
for line in sourceDataList:
    dataList.append(('RESULT', re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())))

以下是获得相同结果的单行代码:

# For Dictionary 
dataList = [{'RESULT' : re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())} for line in sourceDataList]

# For Dictionary 
dataList = [('RESULT', re.sub('[^A-Za-z0-9]+', '', line.split(';')[1].strip())) for line in sourceDataList]

以下是您将收到的结果示例:

# --- For Dictionary ---
[{'RESULT': 'Value01'}, {'RESULT': 'Value02'}, {'RESULT': 'Value03'}, {'RESULT': 'Value04'}]

# --- For tuple ---
[('RESULT', 'Value01'), ('RESULT', 'Value02'), ('RESULT', 'Value03'), ('RESULT', 'Value04')]

关于python 发送带有多个同名参数的http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060582/

相关文章:

Python定时器回调方法

python - 正确使用 numpy searchsorted 例程

delphi - 在delphi中禁用窗体大小调整

angular - 如何针对本质上动态的 JSON 创建 Angular FORM?

python - 简化 Python 中多重哈希的使用

python - 属性错误 : 'str' object has no attribute 'items'

python - functools.partial 以及它如何组成非关键字参数

python - 基于其他数据帧中的行和列信息索引数据帧

javascript - 如何从 ng-repeat 中删除特定元素?

c# - 从字符串中读取字符并计算每个字符