传递参数而不在python3请求中转义 [英] passing parameters without escaping in python3 requests

查看:472
本文介绍了传递参数而不在python3请求中转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Kenneth Retiz提供的出色的请求包来发出Web请求. 请求Github存储库

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

我不知道如何格式化查询参数,使其像这样出来.逗号总是转义到%2C.

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)

谢谢.

推荐答案

当您说我的URL看起来像这样:http://example.site.com/customers?fields=id,first_name,last_name"时,我假设您的意思就是您的URL在浏览器中的样子.关于浏览器如何向您显示URL的重要一点是,为了使阅读更容易,它们将不对URL进行编码以用于显示目的,但是当您访问该URL时,它们实际上会发送编码后的版本.

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.

正如罗伯(Rob)在对您的问题的评论中已经提到的那样,没有充分的理由发送未编码的逗号,但这并不意味着请求不允许这样做,这只会非常困难.

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)

这非常容易出错,因为您在添加自己的参数时没有完全检查任何内容,但这将帮助您实现问题中的要求.它回避了为您做正确的事情的请求,并允许您做自己想做的事情.但是,我强烈建议您进一步阅读高级文档,以了解如何实现通用请求API可能期望的其他所有功能,例如流传输,证书验证等.

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.

这篇关于传递参数而不在python3请求中转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