Fix pep8 errors using the Django core's flake8 preset

This commit is contained in:
ekmartin 2015-11-07 04:10:49 +01:00
parent 351a18ba07
commit 4469b55d96
15 changed files with 53 additions and 33 deletions

View File

@ -16,4 +16,4 @@ channel_backends = BackendManager(
default_app_config = 'channels.apps.ChannelsConfig' default_app_config = 'channels.apps.ChannelsConfig'
# Promote channel to top-level (down here to avoid circular import errs) # Promote channel to top-level (down here to avoid circular import errs)
from .channel import Channel, Group from .channel import Channel, Group # NOQA

View File

@ -1,10 +1,11 @@
from django.apps import AppConfig from django.apps import AppConfig
class ChannelsConfig(AppConfig): class ChannelsConfig(AppConfig):
name = "channels" name = "channels"
verbose_name = "Channels" verbose_name = "Channels"
def ready(self): def ready(self):
# Do django monkeypatches # Do django monkeypatches
from .hacks import monkeypatch_django from .hacks import monkeypatch_django

View File

@ -13,17 +13,19 @@ class BackendManager(object):
def __init__(self, backend_configs): def __init__(self, backend_configs):
self.configs = backend_configs self.configs = backend_configs
self.backends = {} self.backends = {}
def make_backend(self, name): def make_backend(self, name):
# Load the backend class # Load the backend class
try: try:
backend_class = import_string(self.configs[name]['BACKEND']) backend_class = import_string(self.configs[name]['BACKEND'])
except KeyError: except KeyError:
raise InvalidChannelBackendError("No BACKEND specified for %s" % name) raise InvalidChannelBackendError("No BACKEND specified for %s" % name)
except ImportError as e: except ImportError:
raise InvalidChannelBackendError("Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name)) raise InvalidChannelBackendError("Cannot import BACKEND %r specified for %s" %
(self.configs[name]['BACKEND'], name))
# Initialise and pass config # Initialise and pass config
instance = backend_class(**{k.lower(): v for k, v in self.configs[name].items() if k != "BACKEND"}) instance = backend_class(
**{k.lower(): v for k, v in self.configs[name].items() if k != "BACKEND"})
instance.alias = name instance.alias = name
return instance return instance

View File

@ -1,4 +1,3 @@
import time
import json import json
import datetime import datetime
@ -39,6 +38,7 @@ class DatabaseChannelBackend(BaseChannelBackend):
channel = models.CharField(max_length=200, db_index=True) channel = models.CharField(max_length=200, db_index=True)
content = models.TextField() content = models.TextField()
expiry = models.DateTimeField(db_index=True) expiry = models.DateTimeField(db_index=True)
class Meta: class Meta:
apps = Apps() apps = Apps()
app_label = "channels" app_label = "channels"
@ -60,6 +60,7 @@ class DatabaseChannelBackend(BaseChannelBackend):
group = models.CharField(max_length=200) group = models.CharField(max_length=200)
channel = models.CharField(max_length=200) channel = models.CharField(max_length=200)
expiry = models.DateTimeField(db_index=True) expiry = models.DateTimeField(db_index=True)
class Meta: class Meta:
apps = Apps() apps = Apps()
app_label = "channels" app_label = "channels"
@ -81,6 +82,7 @@ class DatabaseChannelBackend(BaseChannelBackend):
class Lock(models.Model): class Lock(models.Model):
channel = models.CharField(max_length=200, unique=True) channel = models.CharField(max_length=200, unique=True)
expiry = models.DateTimeField(db_index=True) expiry = models.DateTimeField(db_index=True)
class Meta: class Meta:
apps = Apps() apps = Apps()
app_label = "channels" app_label = "channels"
@ -93,9 +95,9 @@ class DatabaseChannelBackend(BaseChannelBackend):
def send(self, channel, message): def send(self, channel, message):
self.channel_model.objects.create( self.channel_model.objects.create(
channel = channel, channel=channel,
content = json.dumps(message), content=json.dumps(message),
expiry = now() + datetime.timedelta(seconds=self.expiry) expiry=now() + datetime.timedelta(seconds=self.expiry)
) )
def receive_many(self, channels): def receive_many(self, channels):
@ -125,9 +127,9 @@ class DatabaseChannelBackend(BaseChannelBackend):
seconds (expiry defaults to message expiry if not provided). seconds (expiry defaults to message expiry if not provided).
""" """
self.group_model.objects.update_or_create( self.group_model.objects.update_or_create(
group = group, group=group,
channel = channel, channel=channel,
defaults = {"expiry": now() + datetime.timedelta(seconds=expiry or self.expiry)}, defaults={"expiry": now() + datetime.timedelta(seconds=expiry or self.expiry)},
) )
def group_discard(self, group, channel): def group_discard(self, group, channel):
@ -152,8 +154,8 @@ class DatabaseChannelBackend(BaseChannelBackend):
# We rely on the UNIQUE constraint for only-one-thread-wins on locks # We rely on the UNIQUE constraint for only-one-thread-wins on locks
try: try:
self.lock_model.objects.create( self.lock_model.objects.create(
channel = channel, channel=channel,
expiry = now() + datetime.timedelta(seconds=expiry or self.expiry), expiry=now() + datetime.timedelta(seconds=expiry or self.expiry),
) )
except IntegrityError: except IntegrityError:
return False return False

View File

@ -7,6 +7,7 @@ queues = {}
groups = {} groups = {}
locks = set() locks = set()
class InMemoryChannelBackend(BaseChannelBackend): class InMemoryChannelBackend(BaseChannelBackend):
""" """
In-memory channel implementation. Intended only for use with threading, In-memory channel implementation. Intended only for use with threading,

View File

@ -1,6 +1,5 @@
import time import time
import json import json
import datetime
import math import math
import redis import redis
import random import random
@ -64,7 +63,11 @@ class RedisChannelBackend(BaseChannelBackend):
def send(self, channel, message): def send(self, channel, message):
# if channel is no str (=> bytes) convert it # if channel is no str (=> bytes) convert it
if not isinstance(channel, str): if not isinstance(channel, str):
channel = channel.decode('utf-8') channel = channel.decode("utf-8")
# Write out message into expiring key (avoids big items in list)
# TODO: Use extended set, drop support for older redis?
key = self.prefix + uuid.uuid4().hex
# Pick a connection to the right server - consistent for response # Pick a connection to the right server - consistent for response
# channels, random for normal channels # channels, random for normal channels
if channel.startswith("!"): if channel.startswith("!"):
@ -72,9 +75,7 @@ class RedisChannelBackend(BaseChannelBackend):
connection = self.connection(index) connection = self.connection(index)
else: else:
connection = self.connection(None) connection = self.connection(None)
# Write out message into expiring key (avoids big items in list)
# TODO: Use extended set, drop support for older redis?
key = self.prefix + uuid.uuid4().hex
connection.set( connection.set(
key, key,
json.dumps(message), json.dumps(message),

View File

@ -18,7 +18,8 @@ def linearize(func):
def inner(message, *args, **kwargs): def inner(message, *args, **kwargs):
# Make sure there's a reply channel # Make sure there's a reply channel
if not message.reply_channel: if not message.reply_channel:
raise ValueError("No reply_channel sent to consumer; @no_overlap can only be used on messages containing it.") raise ValueError("No reply_channel sent to consumer; "
"@no_overlap can only be used on messages containing it.")
# Get the lock, or re-queue # Get the lock, or re-queue
locked = message.channel_backend.lock_channel(message.reply_channel) locked = message.channel_backend.lock_channel(message.reply_channel)
if not locked: if not locked:
@ -43,10 +44,12 @@ def channel_session(func):
def inner(message, *args, **kwargs): def inner(message, *args, **kwargs):
# Make sure there's a reply_channel # Make sure there's a reply_channel
if not message.reply_channel: if not message.reply_channel:
raise ValueError("No reply_channel sent to consumer; @channel_session can only be used on messages containing it.") raise ValueError("No reply_channel sent to consumer; "
"@channel_session can only be used on messages containing it.")
# Make sure there's NOT a channel_session already # Make sure there's NOT a channel_session already
if hasattr(message, "channel_session"): if hasattr(message, "channel_session"):
raise ValueError("channel_session decorator wrapped inside another channel_session decorator") raise ValueError("channel_session decorator wrapped "
"inside another channel_session decorator")
# Turn the reply_channel into a valid session key length thing. # Turn the reply_channel into a valid session key length thing.
# We take the last 24 bytes verbatim, as these are the random section, # We take the last 24 bytes verbatim, as these are the random section,
# and then hash the remaining ones onto the start, and add a prefix # and then hash the remaining ones onto the start, and add a prefix

View File

@ -1,7 +1,6 @@
import threading import threading
from django.core.management.commands.runserver import Command as RunserverCommand from django.core.management.commands.runserver import Command as RunserverCommand
from channels import channel_backends, DEFAULT_CHANNEL_BACKEND from channels import channel_backends, DEFAULT_CHANNEL_BACKEND
from channels.adapters import UrlConsumer from channels.adapters import UrlConsumer
from channels.interfaces.wsgi import WSGIInterface from channels.interfaces.wsgi import WSGIInterface

View File

@ -14,7 +14,8 @@ class Command(BaseCommand):
channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND] channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]
if channel_backend.local_only: if channel_backend.local_only:
raise CommandError( raise CommandError(
"You have a process-local channel backend configured, and so cannot run separate workers.\n" "You have a process-local channel backend configured, "
"and so cannot run separate workers.\n"
"Configure a network-based backend in CHANNEL_BACKENDS to use this command." "Configure a network-based backend in CHANNEL_BACKENDS to use this command."
) )
# Launch a worker # Launch a worker

View File

@ -23,7 +23,7 @@ class Command(BaseCommand):
# Run the interface # Run the interface
port = int(options.get("port", None) or 9000) port = int(options.get("port", None) or 9000)
try: try:
import asyncio import asyncio # NOQA
except ImportError: except ImportError:
from channels.interfaces.websocket_twisted import WebsocketTwistedInterface from channels.interfaces.websocket_twisted import WebsocketTwistedInterface
self.logger.info("Running Twisted/Autobahn WebSocket interface server") self.logger.info("Running Twisted/Autobahn WebSocket interface server")

View File

@ -1,7 +1,6 @@
from django.http import HttpRequest from django.http import HttpRequest
from django.utils.datastructures import MultiValueDict from django.utils.datastructures import MultiValueDict
from django.http.request import QueryDict from django.http.request import QueryDict
from django.conf import settings
def encode_request(request): def encode_request(request):

View File

@ -24,9 +24,9 @@ def decode_response(value):
Decodes a response JSONish value to a HttpResponse object. Decodes a response JSONish value to a HttpResponse object.
""" """
response = HttpResponse( response = HttpResponse(
content = value['content'], content=value['content'],
content_type = value['content_type'], content_type=value['content_type'],
status = value['status'], status=value['status'],
) )
for cookie in value['cookies']: for cookie in value['cookies']:
response.cookies.load(cookie) response.cookies.load(cookie)

View File

@ -5,3 +5,5 @@ DATABASES = {
'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.sqlite3',
} }
} }
MIDDLEWARE_CLASSES = []

