Skip to content

Commit a534ba0

Browse files
committed
Prefer dict literals over function calls
Though it adds single quotes, it is the style recommended by pylint now because it looks cleaner and a function call makes the code a bit slower.
1 parent 960f9df commit a534ba0

31 files changed

+230
-249
lines changed

docs/conf.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@
6464
# (references to some Python built-in types do not resolve correctly)
6565
nitpicky = True
6666
nitpick_ignore = [('py:class', t) for t in (
67-
'cgi.FieldStorage', 'html.parser.HTMLParser',
68-
'threading.Thread', 'xmlrpc.client.ProtocolError')]
67+
'html.parser.HTMLParser', 'threading.Thread', 'xmlrpc.client.ProtocolError')]
6968

7069
# -- Options for HTML output -------------------------------------------------
7170

docs/deploy.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ In order to make use of Bjoern, you need to add the following at the end of the
486486

487487
Since Bjoern does not support the WSGI ``write()`` callable, you must configure Webware to not use this mechanism, by using the following settings at the top of the ``Scripts\WSGIScript.py``::
488488

489-
settings = dict(WSGIWrite=False)
489+
settings = {'WSGIWrite': False}
490490

491491
A systemd unit file at ``/etc/systemd/system/bjoern.service`` could look like this::
492492

@@ -531,7 +531,7 @@ Add the following at the end of the ``Scripts\WSGIScript.py`` file in the applic
531531

532532
Similarly to Bjoern, you need to also adapt the settings at the top of the ``Scripts\WSGIScript.py`` file::
533533

534-
settings = dict(WSGIWrite=False)
534+
settings = {'WSGIWrite': False}
535535

536536
Using CherryPy as WSGI server
537537
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

tox.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ commands =
99

1010
[testenv:pylint]
1111
basepython = python3.10
12-
deps = pylint>=2.15,<3
12+
deps = pylint>=2.16,<3
1313
commands =
1414
pylint webware
1515

webware/Admin/ServletCache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def htCache(factory):
7070
paths = []
7171
for key in keys:
7272
head, tail = os.path.split(key)
73-
path = dict(dir=head, base=tail, full=key, id=id(key))
73+
path = {'dir': head, 'base': tail, 'full': key, 'id': id(key)}
7474
paths.append(path)
7575
paths.sort(key=lambda p: (p['base'].lower(), p['dir'].lower()))
7676
for path in paths:

webware/Application.py

Lines changed: 87 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -39,108 +39,104 @@
3939

4040
debug = False
4141

