Fixed up mypy issues or added type:ignore comments as needed for a clean mypy run.

- Legacy-Id: 16772
This commit is contained in:
Henrik Levkowetz 2019-09-30 15:42:18 +00:00
parent c15b3e1ab4
commit 33e8733b91
51 changed files with 169 additions and 82 deletions

View file

@ -3,10 +3,13 @@ import os
import sys
import time as timeutils
import inspect
import six
if six.PY3:
from typing import Callable
try:
import syslog
logger = syslog.syslog
logger = syslog.syslog # type: Callable
except ImportError: # import syslog will fail on Windows boxes
import logging
logging.basicConfig(filename='tracker.log',level=logging.INFO)
@ -15,7 +18,7 @@ except ImportError: # import syslog will fail on Windows box
try:
from pprint import pformat
except ImportError:
pformat = lambda x: x
pformat = lambda x: x # type: ignore
import cProfile
import traceback as tb

View file

@ -6,9 +6,12 @@ from __future__ import absolute_import, print_function, unicode_literals
import os
import patch
import six
import sys
import time
from textwrap import dedent
if six.PY3:
from typing import List, Tuple # pyflakes:ignore
import debug # pyflakes:ignore
debug.debug = True
@ -17,7 +20,7 @@ from django.conf import settings
from django.core import checks
from django.utils.module_loading import import_string
checks_run = []
checks_run = [] # type: List[str]
def already_ran():
import inspect

View file

@ -3,6 +3,10 @@
# Generated by Django 1.11.10 on 2018-02-20 10:52
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List # pyflakes:ignore
from django.db import migrations, models
import django.db.models.deletion
import ietf.utils.models
@ -13,7 +17,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
] # type: List[str]
operations = [
migrations.CreateModel(

View file

@ -5,6 +5,10 @@
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List # pyflakes:ignore
from django.db import migrations, models
@ -13,7 +17,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
] # type: List[str]
operations = [
migrations.CreateModel(

View file

@ -11,7 +11,7 @@ from docutils.utils import SystemMessage
import debug # pyflakes:ignore
from django.template.loaders.base import Loader as BaseLoader
from django.template.base import Template as DjangoTemplate, TemplateEncodingError
from django.template.base import Template as DjangoTemplate, TemplateEncodingError # type: ignore (FIXME: remove when Django 2)
from django.template.exceptions import TemplateDoesNotExist
from django.utils.encoding import smart_text
@ -95,4 +95,4 @@ def load_template_source(template_name, template_dirs=None):
PendingDeprecationWarning
)
return _loader.load_template_source(template_name, template_dirs)
load_template_source.is_usable = True
load_template_source.is_usable = True # type: ignore # https://github.com/python/mypy/issues/2087

View file

@ -8,7 +8,10 @@ from __future__ import absolute_import, print_function, unicode_literals
from django.conf import settings
import datetime, os, shutil, glob, re
import six
from pathlib import Path
if six.PY3:
from typing import List, Tuple # pyflakes:ignore
from ietf.utils import log
from ietf.utils.mail import send_mail
@ -28,7 +31,7 @@ def expirable_draft(draft):
log.assertion('draft.get_state_slug("draft-iesg")')
return bool(expirable_drafts(Document.objects.filter(pk=draft.pk)))
nonexpirable_states = []
nonexpirable_states = [] # type: List[State]
def expirable_drafts(queryset=None):
"""Return a queryset with expirable drafts."""

View file

@ -7,6 +7,9 @@ from __future__ import absolute_import, print_function, unicode_literals
import debug # pyflakes:ignore
import factory
import datetime
import six
if six.PY3:
from typing import Optional # pyflakes:ignore
from django.conf import settings
@ -28,7 +31,7 @@ class BaseDocumentFactory(factory.DjangoModelFactory):
title = factory.Faker('sentence',nb_words=5)
rev = '00'
std_level_id = None
std_level_id = None # type: Optional[str]
intended_std_level_id = None
time = datetime.datetime.now()
expires = factory.LazyAttribute(lambda o: o.time+datetime.timedelta(days=settings.INTERNET_DRAFT_DAYS_TO_EXPIRE))

View file

@ -10,7 +10,8 @@ import six
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
from django.urls import reverse as urlreverse
from django.template.defaultfilters import truncatewords, truncatewords_html, date as datefilter, linebreaks
from django.template.defaultfilters import truncatewords, truncatewords_html, date as datefilter
from django.template.defaultfilters import linebreaks # type: ignore
from django.utils.html import strip_tags
from ietf.doc.models import Document, State, LastCallDocEvent, DocEvent

View file

@ -46,7 +46,7 @@ from django.urls import reverse as urlreverse
from django.db.models import Q
from django.http import Http404, HttpResponseBadRequest, HttpResponse, HttpResponseRedirect, QueryDict
from django.shortcuts import render
from django.utils.cache import _generate_cache_key
from django.utils.cache import _generate_cache_key # type: ignore (FIXME: remove when Django 2)
import debug # pyflakes:ignore

View file

@ -8,6 +8,9 @@ import datetime
import io
import os
import re
import six
if six.PY3:
from typing import Dict # pyflakes:ignore
from django import forms
from django.shortcuts import render, get_object_or_404, redirect
@ -435,7 +438,7 @@ def clean_helper(form, formtype):
return cleaned_data
class EditStatusChangeForm(forms.Form):
relations={}
relations={} # type: Dict[str, str]
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
@ -452,7 +455,7 @@ class StartStatusChangeForm(forms.Form):
create_in_state = forms.ModelChoiceField(State.objects.filter(type="statchg", slug__in=("needshep", "adrev")), empty_label=None, required=False)
notify = forms.CharField(max_length=255, label="Notice emails", help_text="Separate email addresses with commas.", required=False)
telechat_date = forms.TypedChoiceField(coerce=lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').date(), empty_value=None, required=False, widget=forms.Select(attrs={'onchange':'make_bold()'}))
relations={}
relations={} # type: Dict[str, str]
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)

View file

@ -43,8 +43,8 @@ class GroupAdmin(admin.ModelAdmin):
for r in roles:
res.append('<a href="../../person/person/%s/">%s</a> (<a href="../../group/role/%s/">%s)' % (r.person.pk, escape(r.person.plain_name()), r.pk, r.name.name))
return ", ".join(res)
role_list.short_description = "Persons"
role_list.allow_tags = True
role_list.short_description = "Persons" # type: ignore # https://github.com/python/mypy/issues/2087
role_list.allow_tags = True # type: ignore # https://github.com/python/mypy/issues/2087
# SDO reminder

View file

@ -41,6 +41,7 @@ class Migration(migrations.Migration):
('about_page', models.CharField(default='ietf.group.views.group_about', max_length=64)),
('default_tab', models.CharField(default='ietf.group.views.group_about', max_length=64)),
('material_types', models.CharField(default='slides', max_length=64, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of material types', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')])),
# type: ignore (FIXME: remove when Django 2)
('admin_roles', models.CharField(default='chair', max_length=64, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of role slugs', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')])),
('agenda_type', models.ForeignKey(default='ietf', null=True, on_delete=django.db.models.deletion.CASCADE, to='name.AgendaTypeName')),
],

