python—向FlaskAPI发送post请求,但不接收数据

liwlm1x9  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(407)

因此,我试图将某些值发送到flask api streamlit应用程序,但它似乎没有执行post请求。现在,我为我的 main.py 不起作用,因为我得到了一个 TypeError: 'NoneType' .
app.py:

import requests
import json
import streamlit as st
...
api_url = "http://127.0.0.1:5000/" # Flask url
create_row_data = {'name': name, 'type': get_type(name), 'token_value': token_value, 
'external': external, 'start': start, 'end': end, 'step': step}
print(create_row_data)

# The terminal cannot print out the value of r and it appears that it cannot send the post request as well

r = requests.post(url=api_url, json = create_row_data)
print(r)

产量 print(create_row_data) 在app.py中:

{'name': 'session', 'type': 'area_chart', 'token_value': 'G0as7vjk1ksuxn94', 
'external': False, 'start': datetime.datetime(2021,7,1,14,9,7,322438), 'end': datetime.datetime(2021,7,8,14,9,7,322441), 'step': '1d'}

main.py:

from flask import Flask
from flask import jsonify
from flask import request
...
import requests, json
@app.route('/', methods=['GET', 'POST'])
def get_data():
   if request.method == 'GET':
       return "ok", 200
   if request.method =='POST':
      p_name = request.json['name']
      p_type = request.json['type']
      ...
      p_end = request.json['end']
      p_step = request.json['step']
      create_row_data = {'p_name': str(p_name), 'p_type': str(p_type), ... , 'p_end': str(p_end), 'p_step': str(p_step)}
      print(create_row_data)  
      response = requests.post(url, data=json.dumps(create_row_data), headers= {'Content-type': 'application/json'}
      return response.content
p1iqtdky

p1iqtdky1#

据我所知,您需要将数据发布到127.0.0.1,并使用flask_restful从app.py创建一个表,从而创建一个api端点,以便发布数据。main.py的代码为:

from flask import Flask
from flask import Flask, request
from flask_restful import Resource, Api
from flask import jsonify
from flask import request
import requests, json

app = Flask(__name__)
api = Api(app)

@app.route('/', methods=['GET', 'POST'])
def get_data():
    if request.method == 'GET':
        return "ok", 200

class create_row_data(Resource):
    def post(self):
        response = request.get_json()
        p_name = response['name']
        p_type = response['type']
        ...
        # code to process your data and to create a table

        # return something for your client application
        return True    

api.add_resource(create_row_data, '/create_row_data/')

您的客户端app.py不需要更改,但url现在更改为http://127.0.0.1:5000/create_row_data/

相关问题