42-
defaultConfig = dict(
43-
ActivityLogFilename='Activity.csv',
44-
ActivityLogColumns=[
42+
defaultConfig = {
43+
'ActivityLogFilename': 'Activity.csv',
44+
'ActivityLogColumns': [
4545
'request.remoteAddress', 'request.method',
4646
'request.uri', 'response.size',
4747
'servlet.name', 'request.timeStamp',
48-
'transaction.duration',
49-
'transaction.errorOccurred'
48+
'transaction.duration', 'transaction.errorOccurred'
5049
],
51-
AlwaysSaveSessions=True,
52-
AppLogFilename='Application.log',
53-
CacheDir='Cache',
54-
CacheServletClasses=True,
55-
CacheServletInstances=True,
56-
CheckInterval=None,
57-
Contexts={
50+
'AlwaysSaveSessions': True,
51+
'AppLogFilename': 'Application.log',
52+
'CacheDir': 'Cache',
53+
'CacheServletClasses': True,
54+
'CacheServletInstances': True,
55+
'CheckInterval': None,
56+
'Contexts': {
5857
'default': 'Examples',
5958
'Admin': 'Admin',
6059
'Examples': 'Examples',
6160
'Testing': 'Testing',
6261
},
63-
Debug=dict(
64-
Sessions=False,
65-
),
66-
DirectoryFile=['index', 'Index', 'main', 'Main'],
67-
EnterDebuggerOnException=False,
68-
EmailErrors=False,
69-
EmailErrorReportAsAttachment=False,
70-
ErrorEmailServer='localhost',
71-
ErrorEmailHeaders={
62+
'Debug': {'Sessions': False},
63+
'DirectoryFile': ['index', 'Index', 'main', 'Main'],
64+
'EnterDebuggerOnException': False,
65+
'EmailErrors': False,
66+
'EmailErrorReportAsAttachment': False,
67+
'ErrorEmailServer': 'localhost',
68+
'ErrorEmailHeaders': {
7269
'From': 'webware@mydomain',
7370
'To': ['webware@mydomain'],
7471
'Reply-To': 'webware@mydomain',
7572
'Content-Type': 'text/html',
7673
'Subject': 'Error'
7774
},
78-
ErrorLogFilename='Errors.csv',
79-
ErrorMessagesDir='ErrorMsgs',
80-
ErrorPage=None,
81-
ExtensionCascadeOrder=['.py', '.psp', '.html'],
82-
ExtensionsToIgnore={
75+
'ErrorLogFilename': 'Errors.csv',
76+
'ErrorMessagesDir': 'ErrorMsgs',
77+
'ErrorPage': None,
78+
'ExtensionCascadeOrder': ['.py', '.psp', '.html'],
79+
'ExtensionsToIgnore': {
8380
'.pyc', '.pyo', '.tmpl', '.bak', '.py_bak',
8481
'.py~', '.psp~', '.html~', '.tmpl~'
8582
},
86-
ExtensionsToServe=[],
87-
ExtraPathInfo=True,
88-
FancyTracebackContext=5,
89-
FilesToHide={
83+
'ExtensionsToServe': [],
84+
'ExtraPathInfo': True,
85+
'FancyTracebackContext': 5, 'FilesToHide': {
9086
'.*', '*~', '*.bak', '*.py_bak', '*.tmpl',
9187
'*.pyc', '*.pyo', '__init__.*', '*.config'
9288
},
93-
FilesToServe=[],
94-
IgnoreInvalidSession=True,
95-
IncludeEditLink=True,
96-
IncludeFancyTraceback=False,
97-
LogActivity=True,
98-
LogDir='Logs',
99-
LogErrors=True,
100-
MaxValueLengthInExceptionReport=500,
101-
OutputEncoding='utf-8',
102-
PlugIns=['MiscUtils', 'WebUtils', 'TaskKit', 'UserKit', 'PSP'],
103-
PrintConfigAtStartUp=True,
104-
PrintPlugIns=True,
105-
RegisterSignalHandler=False,
106-
ReloadServletClasses=False,
107-
ReportRPCExceptionsInWebware=True,
108-
ResponseBufferSize=8 * 1024, # 8 kBytes
109-
RetainSessions=True,
110-
RPCExceptionReturn='traceback',
111-
RunTasks=True,
112-
SaveErrorMessages=True,
113-
SecureSessionCookie=True,
114-
SessionCookiePath=None,
115-
HttpOnlySessionCookie=True,
116-
SameSiteSessionCookie='Strict',
117-
SessionModule='Session',
118-
SessionName='_SID_',
119-
SessionPrefix='',
120-
SessionStore='Dynamic',
121-
SessionStoreDir='Sessions',
122-
SessionTimeout=60,
123-
ShowDebugInfoOnErrors=False,
124-
SilentURIs=None,
125-
UnknownFileTypes=dict(
126-
ReuseServlets=True,
127-
Technique='serveContent', # or redirectSansScript
128-
CacheContent=False,
129-
MaxCacheContentSize=128 * 1024,
130-
ReadBufferSize=32 * 1024
131-
),
132-
UseAutomaticPathSessions=False,
133-
UseCascadingExtensions=True,
134-
UseCookieSessions=True,
135-
UserErrorMessage=(
89+
'FilesToServe': [],
90+
'IgnoreInvalidSession': True,
91+
'IncludeEditLink': True,
92+
'IncludeFancyTraceback': False,
93+
'LogActivity': True,
94+
'LogDir': 'Logs',
95+
'LogErrors': True,
96+
'MaxValueLengthInExceptionReport': 500,
97+
'OutputEncoding': 'utf-8',
98+
'PlugIns': ['MiscUtils', 'WebUtils', 'TaskKit', 'UserKit', 'PSP'],
99+
'PrintConfigAtStartUp': True,
100+
'PrintPlugIns': True,
101+
'RegisterSignalHandler': False,
102+
'ReloadServletClasses': False,
103+
'ReportRPCExceptionsInWebware': True,
104+
'ResponseBufferSize': 8 * 1024, # 8 kBytes
105+
'RetainSessions': True,
106+
'RPCExceptionReturn': 'traceback',
107+
'RunTasks': True,
108+
'SaveErrorMessages': True,
109+
'SecureSessionCookie': True,
110+
'SessionCookiePath': None,
111+
'HttpOnlySessionCookie': True,
112+
'SameSiteSessionCookie': 'Strict',
113+
'SessionModule': 'Session',
114+
'SessionName': '_SID_',
115+
'SessionPrefix': '',
116+
'SessionStore': 'Dynamic',
117+
'SessionStoreDir': 'Sessions',
118+
'SessionTimeout': 60,
119+
'ShowDebugInfoOnErrors': False,
120+
'SilentURIs': None,
121+
'UnknownFileTypes': {
122+
'ReuseServlets': True,
123+
'Technique': 'serveContent', # or redirectSansScript
124+
'CacheContent': False,
125+
'MaxCacheContentSize': 128 * 1024,
126+
'ReadBufferSize': 32 * 1024
127+
},
128+
'UseAutomaticPathSessions': False,
129+
'UseCascadingExtensions': True,
130+
'UseCookieSessions': True,
131+
'UserErrorMessage': (
136132
'The site is having technical difficulties with this page.'
137133
' An error has been logged, and the problem will be fixed'
138134
' as soon as possible. Sorry!'
139135
),
140-
UseSessionSweeper=True,
141-
Verbose=True,
142-
WSGIWrite=True, # use write callable with WSGI
143-
)
136+
'UseSessionSweeper': True,
137+
'Verbose': True,
138+
'WSGIWrite': True # use write callable with WSGI
139+
}
144140

145141

146142
class EndResponse(Exception):
@@ -467,10 +463,11 @@ def configFilename(self):
467463

468464
def configReplacementValues(self):
469465
"""Get config values that need to be escaped."""
470-
return dict(
471-
ServerSidePath=self._serverSidePath,
472-
WebwarePath=self._webwarePath,
473-
Development=self._development)
466+
return {
467+
'ServerSidePath': self._serverSidePath,
468+
'WebwarePath': self._webwarePath,
469+
'Development': self._development
470+
}
474471

475472
def development(self):
476473
"""Whether the application shall run in development mode"""
@@ -645,12 +642,14 @@ def writeActivityLog(self, trans):
645642
if mode == 'w':
646643
f.write(','.join(self.setting('ActivityLogColumns')) + '\n')
647644
values = []
648-
objects = dict(
649-
application=self, transaction=trans,
650-
request=trans.request(), response=trans.response(),
651-
servlet=trans.servlet(),
645+
objects = {
646+
'application': self, 'transaction': trans,
647+
'request': trans.request(),
648+
'response': trans.response(),
649+
'servlet': trans.servlet(),
652650
# don't cause creation of session here:
653-
session=trans._session)
651+
'session': trans._session
652+
}
654653
for column in self.setting('ActivityLogColumns'):
655654
try:
656655
value = valueForName(objects, column)
@@ -988,7 +987,7 @@ def handleExceptionInTransaction(self, excInfo, trans):
988987
editlink = f'{request.scriptName()}/Admin/EditFile' if self.setting(
989988
'IncludeEditLink') else None
990989
self._exceptionHandlerClass(
991-
self, trans, excInfo, dict(editlink=editlink))
990+
self, trans, excInfo, {'editlink': editlink})
992991

993992
def rootURLParser(self):
994993
"""Accessor: the Root URL parser.
@@ -1172,7 +1171,7 @@ def loadPlugIns(self):
11721171
def __call__(self, environ, start_response):
11731172
"""The WSGI application callable"""
11741173
verbose = self._verbose
1175-
requestDict = dict(environ=environ)
1174+
requestDict = {'environ': environ}
11761175

11771176
requestID = self._requestID
11781177
self._requestID = requestID + 1

webware/Examples/FileUpload.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
class FileUpload(ExamplePage):
55
"""This servlet shows how to handle uploaded files.
66
7-
The process is fairly self explanatory. You use a form like the one below
7+
The process is fairly self-explanatory. You use a form like the one below
88
in the writeContent method. When the form is uploaded, the request field
99
with the name you gave to the file selector form item will be an instance
1010
of the FieldStorage class from the standard Python module "cgi". The key

webware/Examples/ListBox.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ def awake(self, transaction):
2020
if session.hasValue('vars'):
2121
self._vars = session.value('vars')
2222
else:
23-
self._vars = dict(
24-
items=[], height=10, width=250, newCount=1, formCount=1)
23+
self._vars = {
24+
'items': [], 'height': 10, 'width': 250,
25+
'newCount': 1, 'formCount': 1
26+
}
2527
session.setValue('vars', self._vars)
2628
self._error = None
2729

@@ -81,7 +83,7 @@ def widthChange():
8183
def new(self):
8284
"""Add a new item to the list box."""
8385
newCount = self._vars['newCount']
84-
self._vars['items'].append(dict(name=f'New item {newCount}'))
86+
self._vars['items'].append({'name': f'New item {newCount}'})
8587
self._vars['newCount'] += 1
8688
self.writeBody()
8789

webware/Examples/SecurePage.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def loggedInUser(self):
128128
return self.session().value('authenticated_user', None)
129129

130130
def defaultConfig(self):
131-
return dict(RequireLogin=True)
131+
return {'RequireLogin': True}
132132

133133
def configFilename(self):
134134
return 'Configs/SecurePage.config'

webware/HTTPRequest.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""HTTP requests"""
22

3-
import cgi
43
import os
54
import sys
65
import traceback
@@ -11,7 +10,7 @@
1110
import HTTPResponse
1211

1312
from MiscUtils import NoDefault
14-
from WebUtils import FieldStorage
13+
from WebUtils.FieldStorage import FieldStorage
1514
from Request import Request
1615

1716
debug = False
@@ -38,11 +37,11 @@ def __init__(self, requestDict=None):
3837
# because bad headers sometimes can break the field storage
3938
# (see also https://bugs.python.org/issue27777).
4039
try:
41-
self._fields = FieldStorage.FieldStorage(
40+
self._fields = FieldStorage(
4241
self._input, environ=self._environ,
4342
keep_blank_values=True, strict_parsing=False)
4443
except Exception:
45-
self._fields = cgi.FieldStorage(keep_blank_values=True)
44+
self._fields = FieldStorage(keep_blank_values=True)
4645
traceback.print_exc(file=sys.stderr)
4746
self._cookies = Cookie()
4847
if 'HTTP_COOKIE' in self._environ:
@@ -64,7 +63,7 @@ def __init__(self, requestDict=None):
6463
self._time = time()
6564
self._environ = os.environ.copy()
6665
self._input = None
67-
self._fields = cgi.FieldStorage(keep_blank_values=True)
66+
self._fields = FieldStorage(keep_blank_values=True)
6867
self._cookies = Cookie()
6968

7069
env = self._environ
@@ -131,8 +130,8 @@ def __init__(self, requestDict=None):
131130

132131
# We use Tim O'Malley's Cookie class to get the cookies,
133132
# but then change them into an ordinary dictionary of values
134-
self._cookies = dict(
135-
(key, self._cookies[key].value) for key in self._cookies)
133+
self._cookies = {
134+
key: self._cookies[key].value for key in self._cookies}
136135

137136
self._contextName = None
138137
self._serverSidePath = self._serverSideContextPath = None

webware/HTTPResponse.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ def rawResponse(self):
441441
headers.append((key, value))
442442
for cookie in self._cookies.values():
443443
headers.append(('Set-Cookie', cookie.headerValue()))
444-
return dict(headers=headers, contents=self._strmOut.buffer())
444+
return {'headers': headers, 'contents': self._strmOut.buffer()}
445445

446446
def size(self):
447447
"""Return the size of the final contents of the response.

0 commit comments

Comments
 (0)