Skip to content

Commit

Permalink
修改resource配置
Browse files Browse the repository at this point in the history
  • Loading branch information
liangliangyy committed Mar 1, 2023
1 parent 7243508 commit ede88b3
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 38 deletions.
4 changes: 3 additions & 1 deletion blog/management/commands/sync_user_avatar.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.core.management.base import BaseCommand
from django.template.context_processors import static

from djangoblog.utils import save_user_avatar
from oauth.models import OAuthUser
Expand All @@ -8,8 +9,9 @@ class Command(BaseCommand):
help = 'sync user avatar'

def handle(self, *args, **options):
static_url = static("avatar/")
users = OAuthUser.objects.filter(picture__isnull=False).exclude(
picture__istartswith='https://resource.lylinux.net').all()
picture__istartswith=static_url).all()
self.stdout.write('开始同步{count}个用户头像'.format(count=len(users)))
for u in users:
self.stdout.write('开始同步:{id}'.format(id=u.nikename))
Expand Down
7 changes: 1 addition & 6 deletions blog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ class BlogSettings(models.Model):
article_sub_length = models.IntegerField("文章摘要长度", default=300)
sidebar_article_count = models.IntegerField("侧边栏文章数目", default=10)
sidebar_comment_count = models.IntegerField("侧边栏评论数目", default=5)
article_comment_count = models.IntegerField("文章评论数目", default=5)
article_comment_count = models.IntegerField("文章页面默认显示评论数目", default=5)
show_google_adsense = models.BooleanField('是否显示谷歌广告', default=False)
google_adsense_codes = models.TextField(
'广告内容', max_length=2000, null=True, blank=True, default='')
Expand All @@ -343,11 +343,6 @@ class BlogSettings(models.Model):
null=True,
blank=True,
default='')
resource_path = models.CharField(
"静态文件保存地址",
max_length=300,
null=False,
default='/var/www/resource/')

class Meta:
verbose_name = '网站配置'
Expand Down
4 changes: 2 additions & 2 deletions blog/templatetags/blog_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from django.db.models import Q
from django.shortcuts import get_object_or_404
from django.template.defaultfilters import stringfilter
from django.templatetags.static import static
from django.urls import reverse
from django.utils.safestring import mark_safe

Expand Down Expand Up @@ -295,8 +296,7 @@ def gravatar_url(email, size=40):
return o[0].picture
email = email.encode('utf-8')

default = "https://resource.lylinux.net/image/2017/03/26/120117.jpg".encode(
'utf-8')
default = static('blog/images/default_avatar.jpg')

url = "https://www.gravatar.com/avatar/%s?%s" % (hashlib.md5(
email.lower()).hexdigest(), urllib.parse.urlencode({'d': default, 's': str(size)}))
Expand Down
21 changes: 7 additions & 14 deletions blog/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.shortcuts import render
from django.templatetags.static import static
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.detail import DetailView
Expand Down Expand Up @@ -313,20 +314,11 @@ def fileupload(request):
imgextensions = ['jpg', 'png', 'jpeg', 'bmp']
fname = u''.join(str(filename))
isimage = len([i for i in imgextensions if fname.find(i) >= 0]) > 0
blogsetting = get_blog_setting()

basepath = r'{basedir}/{type}/{timestr}'.format(
basedir=blogsetting.resource_path,
type='files' if not isimage else 'image',
timestr=timestr)
if settings.TESTING:
basepath = settings.BASE_DIR + '/uploads'
url = 'https://resource.lylinux.net/{type}/{timestr}/{filename}'.format(
type='files' if not isimage else 'image', timestr=timestr, filename=filename)
if not os.path.exists(basepath):
os.makedirs(basepath)
savepath = os.path.normpath(os.path.join(basepath, f"{uuid.uuid4().hex}{os.path.splitext(filename)[-1]}"))
if not savepath.startswith(basepath):
base_dir = os.path.join(settings.STATICFILES, "files" if not isimage else "image", timestr)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
savepath = os.path.normpath(os.path.join(base_dir, f"{uuid.uuid4().hex}{os.path.splitext(filename)[-1]}"))
if not savepath.startswith(base_dir):
return HttpResponse("only for post")
with open(savepath, 'wb+') as wfile:
for chunk in request.FILES[filename].chunks():
Expand All @@ -335,6 +327,7 @@ def fileupload(request):
from PIL import Image
image = Image.open(savepath)
image.save(savepath, quality=20, optimize=True)
url = static(savepath)
response.append(url)
return HttpResponse(response)

Expand Down
33 changes: 21 additions & 12 deletions djangoblog/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@

import markdown
import requests
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.templatetags.static import static

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -179,27 +181,26 @@ def save_user_avatar(url):
logger.info(url)

try:
basedir = os.path.join(settings.STATICFILES, 'avatar')

imgname = url.split('/')[-1]
if imgname:
path = r'{basedir}/avatar/{img}'.format(
basedir=setting.resource_path, img=imgname)
path = f'{basedir}/{imgname}'
if os.path.exists(path):
os.remove(path)
rsp = requests.get(url, timeout=2)
if rsp.status_code == 200:
basepath = r'{basedir}/avatar/'.format(
basedir=setting.resource_path)
if not os.path.exists(basepath):
os.makedirs(basepath)
if not os.path.exists(basedir):
os.makedirs(basedir)

imgextensions = ['.jpg', '.png', 'jpeg', '.gif']
isimage = len([i for i in imgextensions if url.endswith(i)]) > 0
image_extensions = ['.jpg', '.png', 'jpeg', '.gif']
isimage = len([i for i in image_extensions if url.endswith(i)]) > 0
ext = os.path.splitext(url)[1] if isimage else '.jpg'
savefilename = str(uuid.uuid4().hex) + ext
logger.info('保存用户头像:' + basepath + savefilename)
with open(basepath + savefilename, 'wb+') as file:
save_filename = str(uuid.uuid4().hex) + ext
logger.info('保存用户头像:' + basedir + save_filename)
with open(os.path.join(basedir, save_filename), 'wb+') as file:
file.write(rsp.content)
return 'https://resource.lylinux.net/avatar/' + savefilename
return static('avatar/' + save_filename)
except Exception as e:
logger.error(e)
return url
Expand All @@ -217,3 +218,11 @@ def delete_view_cache(prefix, keys):
from django.core.cache.utils import make_template_fragment_key
key = make_template_fragment_key(prefix, keys)
cache.delete(key)


def get_resource_url():
if settings.STATIC_URL:
return settings.STATIC_URL
else:
site = get_current_site()
return 'http://' + site.domain + '/static/'
18 changes: 15 additions & 3 deletions oauth/tests.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
from django.test import TestCase
from django.test import Client, RequestFactory, TestCase

from .models import OAuthConfig
from oauth.models import OAuthConfig


# Create your tests here.
class OAuthConfigTest(TestCase):
def config_save_test(self):
def setUp(self):
self.client = Client()
self.factory = RequestFactory()

def test_oauth_login_test(self):
c = OAuthConfig()
c.type = 'weibo'
c.appkey = 'appkey'
c.appsecret = 'appsecret'
c.save()

response = self.client.get('/oauth/oauthlogin?type=weibo')
self.assertEqual(response.status_code, 302)
self.assertTrue("api.weibo.com" in response.url)

response = self.client.get('/oauth/authorize?type=weibo&code=code')
self.assertEqual(response.status_code, 302)
self.assertEqual(response.url, '/')

0 comments on commit ede88b3

Please sign in to comment.