我们正在创建一个小项目,其中我们将 flask 作为前端和基于 reSTLet 的 Web 服务。
我们尝试将登录数据作为 JSON 从 flask 发送到 reSTLet:
def login():
error = None
if request.method == 'POST':
payload = {'username' : request.form['username'], 'password' : request.form['password']}
headers = {'Content-Type': 'application/json'}
req = requests.post(WEBSERVICE_IP + '/login', data=json.dumps(payload), headers=headers)
(...)
基于 Flask 的网站正在大声疾呼:
ValueError: No JSON object could be decoded
我们不知道如何调和 flask 和 reSTLet 之间的通信。
编辑(格林威治标准时间 22-04 晚上 10:08): 我发现响应是:
<html>
(...)
Unsupported Media Type
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method
(...)
</html>
编辑(22-04 11:26pm GMT): 我仍然不确定为什么,但我认为它可能是 JSON 格式的东西。更正我的代码以便发送正确的 JSON(说 JSONLint)后,我仍然收到相同的消息。有人知道如何在 Python 中创建 JSONObject 吗? WebService 有方法:
@Post("json")
public JSONObject verifyAccount(JSONObject dane){
编辑(格林威治标准时间 23-04 晚上 7:26): 好的。所以我们几乎可以肯定这是不可见标题的问题。任何人都可以确认此处 python 代码中的 header 创建是正确的吗?
编辑(24-04 下午 5:40 GMT): 问题仍然是实际的。正如其他人所建议的那样,我将请求改回了 urllib2。这有助于解决第一件事——“值(value)问题”。现在浏览器有
urllib2.HTTPError
HTTPError: HTTP Error 415: Unsupported Media Type
立即发布请求:
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
payload = {"Login": request.form['username'],
"Haslo": request.form['haslo']}
data = json.dumps(payload)
clen = len(data)
req = urllib2.Request(WEBSERVICE_IP + '/login', data,
{'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()
编辑(格林威治标准时间 24-04 下午 6:20):
Wireshark 捕获了 POST 请求,看起来没问题。
请您参考如下方法:
如果 data 是一个字典,Requests 将序列化它。你想传递一个字符串:
import json
req = requests.post(WEBSERVICE_IP + '/login', data=json.dumps(payload), ...
