我想在python中创建一个github应用程序,我被困在身份验证部分。由于默认情况下它们不支持python,因此我必须使用第三方库。生成 JWT 令牌后,我可以成功使用 curl 进行身份验证,但不能使用库进行身份验证。
我试过使用 PyGithub 和 Github.py 并且都返回了“错误的凭据”错误,所以我一定忽略了一些东西。
import jwt
from github import Github
from dotenv import load_dotenv
load_dotenv()
GITHUB_PRIVATE_KEY = os.getenv('GITHUB_PRIVATE_KEY')
GITHUB_APP_IDENTIFIER = os.getenv('GITHUB_APP_IDENTIFIER')
GITHUB_WEBHOOK_SECRET = os.getenv('GITHUB_WEBHOOK_SECRET')
message = {'iat': int(time.time()),
'exp': int(time.time()) + (10 * 60),
'iss': GITHUB_APP_IDENTIFIER}
token = jwt.encode(message, GITHUB_PRIVATE_KEY.strip().encode(), 'RS256')
gh = Github(jwt=token.decode())
for repo in gh.get_user().get_repos():
print(repo.name)
Run Code Online (Sandbox Code Playgroud)
此 curl 命令返回我的应用程序的详细信息:
curl -i -H "Authorization: Bearer YOUR_JWT" -H "Accept: application/vnd.github.machine-man-preview+json" https://api.github.com/app
Run Code Online (Sandbox Code Playgroud)
我希望代码能够验证并打印我的回购,但是我得到
Traceback (most recent call last):
File "C:/python/jeev/testing.py", line 21, in <module> …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何使用 PyGithub 模块,但我不断收到相同的错误:
github.GithubException.GithubException:401 {“message”:“需要身份验证”,“documentation_url”:“https://docs.github.com/rest/reference/users#get-the-authenticated-user”}
考虑到我刚刚开始,我的代码非常简单:
from github import Github
g = Github("Charonum","xxxxxxxx")
user = g.get_user()
print(user.name)
print(user.login)
Run Code Online (Sandbox Code Playgroud)
错误发生在到达 时print(user.name)。
我想使用 Pygithub 将图像文件上传到我的 Github 存储库。
from github import Github
g=Github("My Git Token")
repo=g.get_repo("My Repo")
content=repo.get_contents("")
f=open("1.png")
img=f.read()
repo.create_file("1.png","commit",img)
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
File "c:\Users\mjjha\Documents\Checkrow\tempCodeRunnerFile.py", line 10, in <module>
img=f.read()
File "C:\Program Files\Python310\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 119: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
此方法对于文本文件效果很好。但我无法将图像文件上传到我的存储库。
当我使用 open-CV 读取图像文件时,出现以下错误:
assert isinstance(content, (str, bytes))
AssertionError
Run Code Online (Sandbox Code Playgroud)
我使用 cv2 时的代码是:
from github import Github
import cv2
g=Github("")
repo=g.get_repo("")
content=repo.get_contents("")
f=cv2.imread("1.png")
img=f
repo.create_file("1.png","commit",img)
Run Code Online (Sandbox Code Playgroud)
我认为 createFile() 仅将字符串作为参数,因此会出现这些错误。
有没有办法使用 Pygithub(或任何库)将图像文件上传到 Github?
如何创建一个新的GitHub存储库,对其进行克隆,更改文件,然后使用python和pyGitHub和pyGit2库将其推回github?
这两个库的文档都很稀疏,几乎没有示例。
这是我学到的
g = Github("user", "pass")
repoName = "apiTest"
print "Get all repos:"
for repo in g.get_user().get_repos():
print "\t%s" % repo.name
print "<--------------------------------------------------->"
print "Get all branches in repo %s:" % repoName
for branch in g.get_user().get_repo(repoName).get_branches():
print "\t%s" % branch.name
print "<--------------------------------------------------->"
print "Get last commit message in repo %s:" % repoName
branch = g.get_user().get_repo(repoName).get_branch("dev")
lastCommit = branch._commit.value.commit
print "\t%s" % lastCommit._message.value
print "\t%s"
print "<--------------------------------------------------->"
fc = repo.update_file("/README.md", "testing PyGithub", "test commit", fc.sha)
print fc
Run Code Online (Sandbox Code Playgroud)
但我想知道如何结帐到新分支。我没有在网上找到任何示例。非常感谢你。
我正在使用 PyGithub 来抓取一些存储库,但在迭代搜索页面时遇到一些错误。
def scrape_interval(self, interval):
for repo_number, repo in self.search(interval):
code...
def search(self, interval):
try:
iterator = enumerate(self.github.search_repositories(query="Laravel created:" + interval))
except:
print.warning("Going to sleep for 1 hour. The search API hit the limit")
time.sleep(3600)
iterator = self.search(interval)
return iterator
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我在创建迭代器时尝试捕获错误def search。但是错误是在线抛出的for repo_number, repo in self.search(interval):,所以是在迭代器获取下一个项目的某个时刻?
我可以选择哪些选项来捕获这些错误?我最好避免将整个 for 循环包装在 try 子句中,而是在迭代本身期间对其进行管理。
有关错误本身的参考:
File "/Users/olofjondelius/Documents/Code/laravel-ai/src/examples/migration-analysis/../../GithubScraper.py", line 47, in scrape_interval
for repo_number, repo in self.search(interval):
File "/anaconda3/envs/laravel-ai/lib/python3.7/site-packages/github/PaginatedList.py", line 58, in _iter_
newElements = self._grow()
File "/anaconda3/envs/laravel-ai/lib/python3.7/site-packages/github/PaginatedList.py", line …Run Code Online (Sandbox Code Playgroud) 我正在使用PyGithub库邀请新成员加入该组织。我面临的问题是下一个:在方案中,当我仅知道用户的主电子邮件时,如何检索他的用户名以进行相应的邀请?我知道可以通过UI进行操作,但无法通过API找到相应的调用。请协助!
比如我有一个文件t.json,内容是:
{
"a": "abcdefg"
}
Run Code Online (Sandbox Code Playgroud)
文件 t.json 被推送到 master 分支。然后我向文件添加一些内容,并签出到新分支,因此文件现在如下所示:
{
"a": "abcdefg",
"b": "mkjuujj"
}
Run Code Online (Sandbox Code Playgroud)
现在我可以使用 PyGithub 比较两个提交。代码是这样的:
WORKING_BRANCH = "my_new_branch"
new_branch_ref_str = "refs/heads/%s" % WORKING_BRANCH
branch_ref = None
all_ref = repo.get_git_refs()
for ref in all_ref:
if ref.ref == new_branch_ref_str:
branch_ref = ref
break
if not branch_ref:
# create branch from this commit
b = repo.get_branch("master")
branch_ref = repo.create_git_ref(ref=new_branch_ref_str,
sha=b.commit.sha)
last_head = repo.get_branch(WORKING_BRANCH)
fc = repo.get_file_contents("/t.json", ref=WORKING_BRANCH)
file = 't.json'
commit_message = "create a new branch with changes"
input_file …Run Code Online (Sandbox Code Playgroud) 如何在 Github 上使用 PyGithub 在组织中创建新存储库?我特别想知道如何使用该create_repo方法?
我的问题与这个问题相同,但我希望创建的存储库出现在组织中。
在没有组织级别的情况下创建存储库的解决方案是:
g = Github("username", "password")
user = g.get_user()
repo = user.create_repo(full_name)
Run Code Online (Sandbox Code Playgroud) 我正在编写一个网络应用程序,我想在 Django 的 AuthenticationForm 中添加一个必需的复选框
我不知道如何扩展(或覆盖?)AuthenticationForm。
这是我在模板中调用身份验证表单的地方:
<h2>Login</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p}}
<button type="submit" class="btn btn-success">Login</button>
</form>
<br>
<p><strong>-- OR --</strong></p>
<a href="{% url 'social:begin' 'github' %}">Login with GitHub</a><br>
</body>
Run Code Online (Sandbox Code Playgroud)
这是我的 urls.py :
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from django.conf.urls import url, include
from gitInsights import views as core_views
from django.contrib.auth.views import LoginView
urlpatterns = [
path('admin/', admin.site.urls),
path('gitInsights/', include('gitInsights.urls')),
path('login/', auth_views.login, name='login'),
path('logout/', auth_views.logout, name='logout'),
url(r'^auth/', …Run Code Online (Sandbox Code Playgroud) make update最近,在使用此片段运行了一堆存储库后,我一直在尝试使用 pyGithub 创建一些自动 PR 。
body = 'Test PR 2 please ignore'
pr = repo.create_pull(title="Test PR please ignore",
body=body,
head="patch/helm-chart-update",
base="master")
pr
Run Code Online (Sandbox Code Playgroud)
我一直从 API 收到此错误消息
github.GithubException.GithubException: 422 {"message": "Validation Failed", "errors": [{"resource": "PullRequest", "field": "head", "code": "invalid"}], "documentation_url": "https://developer.github.com/v3/pulls/#create-a-pull-request"}
当然,我的第一个猜测是我输错了存储库名称,但事实并非如此。奇怪的是,当我用不存在的分支名称(如“someGarbage”)替换头名称时,我得到了相同的错误。
接下来,我认为 PR 可能存在冲突或其他无效细节(尽管由于我正在使用的测试分支的简单性,这种情况极不可能发生),但 Github GUI 创建 PR 时没有任何问题。
最终我能够使用https://pypi.org/project/git-pull-request/制作 PR ,但不幸的是我看不到一种方法来避免它在 shell 中打开 vim (这会创建很多由于将运行的存储库数量较多,因此很辛苦)。如果一切都失败了,我可能只会使用 requests 来手动调用 Github API,但我真的很想使用 pyGithub,两者都可以保持代码简单/可维护(因为我已经使用该库来搜索目标存储库并将它们克隆到 /tmp 中),因为它通常看起来是一个不错的工具,我想学习如何使用它。
抱歉,由于问题的性质,这不是最可重现的,但我很乐意详细说明细节。有什么想法吗?
更新
在使用调用实现此功能后,我通过这篇文章requests了解到,如果您使用“params”参数进行调用以将 json 对象传递给 POST 请求而不是“json”参数,您会得到相同的错误代码。开始怀疑存在错误,但我希望被证明是错误的
pygithub ×12
python ×12
github-api ×6
github ×4
api ×2
git ×2
django ×1
exception ×1
github-pages ×1
github3.py ×1
jwt ×1
pygit2 ×1