Posting JSON to Python API (created using flask)

huangapple go评论70阅读模式
英文:

Posting JSON to Python API (created using flask)

问题

我有以下代码,我正在使用Flask创建API:

from flask import Flask, request, jsonify
import json

app = Flask(__name__)

@app.route('/post', methods=['GET','POST'])
def post():
   payload = request.data

  # return jsonify(data)
  # json_object = json.dumps(data, indent=4)
  return payload
  # return jsonify(payload)

if __name__ == '__main__':
   app.run(debug=True)

我使用以下代码调用本地主机托管的API:

import requests
headers = {'Content-Type': 'application/json; charset=utf-8'}
url = "http://localhost:5000/post"
text = {"filename": "my_file.csv"}

response = requests.post(url, json=text, headers=headers)

if response.status_code == 200:
    print("CSV文件有效")
#   print(data)
#   print(getjson)
    print(text)
else:
   print("CSV文件无效")

问题是:

  1. 当我使用调用代码调用本地主机URL时,我得到了成功的连接,但是没有数据被“发布”到URL上,

  2. 如果我尝试使用jsonify(或使用JSON dumps),然后运行调用代码,它仍然成功运行,但是本地主机站点会给出以下错误:

    错误请求

    由于请求的Content-Type不是'application/json',因此未尝试加载JSON数据。

如何纠正这个问题?我的目标是通过Flask API推送JSON并在本地主机站点上显示它。从长远来看,我们需要创建一个验证传递的JSON的应用程序,所以首先我正在尝试查看它是否按原样成功读取JSON,或者不是?

如果有任何其他问题,请告诉我。

英文:

I have below code where I am making an API using flask:

from flask import Flask, request, jsonify
import json

app = Flask(__name__)

@app.route('/post', methods=['GET','POST'])
def post():
   payload = request.data

  # return jsonify(data)
  # json_object = json.dumps(data, indent=4)
  return payload
  # return jsonify(payload)

if __name__ == '__main__':
   app.run(debug=True)

and using below code to call the localhost hosted API:

    import requests
    headers =  {'Content-Type': 'application/json; charset=utf-8'}
    url = "http://localhost:5000/post"
    text = {"filename": "my_file.csv"}

    response = requests.post(url, json=text , headers=headers )


    if response.status_code == 200:
        print("CSV file is valid")
    #   print(data)
    #   print(getjson)
        print(text)
    else:
       print("CSV file is invalid")

The problem is

  1. that when I call the localhost URL using the calling code I get a successful connection, however no data gets "posted" on the URL,

  2. if I try to jsonify (or use JSON dumps) and then run the calling code it stills runs successfully however the localhost site gives below error:

    > Bad Request
    >
    > Did not attempt to load JSON data because the request Content-Type was not 'application/json'.

How can I rectify this? My aim is to push JSON using the flask API and display it on the localhost site. The long term goal being is that we need to create an app that is validating the JSON passed, so to begin with I am trying to see if it is reading the JSON successfully as-is, or not?

答案1

得分: 0

以下是已翻译的内容:

要将数据以JSON格式发送到服务器并接收其响应,以下示例代码非常有效。Content-Type标头将自动设置,因此在服务器端不应需要使用request.get_json(force=True)来假定传输为JSON。

对于JSON数据的服务器端验证,我建议查看webargs。该库为您提供了各种验证器来检查发送的数据。

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.post('/echo')
def echo():
    data = request.get_json()
    return jsonify(data)
import requests

url = 'http://127.0.0.1:5000/echo'
dat = { 'lang': 'python' }

r = requests.post(url, json=dat)
r.raise_for_status()
print(r.json())
英文:

To send data in JSON format to the server and receive its response, the following example code is effective. The Content-Type header is set automatically, so it shouldn't be necessary to use request.get_json(force=True) on the server side to assume transmission as JSON.

For server-side validation of the JSON data, I recommend taking a look at webargs. The library offers you various validators to check the sent data.

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.post('/echo')
def echo():
	data = request.get_json()
	return jsonify(data)
import requests

url = 'http://127.0.0.1:5000/echo'
dat = { 'lang': 'python' }

r = requests.post(url, json=dat)
r.raise_for_status()
print(r.json())

huangapple
  • 本文由 发表于 2023年7月17日 13:49:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定