主页添加Github贡献图

前言

看到很多博主的主页都挂载上了自己github的贡献图,怪好看的,所以也打算整一个,说实话我研究了好几天,npm install...npm uninstall...不知道执行了多少次,配置改了又改,一键三连后,恭喜一直喜提loading….,尽管如此,这么好看的贡献图怎么能够放弃呢,经过不懈的捶打我的电脑。。。不是,经过不懈的努力和尝试,今天终于喜提如下画面:

鉴于其他方法的不可实现性(是我的问题,下次实现了再讲),我就讲下我是怎么实现的吧

div+js的挂载方法

  • https://github.com/Zfour/hexo-github-calendar中的githubcalendar.js下载至butterfly下的js文件下并命名为githubcalendar.js
    修改用户名:

    1
    2
    3
    (function(){var git_user = 'codeboy-zuo';
    var github_container = document.getElementById('github_container');
    var github_loading = document.getElementById('github_loading');
  • 在主题配置文件中引入:

    1
    2
    bottom:
    - <script src="/js/githubcalendar.js"></script>
  • 修改index.pug:

    1
    2
    3
    4
    5
    6
    block content
    include ./includes/mixins/post-ui.pug
    #recent-posts.recent-posts
    + <div id="github_container"></div>
    +postUI
    include includes/pagination.pug

    最后一键三连即可hexo cl && hexo g && hexo s

自建API

参考:https://github.com/Zfour/python_github_calendar_api

1
2
var github_canlendar = (git_user, git_color) => {
var git_githubapiurl = "https://gitcalendar.ldfbg.com/api?" + git_user;
  • 登入Vercel新建项目,然后导入第三方库

https://github.com/Zfour/python_github_calendar_api

点击继续,然后自定义项目名称,点击创建,等待Deploy完成
  • 自此api自建完成,检查api是否配置成功,访问api链接(url链接 + ‘/api’ + git用户名,例如我的是
    https://github-calendar-theta.vercel.app/api/?codeboy-zuo
    显示数据则配置成功

可能存在的问题

自建的api访问报错

将下面代码复制,更换github仓库的/api/index.py,即可创建成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- coding: UTF-8 -*-
import requests
import re
from http.server import BaseHTTPRequestHandler
import json

def list_split(items, n):
return [items[i:i + n] for i in range(0, len(items), n)]
def getdata(name):
gitpage = requests.get("https://github.com/" + name)
data = gitpage.text
datadatereg = re.compile(r'data-date="(.*?)" data-level')
datacountreg = re.compile(r'rx="2" ry="2">(.*?) contribution')
datadate = datadatereg.findall(data)
datacount = datacountreg.findall(data)
datacount = list(map(int, [0 if i == "No" else i for i in datacount]))
contributions = sum(datacount)
datalist = []
for index, item in enumerate(datadate):
itemlist = {"date": item, "count": datacount[index]}
datalist.append(itemlist)
datalistsplit = list_split(datalist, 7)
returndata = {
"total": contributions,
"contributions": datalistsplit
}
return returndata
class handler(BaseHTTPRequestHandler):
def do_GET(self):
path = self.path
user = path.split('?')[1]
data = getdata(user)
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(data).encode('utf-8'))
return