我无法通过python(Flask)发送http post请求。
这是我的python代码。
import json
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
@app.route("/",methods=['GET','POST'])
def home():
if request.method == 'POST':
#user inputs
value1 = request.form.get('first')
value2 = request.form.get('second')
value3 = request.form.get('third')
#api call
url = 'http://myapiurl.com/ws/spm/spm-general'
payload = {"perfid" : {0}, "section" : {"hostname" : {1}, "iteration" : {2}, "sectionname" : "sysstat_M"}.format(value1,value2,value3)}
r = requests.post(url, data=json.dumps(payload))
#print(r.status_code, r.headers['content-type'])
#print(r.text)
returnData["result"] = json.loads(r.text)
return jsonify(returnData)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
我正在使用FLASK。 我得到的错误是:
payload = {"perfid" : {0}, "section" : {"hostname" : {1}, "iteration" : {2},
"sectionname" : "sysstat_M"}.format(value1,value2,value3)}
AttributeError: 'dict' object has no attribute 'format'
当我在简单的python(没有Flask)中尝试它时,它可以工作,但我无法使用Flask
这是有效的代码:
import json
import requests
url = 'http://myapiurl.com/ws/spm/spm-general'
payload = {"perfid" : 124, "section" : {"hostname" : "10.161.146.94/10.161.146.90", "iteration" : "1", "sectionname" : "sysstat_M"}}
r = requests.post(url, data=json.dumps(payload))
print(r.status_code, r.headers['content-type'])
print(r.text)
答案 0 :(得分:2)
您似乎将dict
与str
混淆了(payload = {
"perfid" : value1,
"section" : {
"hostname" : value2,
"iteration" : value3,
"sectionname" : "sysstat_M"
}
}
方法)。
只需将变量放入字典文字:
<input class="max1" />
<table>
<tr>
<td colspan="5">Deadlift</td>
</tr>
<tr>
<td align="center">
<span class="perc1">75</span>% x 3</td>
<td align="center">
<span class="perc">78</span>% x 2</td>
<td align="center">
<span class="perc">83</span>% x 1</td>
<td align="center">
<span class="perc">85</span>% x 1</td>
</tr>
<tr>
<td class="weight1"></td>
<td class="weight"></td>
<td class="weight"></td>
<td class="weight"></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('input').keyup(function () {
cal(this);
});
});
function cal(obj) {
var cal1, perc1, result;
cal1 = parseFloat(obj.value);
perc1 = parseFloat($('.perc1').text());
result = (cal1*perc1)/100;
$('.weight1').html(result);
}
</script>
答案 1 :(得分:2)
payload = {"perfid" : value1, "section" : {"hostname" : value2, "iteration" : value3, "sectionname" : "sysstat_M"}
format
是string
的函数,请看一下:https://docs.python.org/2/library/functions.html#format