python – 在postman的post请求中,flask返回400

我正在lynda做一个烧瓶课程并且遇到了一个例子.

https://www.lynda.com/Flask-tutorials/Web-API-Development-Flask/521200-2.html

我正在做一个简单的帖子,它可以从基本的webform中运行,但是从邮递员那里失败了.我认为这是因为邮递员对请求编码不同,但无法弄清楚为什么会这样做或为什么烧瓶无法读取它.

邮差:
《python – 在postman的post请求中,flask返回400》

要求在查尔斯截获的请求:

POST /api/candidate HTTP/1.1
Host: localhost:5000
Content-Length: 248
Postman-Token: 285ed4d8-2af6-0eb6-8de7-e8ecb41fb86e
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

------WebKitFormBoundary3Q45bnchdpXxtZbw
Content-Disposition: form-data; name="first_name"

Susan
------WebKitFormBoundary3Q45bnchdpXxtZbw
Content-Disposition: form-data; name="last_name"

Kruger
------WebKitFormBoundary3Q45bnchdpXxtZbw--

返回:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

从简单的POST网页表单请求:

POST /api/candidate HTTP/1.1
Host: localhost:5000
Content-Length: 33
Cache-Control: max-age=0
Origin: null
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

first_name=Mickey&last_name=Mouse

退货(正确):

{
    "id": "a7c2f6a3-e8d2-4c53-be97-ccf72a04295d",
    "url": "/api/candidate/a7c2f6a3-e8d2-4c53-be97-ccf72a04295d"
}

相关的python代码:
@ app.route(“/ api / candidate”,methods = [“POST”])

def add_candidate():
    print dict(request.form)
    first_name = request.form["first_name"]
    last_name = request.form["last_name"]
    new_candidate_id = DATA_PROVIDER.add_candidate(first_name, last_name)
    return jsonify({
        "id": new_candidate_id,
        "url": url_for("candidate_by_id", id=new_candidate_id)
    })

失败时输出打印:

{'------WebKitFormBoundary3Q45bnchdpXxtZbw\r\nContent-Disposition: form-data; name': [u'"first_name"\r\n\r\nSusan\r\n------WebKitFormBoundary3Q45bnchdpXxtZbw\r\nContent-Disposition: form-data; name="last_name"\r\n\r\nKruger\r\n------WebKitFormBoundary3Q45bnchdpXxtZbw--\r\n']}

工作时打印输出:

{'first_name': [u'Mickey'], 'last_name': [u'Mouse']}

最佳答案 来自您的Web表单的工作请求具有Content-Type标头,其值为application / x-www-form-urlencoded.

您的屏幕截图显示Postman正在使用表单数据:

尝试选择application / x-www-form-urlencoded.

点赞