-
Notifications
You must be signed in to change notification settings - Fork 2
adding functionality to write to datasets #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
elysenko
wants to merge
4
commits into
IDinsight:master
Choose a base branch
from
elysenko:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -13,7 +13,10 @@ | |
import datetime | ||
import warnings | ||
from urllib.parse import quote | ||
|
||
import pandas as pd | ||
import tempfile | ||
import os | ||
import requests | ||
|
||
class IllegalArgumentError(ValueError): | ||
""" | ||
|
@@ -724,3 +727,70 @@ def list_forms(self): | |
raise e | ||
|
||
return response.json()['forms'] | ||
|
||
def upload_dataset(self, df, dataset_id, dataset_title=None, append=False, fill=False): | ||
""" | ||
Uploads a pandas df to a dataset | ||
:return: dictionary with previous dataset preview and upload response | ||
|
||
:param df: pandas DataFrame to upload | ||
:param dataset_id: ID of the dataset on SurveyCTO | ||
:param dataset_title: Optional title for the dataset (defaults to dataset_id) | ||
:param append: If True, appends data; otherwise replaces the dataset | ||
:param fill: If True, allows mismatched columns in append mode | ||
|
||
""" | ||
|
||
assert isinstance(df, pd.DataFrame), "data must be a pandas DataFrame" | ||
assert isinstance(dataset_id, str), "dataset_id must be a string" | ||
if dataset_title is None: | ||
dataset_title = dataset_id | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If the dataset_title is not needed for the API, I think we can remove this from the params as well. There is no check that the title is correct and seems redundant. What do you you think? |
||
|
||
headers = self.__auth() | ||
|
||
try: | ||
check_resp = self.get_server_dataset(dataset_id) | ||
except requests.exceptions.RequestException as e: | ||
raise RuntimeError(f"Failed to retrieve dataset: {e}") | ||
|
||
dataset_upload_mode = 'append' if append else 'clear' | ||
dataset_exists = 1 | ||
dataset_type = 'SERVER' | ||
|
||
with tempfile.NamedTemporaryFile(suffix=".csv", delete=False, mode='w', newline='') as tmp: | ||
df.to_csv(tmp.name, index=False) | ||
tmp_path = tmp.name | ||
|
||
upload_url = ( | ||
f"https://{self.server_name}.surveycto.com/" | ||
f'datasets/{dataset_id}/upload?csrf_token=' + '{headers[' + 'X-csrf-token' + ']}' | ||
) | ||
|
||
with open(tmp_path, 'rb') as f: | ||
files = { | ||
'dataset_file': (os.path.basename(tmp_path), f, 'text/csv') | ||
} | ||
payload = { | ||
'dataset_exists': dataset_exists, | ||
'dataset_id': dataset_id, | ||
'dataset_title': dataset_title, | ||
'dataset_upload_mode': dataset_upload_mode, | ||
'dataset_type': dataset_type, | ||
} | ||
|
||
try: | ||
upload_resp = self._sesh.post( | ||
upload_url, | ||
data=payload, | ||
files=files, | ||
cookies=self._sesh.cookies, | ||
headers=headers | ||
) | ||
upload_resp.raise_for_status() | ||
finally: | ||
os.remove(tmp_path) | ||
|
||
return { | ||
|
||
'response': upload_resp.json() | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks like this parameter isn't getting used in the function. Can we remove it?
In case of mismatched columns does the API return an error?