Created
January 18, 2022 11:08
-
-
Save mazzma12/c755db4c4816ec655d7dcc3c44674192 to your computer and use it in GitHub Desktop.
Push a pandas dataframe to a GIST as a CSV through the Github API
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
import json | |
import os | |
from io import StringIO | |
import requests | |
GITHUB_API = "https://api.github.com" | |
API_TOKEN = os.getenv("GITHUB_API_TOKEN") | |
def dataframe_to_github_gist( | |
df, title, description="", api_token=API_TOKEN, gist_id=None, public=True, **kwargs | |
): | |
""" | |
Push a pandas dataframe to a GIST as a CSV through the Github API | |
If no gist id is provided it will publish a new one. | |
Args: | |
df ([pd.DataFrame]): [description] | |
title ([str]): [description] | |
description (str, optional): [description]. Defaults to "". | |
api_token ([str], optional): [description]. Defaults to API_TOKEN. | |
gist_id ([str], optional): [description]. Defaults to None. | |
public (bool, optional): [description]. Defaults to True. | |
Returns: | |
[type]: [description] | |
""" | |
# form a request URL | |
url = "/".join(filter(None, (GITHUB_API, "gists", gist_id))) | |
csv_buffer = StringIO() | |
df.to_csv(csv_buffer, **kwargs) | |
# print headers,parameters,payload | |
headers = {"Authorization": "token %s" % api_token} | |
params = {"scope": "gist"} | |
payload = { | |
"description": description, | |
"public": public, | |
"files": {title: {"content": csv_buffer.getvalue()}}, | |
} | |
# make a requests | |
res = requests.post(url, headers=headers, params=params, data=json.dumps(payload)) | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment