python不支持地址传参_传递参数而不在python3请求中转义

I'm using the excellent requests package by Kenneth Retiz to make web requests.

Requests Github repository

Sometimes I need to pass in parameters that are comma separated, but the commas are not url encoded, i.e. my url would look like this

http://example.site.com/customers?fields=id,first_name,last_name

I can't figure out how to format the query parameters to come out like that. The comma always gets escaped to %2C.

I've tried the following code, but that doesn't work:

params['fields'] = 'id,first_name,last_name'

url = 'http://example.site.com/customers'

ex = requests.get(url, params = params)

Thanks.

解决方案

When you say that "my url would look like this: http://example.site.com/customers?fields=id,first_name,last_name", I assume that you mean that's what your URL would look like in your browser. The important thing about how browsers display the URL to you is that they will, to make it easier to read, unencode the URL for display purposes but when you visit that URL, they actually send the encoded version.

As Rob already mentioned in the comments on your question, there is no good reason to ever send the comma unencoded but that doesn't mean that Requests disallows this, it just makes it very difficult.

With the strong warning taken care of, there is a way to do what you want:

from requests import Session, Request

request = Request('GET', 'https://httpbin.org/get')

prepared = request.prepare()

prepared.url += '?field=id,first_name,last_name'

session = Session()

response = session.send(prepared)

This is highly error-prone because you're adding your own parameters without exactly checking anything but this will help you achieve what you're asking in the question. It side-steps requests doing the right thing for you and allows you to do what you want. I strongly suggest, however, that you read more into the advanced documentation for how to achieve everything else you might expect from the general requests API like streaming, certificate verification, etc.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值