我正在我的服务器上做一个内部API。 我想将一些 JSON字符串从PHP传输到Python。
在Python上,我有这段代码:
from flask import request
from flask import jsonify
...
@app.route('/database/<string:token>', methods=['POST', 'GET'])
def sync(token):
if token not in VALID_TOKENS:
...
json = request.get_json(force=True)
...
...
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=False, port=6000)
在PHP方面,我有:
$payload = $datafromdatabase;
$payload = json_encode($payload);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload))
);
$result = curl_exec($ch);
但Flask在每次请求时都会回复我:
127.0.0.1 - - [19/Feb/2017 20:08:00] "POST /database/token HTTP/1.1" 400 -
P.S:在Python上,request.data
和request.args
都是None
。
P.P.S。:在Python中使用requests.post(url, json=data)
。