-1

I am new to flask and I have been trying to figure this out for fews days

This is my request.py

import requests

url = 'http://localhost:5000/predict_api'
r = requests.post(url,json={'City':'Berlin', 'Country':'DE', 'Target_PtoD':36,'Start Date':"1/8/2021",'End Date':"14/8/2021"})

I want to store the inputs from the post to object variables like below. When I manually assign variables in the code like below, it works but when I try get it from the request. I get errors

city = 'Berlin'
Country='DE'
Target_PtoD=36
start='14/7/2021'
end='31/7/2021'

I have tried the following

@app.route('/predict',methods=['GET','POST'])

def predict():
city = request.values.get('City')
Country=request.values.get('Country')
Target_PtoD=request.values.get('Target_PtoD')
start=request.values.get('Start Date')
end=request.values.get('End Date')

But for some reason the wrong input gets stored.

Anyone familiar with this, request your kind help.

davidism
  • 121,510
  • 29
  • 395
  • 339
Datalearner
  • 183
  • 7

2 Answers2

0

There are two issues in your code.

First, you name your endpoint predict, but you call predict_api in your request.py.

Second, I am not sure how to use request.values, which returns a CombinedMultiDict - if you insist to use request.values, have a look at the documentation.

It would be easier to use request.json.

So you get the value for the City by city = request.json.get('City').

It is straightforward to debug such problems with a debugger, such as pdb.

I created a 5 min lightning talk for Python Ireland: https://www.youtube.com/watch?v=Fxkco-gS4S8

davidism
  • 121,510
  • 29
  • 395
  • 339
Jürgen Gmach
  • 5,366
  • 3
  • 20
  • 37
  • Thanks for your message. Using request.data, I get the following the error----- 'bytes' object is not callable – Datalearner Aug 09 '21 at 12:39
  • @Datalearner I used your code and run it on my PC - so, I am not sure how it can break with your error message. Usually, it is a good idea to include the complete traceback. Anyhow, my answer has been edited by @davidism to use `request.json`. This also works - I just confirmed it on my PC. – Jürgen Gmach Aug 09 '21 at 14:03
0

You can probably do

request_json = request.get_json()
City = request_json.get("City")
Country = request_json.get("Country")
# etc...

using the .get_json() function first will return a dictionary of the whole json body and that is much easier to work with

c8999c 3f964f64
  • 1,430
  • 1
  • 12
  • 25