diff options
author | Wojciech Polak <wojciechpolak@gmail.com> | 2021-04-05 17:55:19 +0200 |
---|---|---|
committer | Wojciech Polak <wojciechpolak@gmail.com> | 2021-04-05 17:55:19 +0200 |
commit | 1e5698196290a41a2f53b71e2fdf5224d6bb2345 (patch) | |
tree | 6d3c98d32c895a2588b0dca524a0b3a5364673f7 | |
parent | 1c4dc61bb512a12ef0863cc47cd6c6845cdecbd2 (diff) | |
download | glifestream-1e5698196290a41a2f53b71e2fdf5224d6bb2345.tar.gz glifestream-1e5698196290a41a2f53b71e2fdf5224d6bb2345.tar.bz2 |
Misc code fixes
-rw-r--r-- | .pylintrc | 14 | ||||
-rw-r--r-- | INSTALL.md | 2 | ||||
-rw-r--r-- | glifestream/apis/flickr.py | 2 | ||||
-rw-r--r-- | glifestream/apis/vimeo.py | 4 | ||||
-rw-r--r-- | glifestream/apis/youtube.py | 1 | ||||
-rw-r--r-- | glifestream/filters/expand.py | 33 | ||||
-rw-r--r-- | glifestream/filters/truncate.py | 10 | ||||
-rw-r--r-- | glifestream/filters/twyntax.py | 24 | ||||
-rw-r--r-- | glifestream/gauth/forms.py | 2 | ||||
-rw-r--r-- | glifestream/gauth/models.py | 2 | ||||
-rw-r--r-- | glifestream/gauth/views.py | 5 | ||||
-rw-r--r-- | glifestream/settings_sample.py (renamed from glifestream/settings-sample.py) | 2 | ||||
-rw-r--r-- | glifestream/stream/admin.py | 1 | ||||
-rw-r--r-- | glifestream/stream/media.py | 6 | ||||
-rw-r--r-- | glifestream/stream/models.py | 12 | ||||
-rw-r--r-- | glifestream/stream/pshb.py | 24 | ||||
-rw-r--r-- | glifestream/stream/views.py | 47 | ||||
-rw-r--r-- | glifestream/usettings/views.py | 96 | ||||
-rw-r--r-- | requirements.txt | 1 | ||||
-rwxr-xr-x | worker.py | 2 |
20 files changed, 140 insertions, 150 deletions
@@ -28,7 +28,7 @@ limit-inference-results=100 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. -load-plugins= +load-plugins=pylint_django # Pickle collected data for later comparisons. persistent=yes @@ -139,7 +139,11 @@ disable=print-statement, deprecated-sys-function, exception-escape, comprehension-escape, - missing-docstring + missing-docstring, + too-many-branches, + too-many-locals, + too-many-statements, + too-many-return-statements # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option @@ -192,14 +196,14 @@ argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. -#argument-rgx= +argument-rgx=[a-z_][a-z0-9_]{0,30}$ # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. -#attr-rgx= +attr-rgx=[a-z_][a-z0-9_]{0,30}$ # Bad variable names which should always be refused, separated by a comma. bad-names=foo, @@ -291,7 +295,7 @@ variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. -#variable-rgx= +variable-rgx=[a-z_][a-z0-9_]{0,30}$ [MISCELLANEOUS] @@ -35,7 +35,7 @@ Installation instructions ========================= 1. Change the current working directory into the `glifestream` directory. -2. Copy `settings-sample.py` to `settings.py` and edit your local site +2. Copy `settings_sample.py` to `settings.py` and edit your local site configuration. 3. Run `python manage.py syncdb` 4. Run `python manage.py compilemessages` (if you have 'gettext' installed) diff --git a/glifestream/apis/flickr.py b/glifestream/apis/flickr.py index 6e66de0..c4a77da 100644 --- a/glifestream/apis/flickr.py +++ b/glifestream/apis/flickr.py @@ -15,7 +15,7 @@ from itertools import groupby from django.utils.translation import ugettext as _ -from glifestream.utils.time import mtime, now +from glifestream.utils.time import mtime from glifestream.stream.models import Entry from glifestream.stream import media from glifestream.apis import webfeed diff --git a/glifestream/apis/vimeo.py b/glifestream/apis/vimeo.py index 9754fba..e397073 100644 --- a/glifestream/apis/vimeo.py +++ b/glifestream/apis/vimeo.py @@ -159,9 +159,9 @@ class API: pass -def get_thumbnail_url(id): +def get_thumbnail_url(id_video): try: - r = httpclient.get('https://vimeo.com/api/v2/video/%s.json' % id) + r = httpclient.get('https://vimeo.com/api/v2/video/%s.json' % id_video) if r.status_code == 200: jsn = r.json() if 'thumbnail_large' in jsn[0]: diff --git a/glifestream/apis/youtube.py b/glifestream/apis/youtube.py index e148c4c..ce6e865 100644 --- a/glifestream/apis/youtube.py +++ b/glifestream/apis/youtube.py @@ -84,7 +84,6 @@ class API: def process(self, url): for ent in self.json.get('items', ()): snippet = ent.get('snippet', {}) - date = snippet['publishedAt'][:10] vid = ent['contentDetails']['videoId'] if self.playlist_types[url] == 'favorite': diff --git a/glifestream/filters/expand.py b/glifestream/filters/expand.py index cbe5830..23355cd 100644 --- a/glifestream/filters/expand.py +++ b/glifestream/filters/expand.py @@ -69,8 +69,7 @@ def __sp_flickr(m): j = oembed.discover(url, provider='flickr', maxwidth=400) if j and j['type'] == 'photo': return __gen_tai(url, j['url']) - else: - return url + return url def __sp_imgloc(m): @@ -102,47 +101,46 @@ def imgloc(s): def __sv_youtube(m): if m.start() > 0 and m.string[m.start() - 1] == '"': return m.group(0) - id = m.group(2) + id_video = m.group(2) rest = m.group(3) ltag = rest.find('<') if rest else -1 rest = rest[ltag:] if ltag != -1 else '' - link = 'https://www.youtube.com/watch?v=%s' % id - imgurl = 'https://i.ytimg.com/vi/%s/mqdefault.jpg' % id + link = 'https://www.youtube.com/watch?v=%s' % id_video + imgurl = 'https://i.ytimg.com/vi/%s/mqdefault.jpg' % id_video imgurl = media.save_image(imgurl, downscale=True, size=(320, 180)) return '<table class="vc"><tr><td><div data-id="youtube-%s" class="play-video"><a href="%s" rel="nofollow">' \ '<img src="%s" width="320" height="180" alt="YouTube Video" /></a><div class="playbutton">' \ - '</div></div></td></tr></table>%s' % (id, link, imgurl, rest) + '</div></div></td></tr></table>%s' % (id_video, link, imgurl, rest) def __sv_vimeo(m): from glifestream.apis import vimeo if m.start() > 0 and m.string[m.start() - 1] == '"': return m.group(0) - id = m.group(2) + id_video = m.group(2) link = m.group(0) - imgurl = vimeo.get_thumbnail_url(id) + imgurl = vimeo.get_thumbnail_url(id_video) if imgurl: imgurl = media.save_image(imgurl, downscale=True, size=(320, 180)) return '<table class="vc"><tr><td><div data-id="vimeo-%s" class="play-video"><a href="%s" rel="nofollow">' \ '<img src="%s" width="320" height="180" alt="Vimeo Video" /></a>' \ '<div class="playbutton"></div></div></td></tr></table>' % ( - id, link, imgurl) - else: - return link + id_video, link, imgurl) + return link def __sv_dailymotion(m): link = strip_tags(m.group(0)) - id = m.group(1) + id_video = m.group(1) rest = m.group(2) ltag = rest.find('<') if rest else -1 rest = rest[ltag:] if ltag != -1 else '' - imgurl = 'https://www.dailymotion.com/thumbnail/video/%s' % id + imgurl = 'https://www.dailymotion.com/thumbnail/video/%s' % id_video imgurl = media.save_image(imgurl) return '<table class="vc"><tr><td><div data-id="dailymotion-%s" class="play-video"><a href="%s" rel="nofollow">' \ '<img src="%s" width="320" height="180" alt="Dailymotion Video" />' \ '</a><div class="playbutton"></div></div></td></tr></table>%s' % ( - id, link, imgurl, rest) + id_video, link, imgurl, rest) def videolinks(s): @@ -165,8 +163,8 @@ def videolinks(s): def __sa_ogg(m): link = m.group(1) name = m.group(2) - id = hashlib.md5(link).hexdigest() - return '<span data-id="audio-%s" class="play-audio"><a href="%s">%s</a></span>' % (id, link, name) + id_audio = hashlib.md5(link).hexdigest() + return '<span data-id="audio-%s" class="play-audio"><a href="%s">%s</a></span>' % (id_audio, link, name) def __sa_thesixtyone(m): @@ -213,8 +211,7 @@ def __sm_googlemaps(m): return '<div class="geo"><a href="%s" class="map"><span class="latitude">%.10f</span> ' \ '<span class="longitude">%.10f</span></a></div>%s' % ( link, geolat, geolng, rest) - else: - return link + return link def maplinks(s): diff --git a/glifestream/filters/truncate.py b/glifestream/filters/truncate.py index 5d4ff54..f328e0b 100644 --- a/glifestream/filters/truncate.py +++ b/glifestream/filters/truncate.py @@ -18,9 +18,8 @@ def simple(content, max_length=36, suffix='...'): content = content.strip() if len(content) <= max_length: return content - else: - content = content[:max_length].rsplit(' ', 1)[0].rstrip(' -/,:.') - return content + suffix + content = content[:max_length].rsplit(' ', 1)[0].rstrip(' -/,:.') + return content + suffix def smart(content, max_words=7, max_length=36, suffix='...'): @@ -32,6 +31,5 @@ def smart(content, max_words=7, max_length=36, suffix='...'): sx = suffix if len(content) <= max_length: return content.rstrip(' -/,:.') + sx - else: - content = content[:max_length].rsplit(' ', 1)[0].rstrip(' -/,:.') - return content + suffix + content = content[:max_length].rsplit(' ', 1)[0].rstrip(' -/,:.') + return content + suffix diff --git a/glifestream/filters/twyntax.py b/glifestream/filters/twyntax.py index 40c5a4a..da9ae89 100644 --- a/glifestream/filters/twyntax.py +++ b/glifestream/filters/twyntax.py @@ -16,32 +16,24 @@ import re -def parse(s, type='twitter'): +def parse(s, syntax_type='twitter'): from glifestream.stream.templatetags.gls_filters import gls_urlizetrunc - if type == 'twitter': + if syntax_type == 'twitter': s = s.split(': ', 1)[1] - s = hash_tag(s, type) - s = at_reply(s, type) + s = hash_tag(s) + s = at_reply(s) s = gls_urlizetrunc(s, 45) return s -def at_reply(tweet, type='twitter'): +def at_reply(tweet): pattern = re.compile(r"(\A|\W)@(?P<user>\w+)(\Z|\W)") - if type == 'identica': - repl = (r'\1@<a href="http://identi.ca/\g<user>"' - r' title="\g<user> on Identi.ca" rel="nofollow">\g<user></a>\3') - else: - repl = (r'\1@<a href="https://twitter.com/\g<user>"' - r' title="\g<user> on Twitter" rel="nofollow">\g<user></a>\3') + repl = (r'\1@<a href="https://twitter.com/\g<user>"' + r' title="\g<user> on Twitter" rel="nofollow">\g<user></a>\3') return pattern.sub(repl, tweet) -def hash_tag(tweet, type='twitter'): - if type == 'identica': - return re.sub(r'(\A|\s)#(\w[\w\-]+)', - r'\1#<a href="http://identi.ca/tag/\2" title="#\2 search Identi.ca" rel="nofollow">\2</a>', - tweet) +def hash_tag(tweet): return re.sub(r'(\A|\s)#(\w[\w\-]+)', r'\1#<a href="https://twitter.com/search/%23\2" title="#\2 search Twitter" rel="nofollow">\2</a>', tweet) diff --git a/glifestream/gauth/forms.py b/glifestream/gauth/forms.py index a47bc45..687375e 100644 --- a/glifestream/gauth/forms.py +++ b/glifestream/gauth/forms.py @@ -18,7 +18,7 @@ from django.contrib.auth.forms import AuthenticationForm from django.utils.translation import ugettext_lazy as _ -class AuthenticationRememberMeForm (AuthenticationForm): +class AuthenticationRememberMeForm(AuthenticationForm): remember_me = forms.BooleanField(label=_('Remember Me'), initial=False, required=False) diff --git a/glifestream/gauth/models.py b/glifestream/gauth/models.py index 62579b5..041976c 100644 --- a/glifestream/gauth/models.py +++ b/glifestream/gauth/models.py @@ -39,7 +39,7 @@ class OAuthClient (models.Model): class Meta: verbose_name = 'OAuth' verbose_name_plural = 'OAuth' - ordering = 'service', + ordering = ('service',) def __str__(self): return u'%s: %s' % (self.service, self.identifier) diff --git a/glifestream/gauth/views.py b/glifestream/gauth/views.py index b2ade75..3aeec33 100644 --- a/glifestream/gauth/views.py +++ b/glifestream/gauth/views.py @@ -15,6 +15,7 @@ from django.conf import settings from django.urls import reverse +from django.contrib.auth import login as django_login from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.sites.models import Site from django.contrib.sites.requests import RequestSite @@ -41,8 +42,7 @@ def login(request, template_name='login.html', if not form.cleaned_data['remember_me']: request.session.set_expiry(0) - from django.contrib.auth import login - login(request, form.get_user()) + django_login(request, form.get_user()) if request.session.test_cookie_worked(): request.session.delete_test_cookie() @@ -71,4 +71,3 @@ def login(request, template_name='login.html', 'site_name': current_site.name, 'is_secure': request.is_secure(), redirect_field_name: redirect_to}) - diff --git a/glifestream/settings-sample.py b/glifestream/settings_sample.py index 666a138..2163efb 100644 --- a/glifestream/settings-sample.py +++ b/glifestream/settings_sample.py @@ -70,6 +70,8 @@ LOGIN_URL = '/login' # Make this unique, and don't share it with anybody. SECRET_KEY = 'YOUR-SECRET-KEY' +assert SECRET_KEY != 'YOUR-SECRET-KEY', 'SECRET_KEY must be long and unique.' + MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', diff --git a/glifestream/stream/admin.py b/glifestream/stream/admin.py index a16769d..ff668c0 100644 --- a/glifestream/stream/admin.py +++ b/glifestream/stream/admin.py @@ -20,7 +20,6 @@ from django.contrib.admin.widgets import AdminFileWidget from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from glifestream.stream.models import Service, Entry, Media, Favorite, List -from glifestream.stream import media def deactivate(modeladmin, request, queryset): diff --git a/glifestream/stream/media.py b/glifestream/stream/media.py index 795c37b..1c6b7b9 100644 --- a/glifestream/stream/media.py +++ b/glifestream/stream/media.py @@ -117,9 +117,9 @@ def downsave_uploaded_image(file): def extract_and_register(entry): - for hash in re.findall(r'\[GLS-THUMBS\]/([a-f0-9]{40})', entry.content): + for hash_thumb in re.findall(r'\[GLS-THUMBS\]/([a-f0-9]{40})', entry.content): md = Media(entry=entry) - md.file.name = get_thumb_info(hash)['rel'] + md.file.name = get_thumb_info(hash_thumb)['rel'] try: md.save() except: @@ -171,7 +171,7 @@ def mrss_gen_xml(entry): mblob = json.loads(entry.mblob) if 'content' in mblob: for g in mblob['content']: - group = True if len(g) > 1 else False + group = len(g) > 1 if group: m += ' <media:group>\n' for i in g: diff --git a/glifestream/stream/models.py b/glifestream/stream/models.py index d8fdc9c..5775398 100644 --- a/glifestream/stream/models.py +++ b/glifestream/stream/models.py @@ -15,7 +15,6 @@ from __future__ import unicode_literals -from django.conf import settings from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify @@ -54,7 +53,8 @@ class Service (models.Model): active = models.BooleanField(_('Active'), default=True, help_text=_('If not active, this service will not be further updated.')) home = models.BooleanField(_('Home visible'), default=True, - help_text=_('If unchecked, this stream will be still active, but hidden and thus visible only via custom lists.')) + help_text=_('If unchecked, this stream will be still active, but hidden and thus ' + 'visible only via custom lists.')) class Meta: verbose_name = _('Service') @@ -110,7 +110,7 @@ class Entry (models.Model): class Meta: verbose_name = _('Entry') verbose_name_plural = _('Entries') - ordering = '-date_published', + ordering = ('-date_published',) unique_together = (('service', 'guid'),) def __str__(self): @@ -140,7 +140,7 @@ class Favorite (models.Model): class Meta: verbose_name = _('Favorite') verbose_name_plural = _('Favorites') - ordering = '-date_added', + ordering = ('-date_added',) unique_together = (('user', 'entry'),) def __str__(self): @@ -157,7 +157,7 @@ class List (models.Model): class Meta: verbose_name = _('List') verbose_name_plural = _('Lists') - ordering = 'name', + ordering = ('name',) unique_together = (('user', 'slug'),) def save(self): @@ -180,5 +180,5 @@ class Pshb (models.Model): class Meta: verbose_name = 'PSHB' verbose_name_plural = 'PSHB' - ordering = 'service', + ordering = ('service',) unique_together = (('hash', 'service', 'hub'),) diff --git a/glifestream/stream/pshb.py b/glifestream/stream/pshb.py index 71f0f27..d6980bf 100644 --- a/glifestream/stream/pshb.py +++ b/glifestream/stream/pshb.py @@ -56,18 +56,18 @@ def subscribe(service, verbose=False): secret = hashlib.md5('%s:%d/%s/%s' % (hub, service.id, api.url, settings.SECRET_KEY)).hexdigest() - hash = hashlib.sha1(secret).hexdigest()[0:20] + hash_sub = hashlib.sha1(secret).hexdigest()[0:20] secret = secret[0:8] if 'https://' in hub else None save_db = False try: - db = Pshb.objects.get(hash=hash, service=service) + db = Pshb.objects.get(hash=hash_sub, service=service) except Pshb.DoesNotExist: - db = Pshb(hash=hash, service=service, hub=hub, secret=secret) + db = Pshb(hash=hash_sub, service=service, hub=hub, secret=secret) save_db = True topic = __get_absolute_url(reverse('index')) + '?format=atom' - callback = __get_absolute_url(reverse('pshb', args=[hash])) + callback = __get_absolute_url(reverse('pshb', args=[hash_sub])) if settings.PSHB_HTTPS_CALLBACK: callback = callback.replace('http://', 'https://') @@ -97,9 +97,9 @@ def subscribe(service, verbose=False): return {'hub': hub, 'rc': error} -def unsubscribe(id, verbose=False): +def unsubscribe(id_sub, verbose=False): try: - db = Pshb.objects.get(id=id) + db = Pshb.objects.get(id=id_sub) except Pshb.DoesNotExist: return {'rc': 1} @@ -130,13 +130,13 @@ def unsubscribe(id, verbose=False): return {'hub': db.hub, 'rc': error} -def verify(id, GET): +def verify(id_sub, GET): mode = GET.get('hub.mode', None) lease_seconds = GET.get('hub.lease_seconds', None) if mode == 'subscribe': try: - db = Pshb.objects.get(hash=id) + db = Pshb.objects.get(hash=id_sub) db.verified = True if lease_seconds: db.expire = now() + timedelta(seconds=int(lease_seconds)) @@ -145,7 +145,7 @@ def verify(id, GET): return False elif mode == 'unsubscribe': try: - Pshb.objects.get(hash=id).delete() + Pshb.objects.get(hash=id_sub).delete() except Pshb.DoesNotExist: return False @@ -179,9 +179,9 @@ def publish(hubs=None, verbose=False): print('%s, Response: "%s"' % (e, error)) -def accept_payload(id, payload, meta={}): +def accept_payload(id_sub, payload, meta={}): try: - db = Pshb.objects.get(hash=id) + db = Pshb.objects.get(hash=id_sub) except Pshb.DoesNotExist: return False if db.secret: @@ -212,7 +212,7 @@ def renew_subscriptions(force=False, verbose=False): subscribe(s.service, verbose) -def list(raw=False): +def list_subs(raw=False): subscriptions = Pshb.objects.all().order_by('id') if raw: return subscriptions diff --git a/glifestream/stream/views.py b/glifestream/stream/views.py index c0cc09e..bff5b49 100644 --- a/glifestream/stream/views.py +++ b/glifestream/stream/views.py @@ -13,7 +13,6 @@ # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. -import json import time import datetime from functools import reduce @@ -27,6 +26,7 @@ from django.http import HttpResponseRedirect from django.http import HttpResponseNotFound from django.http import HttpResponsePermanentRedirect from django.http import Http404 +from django.http import JsonResponse from django.shortcuts import render from django.template.loader import render_to_string from django.template.defaultfilters import truncatewords @@ -85,10 +85,10 @@ def index(request, **args): dt = datetime.date(year, month, day).strftime('%Y/%m/%d') elif year and month: dt = datetime.date(year, month, 1) - prev, next = pn_month_start(dt) + month_prev, month_next = pn_month_start(dt) page['month_nav'] = True - page['month_prev'] = prev.strftime('%Y/%m') - page['month_next'] = next.strftime('%Y/%m') + page['month_prev'] = month_prev.strftime('%Y/%m') + page['month_next'] = month_next.strftime('%Y/%m') dt = dt.strftime('%Y/%m') elif year: dt = datetime.date(year, 1, 1).strftime('%Y') @@ -227,7 +227,7 @@ def index(request, **args): select = "SELECT * FROM %s WHERE MATCH('%s')" if page['public']: select += ' AND public=1' - if 'friends_only' in sfs and sfs['friends_only'] == False: + if 'friends_only' in sfs and sfs['friends_only'] is False: select += ' AND friends_only=0' select += ' LIMIT 1000' @@ -281,7 +281,7 @@ def index(request, **args): page['copyright_years'] = crymin # Build URL params for links. - if len(urlparams): + if len(urlparams) > 0: urlparams = '?' + reduce(lambda x, y: x + '&' + y, urlparams, '')[1:] + '&' else: urlparams = '?' @@ -304,7 +304,7 @@ def index(request, **args): # Set page theme. page['themes'] = settings.THEMES - page['themes_more'] = True if len(settings.THEMES) > 1 else False + page['themes_more'] = len(settings.THEMES) > 1 page['theme'] = common.get_theme(request) # Setup links. @@ -346,17 +346,17 @@ def index(request, **args): page['title'] = page_title # Pickup right output format and finish. - format = request.GET.get('format', 'html') - if format == 'atom': + output_format = request.GET.get('format', 'html') + if output_format == 'atom': return render(request, 'stream.atom', {'entries': entries, 'page': page}, content_type='application/atom+xml') - elif format == 'json': + elif output_format == 'json': cb = request.GET.get('callback', False) return render(request, 'stream.json', {'entries': entries, 'page': page, 'callback': cb}, content_type='application/json') - elif format == 'html-pure' and request.is_ajax(): + elif output_format == 'html-pure' and request.is_ajax(): # Check which entry is already favorite. if authed and page['ctx'] != 'favorites': ents = [entry.id for entry in entries] @@ -379,8 +379,8 @@ def index(request, **args): } if 'nextpage' in page: d['next'] = page['nextpage'] - return HttpResponse(json.dumps(d), content_type='application/json') - elif format != 'html': + return JsonResponse(d) + elif output_format != 'html': raise Http404 else: # Check which entry is already favorite. @@ -457,7 +457,7 @@ def pshb_dispatcher(request, **args): raise Http404 -def page_not_found(request, exception): +def page_not_found(request, exception): # pylint: disable=unused-argument page = { 'robots': 'noindex', 'base_url': settings.BASE_URL, @@ -499,7 +499,7 @@ def api(request, **args): d = [] for s in srvs: d.append({'id': s['id'], 'cls': s['cls']}) - return HttpResponse(json.dumps(d), content_type='application/json') + return JsonResponse(d) elif cmd == 'share': images = [] @@ -524,8 +524,7 @@ def api(request, **args): if source == 'bookmarklet': d = {'close_msg': _( "You've successfully shared this web page at your stream.")} - return HttpResponse(json.dumps(d), - content_type='application/json') + return JsonResponse(d) else: entry.friends_only = False if request.is_ajax(): @@ -547,7 +546,7 @@ def api(request, **args): return render(request, 'stream-pure.html', {'entries': (entry,), 'authed': authed}) - except Exception: + except Entry.DoesNotExist: pass elif cmd == 'favorite': @@ -555,14 +554,14 @@ def api(request, **args): entry = Entry.objects.get(id=int(entry)) if entry: try: - fav = Favorite.objects.get(user=request.user, entry=entry) + Favorite.objects.get(user=request.user, entry=entry) except Favorite.DoesNotExist: fav = Favorite(user=request.user, entry=entry) fav.save() media.transform_to_local(entry) media.extract_and_register(entry) entry.save() - except Exception: + except Entry.DoesNotExist: pass elif cmd == 'unfavorite': @@ -572,7 +571,7 @@ def api(request, **args): if entry: Favorite.objects.get(user=request.user, entry=entry).delete() - except Exception: + except Entry.DoesNotExist: pass elif cmd == 'getcontent': @@ -591,7 +590,7 @@ def api(request, **args): entry.friends_only = False content = fix_ampersands(gls_content('', entry)) return HttpResponse(content) - except Exception: + except Entry.DoesNotExist: pass elif cmd == 'putcontent': @@ -605,14 +604,14 @@ def api(request, **args): if entry: content = fix_ampersands(gls_content('', entry)) return HttpResponse(content) - except Exception: + except Entry.DoesNotExist: pass return HttpResponse() def __dictfetchall(cursor): - "Returns all rows from a cursor as a dict" + """Returns all rows from a cursor as a dict""" desc = cursor.description return [ dict(list(zip([col[0] for col in desc], row))) diff --git a/glifestream/usettings/views.py b/glifestream/usettings/views.py index 61e5584..cc2b9d1 100644 --- a/glifestream/usettings/views.py +++ b/glifestream/usettings/views.py @@ -14,11 +14,11 @@ # with this program. If not, see <http://www.gnu.org/licenses/>. import re -import json from django.conf import settings from django.urls import reverse from django.shortcuts import render from django.contrib.auth.decorators import login_required +from django.http import JsonResponse from django.http import HttpResponse from django.http import HttpResponseForbidden from django.http import HttpResponseRedirect @@ -44,19 +44,19 @@ def services(request, **args): 'base_url': settings.BASE_URL, 'favicon': settings.FAVICON, 'themes': settings.THEMES, - 'themes_more': True if len(settings.THEMES) > 1 else False, + 'themes_more': len(settings.THEMES) > 1, 'theme': common.get_theme(request), 'title': _('Services - Settings'), 'menu': 'services', } - services = Service.objects.all().order_by('api', 'name') + services_all = Service.objects.all().order_by('api', 'name') return render(request, 'services.html', {'page': page, 'authed': authed, 'is_secure': request.is_secure(), 'user': request.user, 'services_supported': API_LIST, - 'services': services}) + 'services': services_all}) class ListForm (ModelForm): @@ -77,42 +77,41 @@ def lists(request, **args): 'base_url': settings.BASE_URL, 'favicon': settings.FAVICON, 'themes': settings.THEMES, - 'themes_more': True if len(settings.THEMES) > 1 else False, + 'themes_more': len(settings.THEMES) > 1, 'theme': common.get_theme(request), 'title': _('Lists - Settings'), 'menu': 'lists', } curlist = '' - lists = List.objects.filter(user=request.user).order_by('name') + lists_user = List.objects.filter(user=request.user).order_by('name') if 'list' in args: try: - list = List.objects.get(user=request.user, slug=args['list']) + list_user = List.objects.get(user=request.user, slug=args['list']) curlist = args['list'] except List.DoesNotExist: - list = List(user=request.user) + list_user = List(user=request.user) else: - list = List(user=request.user) + list_user = List(user=request.user) if request.method == 'POST': if request.POST.get('delete', False): - list.delete() + list_user.delete() return HttpResponseRedirect(reverse('usettings-lists')) - else: - form = ListForm(request.POST, instance=list) - if form.is_valid(): - form.save() - return HttpResponseRedirect(reverse('usettings-lists-slug', - args=[list.slug])) + form = ListForm(request.POST, instance=list_user) + if form.is_valid(): + form.save() + return HttpResponseRedirect(reverse('usettings-lists-slug', + args=[list_user.slug])) else: - form = ListForm(instance=list) + form = ListForm(instance=list_user) return render(request, 'lists.html', {'page': page, 'authed': authed, 'is_secure': request.is_secure(), 'user': request.user, - 'lists': lists, + 'lists': lists_user, 'curlist': curlist, 'form': form}) @@ -128,7 +127,7 @@ def pshb(re |