简体   繁体   English

在Python请求中转义反斜杠

[英]Escaping backslash in Python requests

I'm trying to access an API where one of the parameter has a \\ in it's name ( Axwell /\\ Ingrosso ). 我正在尝试访问其中一个参数的名称中带有\\的API( Axwell /\\ Ingrosso )。

If I access the API using the website API panel directly, I get the results using Axwell /\\\\ Ingrosso . 如果我直接通过网站API面板访问API,则可以使用Axwell /\\\\ Ingrosso获得结果。

The request URL then becomes https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150 然后,请求URL变为https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150

If I try to access the same API endpoint using Python request, I get an empty response. 如果我尝试使用Python请求访问相同的API端点,则会收到一个空响应。

This is what I'm trying 这就是我正在尝试的

r = session.get('https://oauth-api.beatport.com/catalog/3/tracks', 
               params={'facets': 'artistName:Axwell /\\ Ingrosso', 
                       'perPage': 150})

I've also tried using it without the backslash in Python request but even that outputs an empty response. 我也尝试在Python请求中不带反斜杠的情况下使用它,但即使输出一个空响应。 What am I missing here? 我在这里想念什么?

You need to double the backslashes: 您需要将反斜杠加倍

'artistName:Axwell /\\\\ Ingrosso'

or use a raw string literal by prefixing the string literal with an r : 或者通过在字符串文字前加上r使用原始字符串文字:

r'artistName:Axwell /\\ Ingrosso'

In Python string literals, backslashes start escape sequences, and \\\\ signifies an escaped escape sequence, eg a regular backslash character without specific meaning: 在Python字符串文字中,反斜杠开始转义序列, \\\\表示转义的转义序列,例如,没有特殊含义的常规反斜杠字符:

>>> print 'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\ Ingrosso
>>> print 'artistName:Axwell /\\\\ Ingrosso'
artistName:Axwell /\\ Ingrosso
>>> print r'artistName:Axwell /\\ Ingrosso'
artistName:Axwell /\\ Ingrosso

or as encoded URLs produced by requests : 或作为requests产生的编码URL:

>>> import requests
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': 'artistName:Axwell /\\\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'
>>> requests.Request('GET',
...     'https://oauth-api.beatport.com/catalog/3/tracks',
...     params={'facets': r'artistName:Axwell /\\ Ingrosso',
...             'perPage': 150}).prepare().url
'https://oauth-api.beatport.com/catalog/3/tracks?facets=artistName%3AAxwell+%2F%5C%5C+Ingrosso&perPage=150'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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