I'm getting a value as params when I make an axios GET request and I want to use that value to make an SQL query. This is the code:
@app.route('/get-hcp-data', methods=['GET', 'POST'])
def get_hcp_data():
value = request.args.get('nameValue')
engine = connect_pg()
sql = "select * from dim_hcp_details where hcp_name like " + value + "%"
hcp_details = pd.read_sql_query(sql,engine)
hcp_dict = hcp_details.to_dict()
print(hcp_dict)
return jsonify(hcp_dict)
``
When I press the button 'a', I'm getting this error in the terminal of Flask:
> [SQL: select * from dim_hcp_details where hcp_name like a%]
(Background on this error at: http://sqlalche.me/e/13/f405)
For reference here is the axios get request that I'm executing in the front end using ReactJS.
```javascript
fetchingDataOnChange = () => {
let nameValue = this.state.searchName;
console.log('Name inside fetchingdata: ', nameValue);
axios.get('/get-hcp-data?', {
params: {
nameValue: nameValue,
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}
I came up with a solution like this. First, I sent a post request instead of a get request using Axios inside my React Component like this:
fetchingDataOnChange = () => {
let nameValue = this.state.searchName;
var myParams = {
nameValue: nameValue
}
axios.post('/get-hcp-data', myParams)
.then((res) => {
const hcps = res.data;
this.setState({ hcps: hcps, hcpName:
Object.values(hcps.hcp_details_concat) })
Object.values(this.state.hcps.hcp_details_concat));
console.log(res);
}, (error) => {
console.log(error);
});
}
I then wrote my Flask code in this manner to get the data from axios. Used request.get_json to get every keystroke and executed a SQL query based on that.
@app.route('/get-hcp-data', methods=['GET', 'POST'])
def get_hcp_data():
value = request.get_json()
newValue = value['nameValue']
engine = connect_pg()
sql = "select * from dim_hcp_details where lower(hcp_name) like
lower('"+newValue+"%') limit 50"
hcp_details = pd.read_sql_query(sql,engine)
hcp_details['hcp_details_concat'] = "[" + hcp_details['hcp_id'] + "]" +
hcp_details['hcp_name']
hcp_dict = hcp_details.to_dict()
return jsonify(hcp_dict)