zangsir zangsir - 1 month ago 4
Python Question

Python push files to Github remote repo without local working directory

I am working on a Python based web application for collaborative xml/document editing, and one requirement from the client is that users should be able to push the files they created (and saved on the server) directly to a Github remote repo, without the need of ever creating a local clone on the server (i.e., no local working directory or tracking of any sort). In GUI terms, this would correspond to going to Github website and manually add the file to the remote repo by clicking the "Upload files" or "create new file" button, or simply edit the existing file on the remote repo on the Github website and then commit the change inside the web browser. I wonder is this functionality even possible to achieve either using some Python Github modules or writing some code from scratch using the Github API or something?

Answer

So you can create files via the API and if the user has their own GitHub account, you can upload it as them.

Let's use github3.py as an example of how to do this:

import github3

gh = github3.login(username='foo', password='bar')
repository = gh.repository('organization-name', 'repository-name')
for file_info in files_to_upload:
    with open(file_info, 'rb') as fd:
        contents = fd.read()
    repository.create_file(
        path=file_info,
        message='Start tracking {!r}'.format(file_info),
        content=contents,
    )

You will want to check that it returns an object you'd expect to verify the file was successfully uploaded. You can also specify committer and author dictionaries so you could attribute the commit to your service so people aren't under the assumption that the person authored it on a local git set-up.

Comments