2

So, here goes the line I'm trying to use:

 r=  requests.post('https://github.com/Gevez/gameficacao/upload/master', auth=HTTPBasicAuth('user', 'pass'), data='data.json')

The server returns a 403 code, even if I put the credentials correctly. Now I want to know if I'm doing it the wrong way or if github doesn't allow me to do it.

1 Answer 1

4

You can use Github create repo content API for creating a file on your repository via the API :

PUT /repos/:owner/:repo/contents/:path

You would need to create a personal access token first. For example :

import requests 
import base64

token = "YOUR_TOKEN"

repo = 'bertrandmartel/test-repo'
path = 'data.json'

data = open("data.json", "r").read()

r = requests.put(
    f'https://api.github.com/repos/{repo}/contents/{path}',
    headers = {
        'Authorization': f'Token {token}'
    },
    json = {
        "message": "add new file",
        "content": base64.b64encode(data.encode()).decode(),
        "branch": "master"
    }
)
print(r.status_code)
print(r.json())

You can also use PyGithub library :

from github import Github

token = "YOUR_TOKEN"

repo = "bertrandmartel/test-repo"
path = "data.json"

# if using username and password
#g = Github("user", "password")

g = Github(token)

data = open("data.json", "r").read()

repo = g.get_repo(repo)
repo.create_file(
    path = path, 
    message = "add new file", 
    content = data, 
    branch = "master"
)
Sign up to request clarification or add additional context in comments.

2 Comments

Now, if I want to update this file, I just need the sha file that was given me when I first uploaded it ?
To answer the thing I asked, no. Every file has a sha, which is basically the content of your json encrypted, so if you change the content of your json and update it, the sha changes as well. In order to make another update you will need the new sha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.