View file

@ -45,6 +45,7 @@ class Migration(migrations.Migration):
model_name='groupfeatures',
name='role_order',
field=models.CharField(default='chair,secr,member', help_text='The order in which roles are shown, for instance on photo pages', max_length=128, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of role slugs', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')]),
# type: ignore (FIXME: remove when Django 2)
),
migrations.AddField(
model_name='groupfeatures',
@ -60,6 +61,7 @@ class Migration(migrations.Migration):
model_name='groupfeatures',
name='matman_roles',
field=models.CharField(default='ad,chair,delegate,secr', max_length=64, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of role slugs', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')]),
# type: ignore (FIXME: remove when Django 2)
),
migrations.AddField(
model_name='historicalgroupfeatures',
@ -90,6 +92,7 @@ class Migration(migrations.Migration):
model_name='historicalgroupfeatures',
name='role_order',
field=models.CharField(default='chair,secr,member', help_text='The order in which roles are shown, for instance on photo pages', max_length=128, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of role slugs', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')]),
# type: ignore (FIXME: remove when Django 2)
),
migrations.AddField(
model_name='historicalgroupfeatures',
@ -105,5 +108,6 @@ class Migration(migrations.Migration):
model_name='historicalgroupfeatures',
name='matman_roles',
field=models.CharField(default='ad,chair,delegate,secr', max_length=64, validators=[django.core.validators.RegexValidator(code=b'invalid', message=b'Enter a comma-separated list of role slugs', regex=b'[a-z0-9_-]+(,[a-z0-9_-]+)*')]),
# type: ignore (FIXME: remove when Django 2)
),
]

View file

@ -26,7 +26,7 @@ def forward(apps, schema_editor):
# This migration changes existing data fields in an incompatible manner, and
# would not be interleavable if we hadn't added compatibility code in
# Group.features() beforehand. With that patched in, we permit interleaving.
forward.interleavable = True
forward.interleavable = True # type: ignore # https://github.com/python/mypy/issues/2087
def reverse(apps, schema_editor):
GroupFeatures = apps.get_model('group', 'GroupFeatures')

View file