View File

@ -1,7 +1,6 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from django.test import TestCase from django.test import TestCase
from ..channel import Channel
from ..backends.database import DatabaseChannelBackend from ..backends.database import DatabaseChannelBackend
from ..backends.redis_py import RedisChannelBackend from ..backends.redis_py import RedisChannelBackend
from ..backends.memory import InMemoryChannelBackend from ..backends.memory import InMemoryChannelBackend

14
tox.ini
View File

@ -1,7 +1,14 @@
[tox] [tox]
skipsdist = True skipsdist = True
envlist = envlist =
{py27,py35}-django-{16,17,18} {py27}-django-{17,18,19}
{py35}-django-{18,19}
{py27,py35}-flake8
[flake8]
exclude = venv/*,tox/*,docs/*
ignore = E123,E128,E402,W503,E731,W601
max-line-length = 119
[testenv] [testenv]
setenv = setenv =
@ -9,8 +16,11 @@ setenv =
deps = deps =
six six
redis==2.10.5 redis==2.10.5
flake8: flake8
django-16: Django>=1.6,<1.7 django-16: Django>=1.6,<1.7
django-17: Django>=1.7,<1.8 django-17: Django>=1.7,<1.8
django-18: Django>=1.8,<1.9 django-18: Django>=1.8,<1.9
django-19: Django==1.9b1
commands = commands =
python {toxinidir}/runtests.py flake8: flake8
django: python {toxinidir}/runtests.py