我想将三个值发布到本地服务器,但是显然总是缺少值。如果我使用Postman进行整个操作,尽管我使用完全相同的标头和完全相同的正文,但一切都正常。
我试图将标头作为一个整体保留下来,使主体的值保持静态并由用户控制。我还搜索了人们使用python的其他HTTP POST问题。
服务器代码:
import json
from urllib.parse import urlparse
import requests
from flask import Flask, jsonify, request
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
values = request.get_json(force=True)
# Check that the required fields are in the POST'ed data
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing Values', 400
# Create a new Transaction
index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
response = {'message': f'Transaction will be added to Block {index}'}
return jsonify(response), 201
客户代码:
import urllib.request
import requests
if user_input == "-s" != "--send":
send_recipient = input("Please enter the address of the recipient: ")
send_amount = input("Please enter the amount you want to send: ")
node_identifier = 12345678
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
r = requests.post("http://localhost:5000/transactions/new", data={'sender': node_identifier, 'recipient': send_recipient, 'amount': send_amount}, headers=headers)
在服务器控制台中,我总是得到代码400,而不是201。使用Postman时,一切正常,并且显示201。
答案 0 :(得分:1)
使用values = request.form
代替request.get_json
,
日志:
ImmutableMultiDict([('sender', '12345678'), ('recipient', 'ab'), ('amount', 'ab')])
127.0.0.1--[18 / Jun / 2019 12:20:41]“ POST / transactions / new / HTTP / 1.1” 201