简体   繁体   中英

FastAPI and Flask response issue

I've below code of Flask calling FastAPI end point. But the response not getting generated(Error: 422) when the FastAPI end point is being invoked and FastAPI end point log says INFO:127.0.0.1:56904 - "POST /runquery HTTP/1.1" 422 Unprocessable Entity

Inputs to FASTAPI end point

query: select c2,c2,c4,c5 from table_tab

env= iAT

Flask Code

  import requests
  
  app = Flask(__name__)    
  
  @app.route("/", methods=["GET", "POST"])
  def index():
      query_id = ""
      query = ""
      status = ""
      env = ""
      if request.method == "POST":
          query = request.form["query"]
          env = request.form["env"]
          data = {"query": query, "env": env}
          print(data)
          headers = {'Content-Type': 'application/json'}
          **response = requests.post("http://localhost:8000/runquery", json=data,headers=headers)**
          print(response)
          if response.status_code != 200:
              return f'Error: {response.status_code}'
          else:
              print(response.json())
          response_data = response.json()
          query_id = response_data["query_id"]
          status = response_data["status"]
      return render_template("index.html", query_id=query_id, query=query, status=status, env=env)
  
  
  if __name__ == "__main__":
      app.run(debug=True) ```        


**Here is the FastAPI end point code**
      
 ``` @app.post("/runquery")
  async def runquery(query: str, env: str):
      print('.....')
      delay = 60
      parsed_query = sqlparse.parse(query)[0]
      if parsed_query.get_type() == "SELECT":
          pass
      else:
          return JSONResponse(content={"error": "Only SELECT queries are allowed"}, status_code=422)
          # return {"error": "Only SELECT queries are allowed"}
  
      registry_scheduled = ScheduledJobRegistry(queue=que)
      registry_started = StartedJobRegistry(queue=que)
      # registry_completed = FinishedJobRegistry(queue=que)
      # registry_failed = FailedJobRegistry(queue=que)
  
      if len(registry_scheduled.get_job_ids()) >= 2:
          return JSONResponse(content={"Info": "GQs are already in-progress. Try after some time"})
          # return {"Info": "GQs are already in-progress. Try after some time"}
  
      if len(registry_started.get_job_ids()) >= 2:
          return JSONResponse(content={"Info": "GQs are already in-progress.Try after some time"})
          # return {"Info": "GQs are already in-progress.Try after some time"}
  
      # Generate a unique ID for the query
      query_id = str(uuid.uuid4())
      print('query_id..........', query_id)
      directory_path = os.path.join(home_path, query_id)
      print(directory_path)
      if not os.path.exists(directory_path):
          os.makedirs(directory_path)
  
      file_path = os.path.join(directory_path, "query.sql")
      with open(file_path, "w") as f:
          f.write(query)
  
      # job = que.enqueue(exec_query, query, env, sqlfile)
      job = que.enqueue_in(timedelta(seconds=delay), exec_query, query, env, query_id)
      r.set(query_id, job.id)
  
        # Return the query ID to the user
        return JSONResponse(content={"query_id": query_id, "query": query, "stauts": "OK"}, 
        status_code=202) ```

422 is Unprocessable Entity, it means that your request sent has wrong format parameter in the body. You must use Pydantic class to validate json.

Change FastAPI endpoint in this way:

from pydantic import BaseModel

class Data(BaseModel):
    query: str
    env: str

@app.post("/runquery")
async def runquery(data: Data):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM