How to run Python script in KNIME

I have Python Script which is correctly works in the Python environment. But I want run this script in the KNIME. I see some output table and don’t know how it correctly write…

from datetime import date, datetime, timedelta
import requests
import time
import json

#specify your range
start_date = date(2015, 5, 5)

end_date = date(2015, 5, 6)

list_of_dates = [start_date]

while start_date != end_date:

next_date = start_date + timedelta(days=1)

list_of_dates.append(next_date)

print(list_of_dates)

start_date = next_date

list_of_api_responses = {}

for date in list_of_dates :

date_param = date.isoformat()

print(date_param)

#Make API call
url = "myURL"

querystring = {"filter[review-date]": date_param,"instance":"myInstance"}

headers = {
    'accept': "application/vnd.api+json",
    'content-type': "application/vnd.api+json",
    'authorization': "myToken" 
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

##Append the new response to dict
list_of_api_responses[date_param]=response.text

##Create timelag between API calls
print("Delaying script")

time.sleep(8)

##Output the dict of JSON reponses
print(list_of_api_responses)

with open(‘output.txt’, ‘a’) as outfile:
json.dump(list_of_api_responses, outfile)

Python in KNIME typically would expect an
output_table

that gets converted to a KNIME table. Of course it is also possible to use KNIME just to run python scripts and store the results somewhere else.

Maybe you could bring your code into a file that would preserve the python structure or even better include it into a KNIME workflow so we could check it out in a real sample environment of KNIME.

Simple example
https://hub.knime.com/mlauber71/spaces/Public/latest/kn_example_python_if_then

Example how to store python objects somewhere else
https://hub.knime.com/mlauber71/spaces/Public/latest/kn_example_python_pickle_dictionary

2 Likes

Yes, I see example. But I am studying Python only third day and don’t know how it correctly change…
I attach screen from the KNIME.

It would be much easier to have an example in code. Maybe you start by exploring some examples of KNIME and python and set up an environment where you can successfully run some examples.

KNIME and Python use Pandas data structures
If you want to transfer json objects one would have to take some additional steps.

Also it might help if we knew what the purpose of your workflow is.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.