0

I have a github directory called "latviadebate". It looks like this:

$ main 
. 
├── index.html 
├── style.css 
├── images 
│   └── image1.png 
│   └── image2.png 
├── pages 
│   └── 20-03-2023.html 
│   └── 08-01-2022.html

So, what I need to do is upload new images and new pages, using Python. I managed to upload them to root directory (where index.html and style.css are), but no luck with putting them in folders (/pages/ and /images/).

My Python code looks like this:

import tkinter
import tkinter.filedialog
import base64
import os
from github import Github
from github import InputGitTreeElement
from tkinter import *
from tkinter import messagebox
from datetime import datetime, timedelta

user = 'dzhemvrot'
token = 'TOKEN'
commit_message = 'python commit'
g = Github(token)
repo = g.get_user().get_repo('latviadebate') # repo name

...

def load():
    try:
        fn = datetime.now().strftime("%Y-%m-%d")
        artic = Text.get('1.0', 'end')
        artic = artic.replace("\n", "<br>")
        artna = Name.get()
        regl = Regist.get()
        dienl = Dienas.get()
        whfi = """here was html page, it works just fine"""
        open(fn+".html", 'wt', encoding="utf-8").write(whfi)
        phots = photo()
        phot = os.path.basename(phots).split('/')[-1]
        file_list = [
        f'{fn}.html',
        f'{phot}'
    ]
        file_names = [
        f'pages\{fn}.html',
        f'images\{phot}'
    ]
        master_ref = repo.get_git_ref('heads/main')
        master_sha = master_ref.object.sha
        base_tree = repo.get_git_tree(master_sha)

        element_list = list()
        for i, entry in enumerate(file_list):
            if entry.endswith('.html'):
                with open(entry) as input_file:
                    data = input_file.read()
            #if entry.endswith('.png'): # images must be encoded
            #    data = base64.b64encode(data)
            element = InputGitTreeElement(file_names[i], '100644', 'blob', data)
            element_list.append(element)
        tree = repo.create_git_tree(element_list, base_tree)
        parent = repo.get_git_commit(master_sha)
        commit = repo.create_git_commit(commit_message, tree, [parent])
        master_ref.edit(commit.sha)
        os.remove(f"{fn}.html")

def photo():
    ftypes = [('.PNG', '*.png'), ('.JPG', '*.jpg'), ('.WEBP', '*.webp'), ('All files', '*')] 
    photo = tkinter.filedialog.Open(root, filetypes = ftypes).show()
    if photo == '':
        return
    return photo

I tried putting \ and / in front of pages{fn}.html, but there was this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:\Documents\zlib de- and compress\latviadebate.py", line 131, in load
    tree = repo.create_git_tree(element_list, base_tree)
  File "C:\Python310\lib\site-packages\github\Repository.py", line 1169, in create_git_tree
    headers, data = self._requester.requestJsonAndCheck(
  File "C:\Python310\lib\site-packages\github\Requester.py", line 400, in requestJsonAndCheck
    return self.__check(
  File "C:\Python310\lib\site-packages\github\Requester.py", line 425, in __check
    raise self.__createException(status, responseHeaders, output)
github.GithubException.GithubException: 422 {"message": "tree.path cannot start with a slash", "documentation_url": "https://docs.github.com/rest/reference/git#create-a-tree"}
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Blue Robin Mar 14 '23 at 20:21
  • @BlueRobin, I'm sorry, but all of it is needed. I already trimmed a lot. – Chur-Ka Han Mar 20 '23 at 01:18

0 Answers0