@ -231,7 +231,7 @@ def forward(apps, schema_editor):
gf.save()
# This migration does not remove or change any previous fields, and executes
# swirftly, so we permit it to be interleaved with schema migrations
forward.interleavable = True
forward.interleavable = True # type: ignore # https://github.com/python/mypy/issues/2087
def reverse(apps, schema_editor):
pass

View file

@ -143,7 +143,7 @@ def forward(apps, schema_editor):
# This migration does not remove or change any previous fields, and executes
# swirftly, so we permit it to be interleaved with schema migrations
forward.interleavable = True
forward.interleavable = True # type: ignore # https://github.com/python/mypy/issues/2087
def reverse(apps, schema_editor):
pass

View file

@ -11,7 +11,7 @@ from tastypie.cache import SimpleCache
from ietf import api
from ietf.group.models import (Group, GroupStateTransitions, GroupMilestone, GroupHistory,
from ietf.group.models import (Group, GroupStateTransitions, GroupMilestone, GroupHistory, # type: ignore
GroupURL, Role, GroupEvent, RoleHistory, GroupMilestoneHistory, MilestoneGroupEvent,
ChangeStateGroupEvent, GroupFeatures, HistoricalGroupFeatures)

View file

@ -1,6 +1,7 @@
# Copyright The IETF Trust 2007-2019, All Rights Reserved
# Copyright The IETF Trust 2007, 2009, All Rights Reserved
from django.contrib.auth.views import logout
from django.contrib.auth.views import logout # type: ignore (FIXME: remove when Django 2)
from ietf.ietfauth import views
from ietf.utils.urls import url

View file

@ -1,4 +1,4 @@
# Copyright The IETF Trust 2007, All Rights Reserved
# Copyright The IETF Trust 2007-2019, All Rights Reserved
#
from django.contrib.sitemaps import GenericSitemap
from ietf.ipr.models import IprDisclosureBase
@ -8,4 +8,4 @@ from ietf.ipr.models import IprDisclosureBase
queryset = IprDisclosureBase.objects.filter(state__in=('posted','removed'))
archive = {'queryset':queryset, 'date_field': 'time', 'allow_empty':True }
IPRMap = GenericSitemap(archive)
IPRMap = GenericSitemap(archive) # type: ignore (FIXME: remove when Django 2)

View file

@ -32,7 +32,7 @@ class LiaisonStatementAdmin(admin.ModelAdmin):
def related_to(self, obj):
return '<br />'.join(['<a href="%s">%s</a>' % (reverse('admin:liaisons_liaisonstatement_change', None, (i.target.id, )), str(i.target)) for i in obj.source_of_set.select_related('target').all()])
related_to.allow_tags = True
related_to.allow_tags = True # type: ignore # https://github.com/python/mypy/issues/2087
class LiaisonStatementAttachmentAdmin(admin.ModelAdmin):
list_display = ['id', 'statement', 'document', 'removed']

View file

@ -8,6 +8,8 @@ import io
import datetime, os
import operator
import six
if six.PY3:
from typing import Union # pyflakes:ignore
from email.utils import parseaddr
from form_utils.forms import BetterModelForm
@ -216,7 +218,7 @@ class LiaisonModelForm(BetterModelForm):
a problem with validating
'''
from_groups = forms.ModelMultipleChoiceField(queryset=Group.objects.all(),label='Groups',required=False)
from_contact = forms.EmailField()
from_contact = forms.EmailField() # type: Union[forms.EmailField, SearchableEmailField]
to_contacts = forms.CharField(label="Contacts", widget=forms.Textarea(attrs={'rows':'3', }), strip=False)
to_groups = forms.ModelMultipleChoiceField(queryset=Group.objects,label='Groups',required=False)
deadline = DatepickerDateField(date_format="yyyy-mm-dd", picker_settings={"autoclose": "1" }, label='Deadline', required=True)

View file

@ -181,7 +181,7 @@ class LiaisonStatement(models.Model):
interface'''
groups = self.to_groups.order_by('acronym').values_list('acronym',flat=True)
return ', '.join(groups)
from_groups_short_display.short_description = 'From Groups'
from_groups_short_display.short_description = 'From Groups' # type: ignore # https://github.com/python/mypy/issues/2087
def set_state(self,slug):
try:

View file

@ -1,3 +1,4 @@
# Copyright The IETF Trust 2015-2019, All Rights Reserved
from django.contrib import admin
from ietf.mailtrigger.models import MailTrigger, Recipient
@ -6,7 +7,7 @@ class RecipientAdmin(admin.ModelAdmin):
list_display = [ 'slug', 'desc', 'template', 'has_code', ]
def has_code(self, obj):
return hasattr(obj,'gather_%s'%obj.slug)
has_code.boolean = True
has_code.boolean = True # type: ignore # https://github.com/python/mypy/issues/2087
admin.site.register(Recipient, RecipientAdmin)

View file

@ -1,9 +1,17 @@
# Copyright The IETF Trust 2015-2019, All Rights Reserved
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import Dict, List # pyflakes:ignore
from django import forms
from ietf.mailtrigger.models import MailTrigger
class CcSelectForm(forms.Form):
expansions = dict()
expansions = dict() # type: Dict[str, List[str]]
cc_choices = forms.MultipleChoiceField(
label='Cc',
choices=[],

View file

@ -5,6 +5,10 @@
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List # pyflakes:ignore
from django.db import migrations, models
@ -13,7 +17,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
] # type: List[str]
operations = [
migrations.CreateModel(

View file

@ -62,7 +62,7 @@ class TimeSlotAdmin(admin.ModelAdmin):
return "%s (%s)" % (instance.session.group.name, instance.session.group.acronym)
return ""
session_desc.short_description = "session"
session_desc.short_description = "session" # type: ignore # https://github.com/python/mypy/issues/2087
admin.site.register(TimeSlot, TimeSlotAdmin)
@ -76,7 +76,7 @@ class ConstraintAdmin(admin.ModelAdmin):
def name_lower(self, instance):
return instance.name.name.lower()
name_lower.short_description = "constraint name"
name_lower.short_description = "constraint name" # type: ignore # https://github.com/python/mypy/issues/2087
admin.site.register(Constraint, ConstraintAdmin)
@ -90,7 +90,7 @@ class SessionAdmin(admin.ModelAdmin):
def name_lower(self, instance):
return instance.name.name.lower()
name_lower.short_description = "constraint name"
name_lower.short_description = "constraint name" # type: ignore # https://github.com/python/mypy/issues/2087
admin.site.register(Session, SessionAdmin)
@ -116,7 +116,7 @@ admin.site.register(SchedTimeSessAssignment, SchedTimeSessAssignmentAdmin)
class ResourceAssociationAdmin(admin.ModelAdmin):
def used(self, instance):
return instance.name.used
used.boolean = True
used.boolean = True # type: ignore # https://github.com/python/mypy/issues/2087
list_display = ["name", "icon", "used", "desc"]
admin.site.register(ResourceAssociation, ResourceAssociationAdmin)

View file

@ -7,6 +7,9 @@
import io
import os, sys
import django
import six
if six.PY3:
from typing import Any, List # pyflakes:ignore
basedir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..'))
sys.path.insert(0, basedir)
@ -29,7 +32,7 @@ def output(name, seq):
raise
# pick all name models directly out of the module
objects = []
objects = [] # type: List[object]
import inspect
import ietf.name.models

View file

@ -5,6 +5,10 @@
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List # pyflakes:ignore
from django.db import migrations, models
import django.db.models.deletion
import ietf.utils.models
@ -15,7 +19,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
] # type: List[str]
operations = [
migrations.CreateModel(

View file

@ -50,7 +50,7 @@ admin.site.register(Position, PositionAdmin)
class FeedbackAdmin(admin.ModelAdmin):
def nominee(self, obj):
return ", ".join(n.person.ascii for n in obj.nominees.all())
nominee.admin_order_field = 'nominees__person__ascii'
nominee.admin_order_field = 'nominees__person__ascii' # type: ignore # https://github.com/python/mypy/issues/2087
list_display = ['id', 'nomcom', 'author', 'nominee', 'subject', 'type', 'user', 'time']
list_filter = ['nomcom', 'type', 'time', ]

View file

@ -5,6 +5,8 @@
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List, Tuple # pyflakes:ignore
from django.conf import settings
from django import forms
@ -592,7 +594,7 @@ class QuestionnaireForm(forms.ModelForm):
class Meta:
model = Feedback
fields = []
fields = [] # type: List[str]
class NomComTemplateForm(DBTemplateForm):
content = forms.CharField(label="Text", widget=forms.Textarea(attrs={'cols': '120', 'rows':'40', }), strip=False)

View file

@ -1,17 +1,18 @@
# Copyright The IETF Trust 2013-2019, All Rights Reserved
from django.db import models
from django.db.models.query import QuerySet
import debug # pyflakes:ignore
class MixinManager(object):
def __getattr__(self, attr, *args):
def __getattr__(self, attr):
if attr.startswith('__'):
return getattr(self.__class__, attr, *args)
return getattr(self.__class__, attr)
else:
try:
return getattr(self.__class__, attr, *args)
return getattr(self.__class__, attr)
except AttributeError:
return getattr(self.get_queryset(), attr, *args)
return getattr(self.get_queryset(), attr)
class NomineePositionQuerySet(QuerySet):

View file

@ -9,7 +9,7 @@ from django.db.models.signals import post_delete
from django.conf import settings
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.template.defaultfilters import linebreaks
from django.template.defaultfilters import linebreaks # type: ignore
from django.utils.encoding import python_2_unicode_compatible
import debug # pyflakes:ignore

View file

@ -10,7 +10,7 @@ from tastypie.cache import SimpleCache
from ietf import api
from ietf.person.models import (Person, Email, Alias, PersonalApiKey, PersonEvent, PersonApiKeyEvent, HistoricalPerson, HistoricalEmail)
from ietf.person.models import (Person, Email, Alias, PersonalApiKey, PersonEvent, PersonApiKeyEvent, HistoricalPerson, HistoricalEmail) # type: ignore
from ietf.utils.resources import UserResource

View file

@ -11,7 +11,7 @@ from tastypie.cache import SimpleCache
from ietf import api
from ietf.api import ToOneField # pyflakes:ignore
from ietf.review.models import (ReviewerSettings, ReviewRequest, ReviewAssignment,
from ietf.review.models import (ReviewerSettings, ReviewRequest, ReviewAssignment, # type: ignore
UnavailablePeriod, ReviewWish, NextReviewerInTeam,
ReviewSecretarySettings, ReviewTeamSettings,
HistoricalReviewerSettings )

View file

@ -126,8 +126,8 @@ def do_resurrect(draft, request):
try:
shutil.move(file, settings.INTERNET_DRAFT_PATH)
log(" Moved file %s to %s" % (file, settings.INTERNET_DRAFT_PATH))
except shutil.Error as e:
log(" Exception %s when attempting to move %s" % (e, file))
except shutil.Error as ex:
log(" Exception %s when attempting to move %s" % (ex, file))
# Update draft record
draft.set_state(State.objects.get(type="draft", slug="active"))

View file

@ -1,7 +1,9 @@
# Copyright The IETF Trust 2014-2019, All Rights Reserved
#import logging
from django.db import connection
from django.utils.log import getLogger
from django.utils.log import getLogger # type: ignore (FIXME: remove when Django 2)
logger = getLogger(__name__)
#logger.setLevel(logging.DEBUG)

View file

@ -20,7 +20,7 @@ from ietf.person.fields import SearchablePersonsField
NUM_SESSION_CHOICES = (('','--Please select'),('1','1'),('2','2'))
# LENGTH_SESSION_CHOICES = (('','--Please select'),('1800','30 minutes'),('3600','1 hour'),('5400','1.5 hours'), ('7200','2 hours'),('9000','2.5 hours'))
LENGTH_SESSION_CHOICES = (('','--Please select'),('1800','30 minutes'),('3600','1 hour'),('5400','1.5 hours'), ('7200','2 hours'))
WG_CHOICES = list( Group.objects.filter(type__in=('wg','rg','ag'),state__in=('bof','proposed','active')).values_list('acronym','acronym').order_by('acronym'))
WG_CHOICES = list( Group.objects.filter(type__in=('wg','rg','ag'),state__in=('bof','proposed','active')).values_list('acronym','acronym').order_by('acronym')) # type: ignore
WG_CHOICES.insert(0,('','--Select WG(s)'))
# -------------------------------------------------

View file

@ -9,9 +9,12 @@ from __future__ import absolute_import, print_function, unicode_literals
# http://code.djangoproject.com/wiki/SplitSettings
import os
import six
import sys
import datetime
import warnings
if six.PY3:
from typing import Any, Dict, List, Tuple # pyflakes:ignore
warnings.simplefilter("always", DeprecationWarning)
warnings.filterwarnings("ignore", message="Report.file_reporters will no longer be available in Coverage.py 4.2", module="coverage.report")
@ -19,7 +22,7 @@ warnings.filterwarnings("ignore", message="The popen2 module is deprecated. Use
warnings.filterwarnings("ignore", message="Usage of field.rel has been deprecated. Use field.remote_field instead.", module="tastypie.resources")
warnings.filterwarnings("ignore", message="Importing from django.core.urlresolvers is deprecated in favor of django.urls.", module="tastypie.resources")
warnings.filterwarnings("ignore", message="on_delete will be a required arg for OneToOneField in Django 2.0.", module="tastypie")
warnings.filterwarnings("ignore", message="The load_template\(\) method is deprecated. Use get_template\(\) instead.")
warnings.filterwarnings("ignore", message=r"The load_template\(\) method is deprecated. Use get_template\(\) instead.")
warnings.filterwarnings("ignore", message="escape isn't the last filter in")
warnings.filterwarnings("ignore", message="Deprecated allow_tags attribute used on field")
warnings.filterwarnings("ignore", message="You passed a bytestring as `filenames`. This will not work on Python 3.")
@ -57,13 +60,13 @@ SERVER_MODE = 'development'
# Domain name of the IETF
IETF_DOMAIN = 'ietf.org'
ADMINS = (
ADMINS = [
('Henrik Levkowetz', 'henrik@levkowetz.com'),
('Robert Sparks', 'rjsparks@nostrum.com'),
# ('Ole Laursen', 'olau@iola.dk'),
('Ryan Cross', 'rcross@amsl.com'),
('Glen Barney', 'glen@amsl.com'),
)
] # type: List[Tuple[str, str]]
BUG_REPORT_EMAIL = "datatracker-project@ietf.org"
@ -320,7 +323,7 @@ SESSION_SAVE_EVERY_REQUEST = True
PREFERENCES_COOKIE_AGE = 60 * 60 * 24 * 365 * 50 # Age of cookie, in seconds: 50 years
TEMPLATES = [
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
@ -351,13 +354,13 @@ TEMPLATES = [
]
},
},
]
] # type: List[Dict[str,Any]]
if DEBUG:
TEMPLATES[0]['OPTIONS']['string_if_invalid'] = "** No value found for '%s' **"
MIDDLEWARE = (
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware', # see docs on CORS_REPLACE_HTTPS_REFERER before using it
'django.middleware.common.CommonMiddleware',
@ -376,7 +379,7 @@ MIDDLEWARE = (
'django.middleware.security.SecurityMiddleware',
'csp.middleware.CSPMiddleware',
'ietf.middleware.unicode_nfkc_normalization_middleware',
)
]
ROOT_URLCONF = 'ietf.urls'
@ -387,7 +390,7 @@ STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'externals/static'),
)
INSTALLED_APPS = (
INSTALLED_APPS = [
# Django apps
'django.contrib.admin',
'django.contrib.admindocs',
@ -445,7 +448,7 @@ INSTALLED_APPS = (
'ietf.secr.rolodex',
'ietf.secr.sreq',
'ietf.secr.telechat',
)
]
# Settings for django-bootstrap3
# See http://django-bootstrap3.readthedocs.org/en/latest/settings.html
@ -552,7 +555,7 @@ TEST_CODE_COVERAGE_EXCLUDE_FILES = [
TEST_CODE_COVERAGE_EXCLUDE_LINES = [
"coverage: *ignore",
"debug",
"unreachable\([^)]*\)",
r"unreachable\([^)]*\)",
"if settings.DEBUG",
"if settings.TEST_CODE_COVERAGE_CHECKER",
"if __name__ == .__main__.:",
@ -763,7 +766,7 @@ IDSUBMIT_STAGING_URL = '//www.ietf.org/staging/'
IDSUBMIT_IDNITS_BINARY = '/a/www/ietf-datatracker/scripts/idnits'
SUBMIT_PYANG_COMMAND = 'pyang --verbose --ietf -p {libs} {model}'
SUBMIT_YANGLINT_COMMAND = 'yanglint --verbose -p {tmplib} -p {rfclib} -p {draftlib} -p {ianalib} {model} -i'
SUBMIT_YANGLINT_COMMAND = None # use the value above if you have yanglint installed
SUBMIT_YANGLINT_COMMAND = '' # use the value above if you have yanglint installed
SUBMIT_YANG_CATALOG_MODULEARG = "modules[]={module}"
SUBMIT_YANG_CATALOG_IMPACT_URL = "https://www.yangcatalog.org/yang-search/impact_analysis.php?{moduleargs}&recurse=0&rfcs=1&show_subm=1&show_dir=both"
@ -912,7 +915,7 @@ SKIP_SELENIUM = True
# Set debug apps in settings_local.DEV_APPS
DEV_APPS = ()
DEV_APPS = [] # type: List[str]
DEV_MIDDLEWARE = ()
# django-debug-toolbar and the debug listing of sql queries at the bottom of
@ -1124,6 +1127,6 @@ if SERVER_MODE != 'production':
try:
# see https://github.com/omarish/django-cprofile-middleware
import django_cprofile_middleware # pyflakes:ignore
MIDDLEWARE = MIDDLEWARE + ('django_cprofile_middleware.middleware.ProfilerMiddleware', )
MIDDLEWARE = MIDDLEWARE + ['django_cprofile_middleware.middleware.ProfilerMiddleware', ]
except ImportError:
pass

View file

@ -13,6 +13,7 @@ from __future__ import absolute_import, print_function, unicode_literals
import os
from ietf.settings import * # pyflakes:ignore
from ietf.settings import TEST_CODE_COVERAGE_CHECKER, BASE_DIR, PHOTOS_DIRNAME
import debug # pyflakes:ignore
debug.debug = True

View file

@ -39,7 +39,7 @@ CACHES = {
},
}
PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', )
PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
SERVER_MODE = 'test'
ALLOWED_HOSTS = ["127.0.0.1", "localhost:8000", "testserver", ]

View file

@ -11,6 +11,8 @@ import os.path
import argparse
import six
import time
if six.PY3:
from typing import Set, Optional # pyflakes:ignore
basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
sys.path = [ basedir ] + sys.path
@ -129,12 +131,12 @@ for doc in docs_qs.prefetch_related("docalias", "formal_languages", "documentaut
# the draft parser sometimes has a problem when
# affiliation isn't in the second line and it then thinks
# it's an extra author - skip those extra authors
seen = set()
seen = set() # type: Set[Optional[str]]
for full, _, _, _, _, email, country, company in d.get_author_list():
assert full is None or isinstance(full, six.text_type)
assert email is None or isinstance(email, six.text_type)
assert country is None or isinstance(country, six.text_type)
assert company is None or isinstance(company, six.text_type)
assert isinstance(company, six.text_type)
#full, email, country, company = [ unicode(s) for s in [full, email, country, company, ] ]
if email in seen:
continue

View file

@ -1,3 +1,4 @@
# Copyright The IETF Trust 2011-2019, All Rights Reserved
from django.urls import reverse as urlreverse
from django.contrib import admin
@ -16,14 +17,14 @@ class SubmissionAdmin(admin.ModelAdmin):
kwargs=dict(submission_id=instance.pk,
access_token=instance.access_token()))
return '<a href="%s">%s</a>' % (url, instance.state)
status_link.allow_tags = True
status_link.allow_tags = True # type: ignore # https://github.com/python/mypy/issues/2087
def draft_link(self, instance):
if instance.state_id == "posted":
return '<a href="https://www.ietf.org/id/%s-%s.txt">%s</a>' % (instance.name, instance.rev, instance.name)
else:
return instance.name
draft_link.allow_tags = True
draft_link.allow_tags = True # type: ignore # https://github.com/python/mypy/issues/2087
admin.site.register(Submission, SubmissionAdmin)
class SubmissionEventAdmin(admin.ModelAdmin):

View file

@ -8,6 +8,9 @@ import re
import magic
import datetime
import debug # pyflakes:ignore
import six
if six.PY3:
from typing import List, Optional # pyflakes:ignore
from django.conf import settings
from django.template.defaultfilters import filesizeformat
@ -45,8 +48,8 @@ class ParseInfo(object):
class FileParser(object):
ext = None
mimetypes = []
ext = None # type: Optional[str]
mimetypes = [] # type: List[str]
def __init__(self, fd):
self.fd = fd

View file

@ -11,11 +11,11 @@ import re
import six # pyflakes:ignore
import xml2rfc
if six.PY3:
from typing import Callable, Optional
from typing import Callable, Optional # pyflakes:ignore
from django.conf import settings
from django.core.validators import validate_email, ValidationError
from django.http import HttpRequest
from django.http import HttpRequest # pyflakes:ignore
from django.utils.module_loading import import_string
import debug # pyflakes:ignore
@ -164,7 +164,8 @@ def create_submission_event(request, submission, desc):
SubmissionEvent.objects.create(submission=submission, by=by, desc=desc)
def docevent_from_submission(request, submission, desc, who=None): # type: (HttpRequest, Submission, str, Optional[Person]) -> Optional[DocEvent]
def docevent_from_submission(request, submission, desc, who=None):
# type: (HttpRequest, Submission, str, Optional[Person]) -> Optional[DocEvent]
log.assertion('who is None or isinstance(who, Person)')
try:

View file

@ -7,6 +7,9 @@ from __future__ import absolute_import, print_function, unicode_literals
import re
import base64
import datetime
import six
if six.PY3:
from typing import Optional # pyflakes:ignore
from django.conf import settings
from django.contrib import messages
@ -14,6 +17,7 @@ from django.contrib.auth.models import User
from django.urls import reverse as urlreverse
from django.core.validators import ValidationError
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden, HttpResponse
from django.http import HttpRequest # pyflakes:ignore
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import csrf_exempt
@ -145,6 +149,7 @@ def api_submit(request):
create_submission_event(request, submission, msg)
docevent_from_submission(request, submission, docDesc, who=Person.objects.get(name="(System)"))
return HttpResponse(
"Upload of %s OK, confirmation requests sent to:\n %s" % (submission.name, ',\n '.join(sent_to)),
content_type="text/plain")
@ -198,6 +203,7 @@ def can_edit_submission(user, submission, access_token):
return key_matched or has_role(user, "Secretariat")
def submission_status(request, submission_id, access_token=None):
# type: (HttpRequest, str, Optional[str]) -> HttpResponse
submission = get_object_or_404(Submission, pk=submission_id)
key_matched = access_token and submission.access_token() == access_token
@ -285,11 +291,11 @@ def submission_status(request, submission_id, access_token=None):
prev_authors = [] if not doc else [ author.person for author in doc.documentauthor_set.all() ]
curr_authors = [ get_person_from_name_email(author["name"], author.get("email")) for author in submission.authors ]
if request.user.is_authenticated and request.user.person in (prev_authors if submission.rev != '00' else curr_authors):
if request.user.is_authenticated and request.user.person in (prev_authors if submission.rev != '00' else curr_authors): # type: ignore (FIXME: revisit: "User" has no attribute "person" )
# go directly to posting submission
docevent_from_submission(request, submission, desc="Uploaded new revision", who=request.user.person)
docevent_from_submission(request, submission, desc="Uploaded new revision", who=request.user.person) # type: ignore (FIXME: revisit: "User" has no attribute "person" )
desc = "New version accepted (logged-in submitter: %s)" % request.user.person
desc = "New version accepted (logged-in submitter: %s)" % request.user.person # type: ignore (FIXME: revisit: "User" has no attribute "person")
post_submission(request, submission, desc)
create_submission_event(request, submission, desc)
else:

View file

@ -49,7 +49,8 @@ import six
import stat
import sys
import time
if six.PY3:
from typing import Dict, List # pyflakes:ignore
version = "0.35"
program = os.path.basename(sys.argv[0])
@ -502,7 +503,7 @@ class Draft():
return self._authors_with_firm
def get_author_list(self):
def get_author_list(self): # () -> List[List[str, str, str, str, str, str, str]]
"""Returns a list of tuples, with each tuple containing (given_names,
surname, email, company). Email will be None if unknown.
"""
@ -1310,7 +1311,7 @@ def _printmeta(fn, outfile=sys.stdout):
# Main
# ----------------------------------------------------------------------
company_domain = {}
company_domain = {} # type: Dict[str, str]
def _main(outfile=sys.stdout):
global opt_debug, opt_timestamp, opt_trace, opt_authorinfo, opt_getauthors, files, company_domain, opt_attributes
# set default values, if any

View file

@ -10,10 +10,12 @@ import inspect
import os.path
import six
import traceback
if six.PY3:
from typing import Callable # pyflakes:ignore
try:
import syslog
logfunc = syslog.syslog
logfunc = syslog.syslog # type: Callable
except ImportError: # import syslog will fail on Windows boxes
logging.basicConfig(filename='tracker.log',level=logging.INFO)
logfunc = logging.info

View file

@ -38,6 +38,9 @@ import ietf
from ietf.utils.log import log, assertion
from ietf.utils.text import isascii
if six.PY3:
from typing import Any, Dict, List # pyflakes:ignore
# Testing mode:
# import ietf.utils.mail
# ietf.utils.mail.test_mode = True
@ -45,7 +48,7 @@ from ietf.utils.text import isascii
# ... inspect ietf.utils.mail.outbox ...
# ... call ietf.utils.mail.empty_outbox() ...
test_mode = False
outbox = []
outbox = [] # type: List[Message]
SMTP_ADDR = { 'ip4':settings.EMAIL_HOST, 'port':settings.EMAIL_PORT}

View file

@ -67,7 +67,7 @@ def check(codeString, filename, verbosity=1):
lines = codeString.split('\n')
# honour pyflakes:ignore comments
messages = [message for message in w.messages
if lines[message.lineno-1].find('pyflakes:ignore') < 0]
if (lines[message.lineno-1].find('pyflakes:ignore') < 0 and lines[message.lineno-1].find('pyflakes: ignore')) ]
# honour pyflakes:
messages.sort(key=lambda x: x.lineno)

View file

@ -5,6 +5,10 @@
from __future__ import absolute_import, print_function, unicode_literals
import six
if six.PY3:
from typing import List, Tuple # pyflakes:ignore
from django.db import migrations, models
@ -13,7 +17,7 @@ class Migration(migrations.Migration):
initial = True
dependencies = [
]
] # type: List[str]
operations = [
migrations.CreateModel(

View file

@ -9,6 +9,8 @@ import os.path
import shutil
import six
import types
if six.PY3:
from typing import Dict, List # pyflakes:ignore
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
@ -25,6 +27,7 @@ from django.contrib.auth.models import User
from django.conf import settings
from django.core.management import call_command
from django.template import Context
from django.template import Template # pyflakes:ignore
from django.template.defaulttags import URLNode
from django.template.loader import get_template
from django.templatetags.static import StaticNode
@ -174,8 +177,8 @@ def get_callbacks(urllist):
class TemplateChecksTestCase(TestCase):
paths = []
templates = {}
paths = [] # type: List[str]
templates = {} # type: Dict[str, Template]
def setUp(self):
set_coverage_checking(False)