我有两个Python脚本。一个使用Urllib2 library,一个使用Requests library。
我发现请求更容易实现,但我找不到urlib2的read()
函数的等价物。例如:
...
response = url.urlopen(req)
print response.geturl()
print response.getcode()
data = response.read()
print data
一旦我建立了我的帖子网址,data = response.read()
给了我内容 - 我正在尝试连接到vcloud导演api实例,响应显示了我可以访问的端点。但是,如果我按如下方式使用Requests库.....
....
def post_call(username, org, password, key, secret):
endpoint = '<URL ENDPOINT>'
post_url = endpoint + 'sessions'
get_url = endpoint + 'org'
headers = {'Accept':'application/*+xml;version=5.1', \
'Authorization':'Basic '+ base64.b64encode(username + "@" + org + ":" + password), \
'x-id-sec':base64.b64encode(key + ":" + secret)}
print headers
post_call = requests.post(post_url, data=None, headers = headers)
print post_call, "POST call"
print post_call.text, "TEXT"
print post_call.content, "CONTENT"
post_call.status_code, "STATUS CODE"
....
.... print post_call.text
和print post_call.content
不返回任何内容,即使在请求后调用中状态代码等于200。
为什么我的回复不会从请求中返回任何文本或内容?
答案 0 :(得分:75)
请求与Urlib2的read()
不同。
>>> import requests
>>> response = requests.get("http://www.google.com")
>>> print response.content
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head>....'
>>> print response.content == response.text
True
看起来你正在发出的POST请求没有返回任何内容。 POST请求通常就是这种情况。也许它设置了一个cookie?状态代码告诉您POST完全成功。
答案 1 :(得分:1)
如果将示例图像推送到某个API并想要返回结果地址(响应),则可以执行以下操作:
import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)
答案 2 :(得分:0)
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
结果如下:
键:状态值:成功键:数据值:{'蜡烛': [['2019-11-19T00:00:00 + 0530',11919.45,11958.85,11881.75,11940.1, 0,0],['2019-11-20T00:00:00 + 0530',12004.75,12038.6,11966.05, 11999.1,0,0]]}
如何在Excel中按列和行拆分这些数据?