此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结
投诉
前段时间被打了,导致图床寄了,索性用github当做图床防止再次欠费
之前用的七牛云(害)
亏损了大概一千元,家人谁懂啊
配置跨域
django需要调用github的api进行传照片, 所以要配置跨域
这个是在settings文件里
1 2 3 4 5 6 7 8 9
| INSTALLED_APPS = [ 'corsheaders', ]
MIDDLEWARE = [ 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', ]
|
views.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 40 41 42 43 44 45
| def save_to_github(filename, content): url = f"{settings.GITHUB_API_URL}/repos/{settings.GITHUB_OWNER}/{settings.GITHUB_REPO}/contents/{filename}" headers = { 'Authorization': f'token {settings.GITHUB_TOKEN}', 'Content-Type': 'application/json' } data = { 'message': f'Add {filename}', 'content': content, 'branch': settings.GITHUB_BRANCH } response = requests.put(url, headers=headers, json=data) if response.status_code == 201: return True return False @method_decorator(csrf_exempt, name='dispatch') class UploadImageAPIView(APIView): def post(self, request): if request.FILES: image_file = request.FILES.get('image') file_format = image_file.name.split('.')[-1] filename = 'ouchelper/' + f'{uuid1().hex}.{file_format}' content = base64.b64encode(image_file.file.read()).decode('utf-8') if save_to_github(filename, content): # image_url = f"https://raw.githubusercontent.com/{settings.GITHUB_OWNER}/{settings.GITHUB_REPO}/{settings.GITHUB_BRANCH}/{filename}" image_url = f"https://picture.daoxuan.cc/{filename}" data = { 'success': True, 'url': image_url, } return Response(data) else: data = { 'success': False, 'message': 'Failed to upload image' } return Response(data) else: data = { 'success': False, 'message': 'Unsupported file format' } return Response(data)
|
函数大概就是这个样子GITHUB_API_URL、GITHUB_OWNER、GITHUB_REPO都放在settings里面
GITHUB_TOKEN是token,怎么申请可以在网上搜索教程,正常的url应该是image_url = f”https://raw.githubusercontent.com/{settings.GITHUB_OWNER}/{settings.GITHUB_REPO}/{settings.GITHUB_BRANCH}/{filename}"这样的,只不过我使用cloudfare的worker代理了一下,所以绑定自己的域名进行访问了。