I have the following code in python.
file1 = pd.read_csv(./file1.csv) file2 = pd.read_csv(./file2.csv) merged = pd.merge(file1, file2, how='left', left_on='id', right_on='id') def task(val): x = file1['temp'].sum() y = file2['temp'].sum() merged['x_y'] = (x+y) - val return merged def run_task(df): merged_fil = merged[merged['col']=='z'] return merged_fil # Call function run_task(merged)
Now, I need to convert this code into rest api. The objective is to take the value of ‘val’ from the user on the webpage using a slider input.
P.S. – Mongo Server is being used. Can anyone tell me how to do that and convert this code. It’s just that the input value of val should be user based on the webpage. and then the same code runs and the ‘merged_fil’ output is rendered.
Advertisement
Answer
Solution:
I suggest you use flask which is a micro web framework which can be used to make web services easily. Follow the instructions that follow to transform these functions into web services using flask:
Step 1:
You need to install flask by typing: pip3 instal flask
step 2:
I am first going to give some context or an example into how flask works:
from flask import Flask app = Flask(__name__) @app.route(‘/’) def hello_world(): return ‘Hello, World!’
Then to run this example type flask run <script_name>
The very first line imports the Flask from its library, and the next line creates a variable name and instantiates the app using Flask class.
The next line @app.route('/')
(/
means the home page ) is called a route which is used to redirect the user to a specific page or perform a particular function when the user visit’s a particular URL.
The above service is equivalent to this function:
def hello_world(): return 'Hello, World!'
Step 3:
To add an input to a flask service/function simply add /<parameter>
to the end of the route and call it with the parameter at the end of the route
Here are your functions transformed into services:
form flask import Flask #import flask file1 = pd.read_csv(./file1.csv) file2 = pd.read_csv(./file2.csv) merged = pd.merge(file1, file2, how='left', left_on='id', right_on='id') @app.route(‘/task/<val>’)//the <val>is the input parameter as part of the route def task(val): x = file1['temp'].sum() y = file2['temp'].sum() merged['x_y'] = (x+y) - val return merged @app.route(‘/task/<df>’)//the <df>is the input parameter as part of the route def run_task(df): merged_fil = merged[merged['col']=='z'] return merged_fil
For more information on flask go here