Reputation: 5
Python newbie here. I have a basic Flask API to price check a car's make and model.
Expected Behavior: The purpose is to send a GET request to the server like this:
http://127.0.0.1:5000//EndPoint1?CarMakeModel=ChevySilverado
And the response should return the price: $25000
If I submit a second request like this:
http://127.0.0.1:5000//EndPoint1?CarMakeModel=FordPinto
The response should return the price: $5000
Incorrect Observed Behavior: When I make a GET request for ChevySilverado (like the URL above), it returns $25000 correctly. But when I send a second URL for FordPinto, it returns $25000 again instead of $5000. It will always repeat $25000 as the output.
How can I get this Python code to return $5000 when I submit 'FordPinto' on the second request URL?
Here's the code I've tried:
#PriceCheck.py:
from Flask import request
PriceChecker=[]
Price=[]
PriceChecker= request.args.get('CarMakeModel')
if PriceChecker == 'ChevySilverado':
Price = '$25000'
if PriceChecker == 'FordPinto':
Price = '$5000'
#Run.py:
from flask import Flask
app = Flask(__name__)
@app.route('/EndPoint1')
def Response():
from PriceCheck import PriceChecker
return str(PriceChecker)
if __name__ == '__main__':
app.run(debug=True)
Upvotes: 0
Views: 1200
Reputation: 57640
Because Price
is a module global variable, it is is only set once, when PriceCheck.py
is first imported. You should instead wrap the code in PriceCheck.py
in a function so that it can be called repeatedly:
New PriceCheck.py
:
from Flask import request
def check_price():
PriceChecker= request.args.get('CarMakeModel')
if PriceChecker == 'ChevySilverado':
Price = '$25000'
if PriceChecker == 'FordPinto':
Price = '$5000'
# You also need to handle `PriceChecker` being other values!
return Price
New Run.py
:
from flask import Flask
from PriceCheck import check_price
app = Flask(__name__)
@app.route('/EndPoint1')
def Response():
return check_price()
if __name__ == '__main__':
app.run(debug=True)
Upvotes: 4