Skip to content

Instantly share code, notes, and snippets.

@mazzma12
Created January 18, 2022 11:08
Show Gist options
  • Save mazzma12/c755db4c4816ec655d7dcc3c44674192 to your computer and use it in GitHub Desktop.
Save mazzma12/c755db4c4816ec655d7dcc3c44674192 to your computer and use it in GitHub Desktop.

Revisions

  1. mazzma12 created this gist Jan 18, 2022.
    46 changes: 46 additions & 0 deletions dataframe_gist.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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