"语法错误GraphQL请求"用"&"在查询中

时间:2017-07-23 22:21:17

标签: python python-2.7 graphql

我使用下面这个简单的python代码查询数据库。它适用于所有区域,除了那些带有"&"在名称中,如"拉丁美洲&加勒比&#34 ;.当我点击这些区域时,我得到语法错误。有谁能建议如何解决这个问题?

我的代码:

import requests

def get_data(query):    
    url = "https://API_URL/graphql?query=" + query
    try:
        response = requests.get(url, cert=('xxx.crt', 'xxx.key'),  verify='xxx.crt')
        print("api responds with: HTTP " + str(response.status_code))
    except requests.exceptions.RequestException as e:
        print("-- error getting data from api: " + str(e))
    else:
        data = response.text
        print(data)
        return data


query = '''
query {
  pages(region:"Latin America & Caribbean",
    From:"May 6 2017 00:00:00 GMT+0000 (GMT)", 
    To: "May 7 2017 00:00:00 GMT+0000 (GMT)")
  {
    _id
  }

    }
'''
get_data(query)

错误:

api responds with: HTTP 400
{"errors":[{"message":"Syntax Error GraphQL request (3:48) Unterminated string.\n\n2: query {\n3:   pages(region:\"Latin America \n                                                  ^\n","locations":[{"line":3,"column":48}]}]}

1 个答案:

答案 0 :(得分:1)

&是网址中的保留字符,因此需要进行转义。我相信你可以利用urllib的quote函数来逃避查询字符串中的保留和不安全字符,然后再将其附加到你网址的其余部分。