[misc] Use single quotes when possible

This commit is contained in:
Martin Rey 2020-10-13 10:12:35 +02:00 committed by Maike
parent d0fc51fd7e
commit eba21e8409
11 changed files with 32 additions and 28 deletions

View file

@ -57,8 +57,8 @@ if argv[0].endswith('kibicara'):
parser.add_argument( parser.add_argument(
'-v', '-v',
'--verbose', '--verbose',
action="count", action='count',
help="Raise verbosity level", help='Raise verbosity level',
) )
args = parser.parse_args() args = parser.parse_args()
@ -72,7 +72,7 @@ if argv[0].endswith('kibicara_mda'):
help='path to config file', help='path to config file',
) )
# the MDA passes the recipient address as command line argument # the MDA passes the recipient address as command line argument
parser.add_argument("recipient") parser.add_argument('recipient')
args = parser.parse_args() args = parser.parse_args()
if args is not None: if args is not None:

View file

@ -40,7 +40,7 @@ class Main:
} }
basicConfig( basicConfig(
level=LOGLEVELS.get(args.verbose, DEBUG), level=LOGLEVELS.get(args.verbose, DEBUG),
format="%(asctime)s %(name)s %(message)s", format='%(asctime)s %(name)s %(message)s',
) )
getLogger('aiosqlite').setLevel(WARNING) getLogger('aiosqlite').setLevel(WARNING)
Mapping.create_all() Mapping.create_all()
@ -71,8 +71,8 @@ class Main:
CORSMiddleware, CORSMiddleware,
allow_origins=config['cors_allow_origin'], allow_origins=config['cors_allow_origin'],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=['*'],
allow_headers=["*"], allow_headers=['*'],
) )
if config['frontend_path'] is not None: if config['frontend_path'] is not None:
app.mount( app.mount(

View file

@ -51,11 +51,11 @@ class EmailBot(Censor):
logger.debug('Trying to send: \n{0}'.format(body)) logger.debug('Trying to send: \n{0}'.format(body))
email.send_email( email.send_email(
subscriber.email, subscriber.email,
"Kibicara {0}".format(self.hood.name), 'Kibicara {0}'.format(self.hood.name),
body=body, body=body,
) )
except (ConnectionRefusedError, SMTPException): except (ConnectionRefusedError, SMTPException):
logger.exception("Sending email to subscriber failed.") logger.exception('Sending email to subscriber failed.')
spawner = Spawner(Hood, EmailBot) spawner = Spawner(Hood, EmailBot)

View file

@ -202,17 +202,19 @@ async def email_subscribe(
raise HTTPException(status_code=status.HTTP_409_CONFLICT) raise HTTPException(status_code=status.HTTP_409_CONFLICT)
email.send_email( email.send_email(
subscriber.email, subscriber.email,
"Subscribe to Kibicara {0}".format(hood.name), 'Subscribe to Kibicara {0}'.format(hood.name),
body='To confirm your subscription, follow this link: {0}'.format(confirm_link), body='To confirm your subscription, follow this link: {0}'.format(
confirm_link
),
) )
return {} return {}
except ConnectionRefusedError: except ConnectionRefusedError:
logger.info(token) logger.info(token)
logger.error("Sending subscription confirmation email failed.", exc_info=True) logger.error('Sending subscription confirmation email failed.', exc_info=True)
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY)
except SMTPException: except SMTPException:
logger.info(token) logger.info(token)
logger.error("Sending subscription confirmation email failed.", exc_info=True) logger.error('Sending subscription confirmation email failed.', exc_info=True)
raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY) raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY)
@ -252,7 +254,7 @@ async def email_unsubscribe(token, hood=Depends(get_hood_unauthorized)):
:param hood: Hood the Email bot belongs to. :param hood: Hood the Email bot belongs to.
""" """
try: try:
logger.warning("token is: {0}".format(token)) logger.warning('token is: {0}'.format(token))
payload = from_token(token) payload = from_token(token)
# If token.hood and url.hood are different, raise an error: # If token.hood and url.hood are different, raise an error:
if hood.id is not payload['hood']: if hood.id is not payload['hood']:
@ -305,14 +307,14 @@ async def email_message_create(
if message.secret == receiver.secret: if message.secret == receiver.secret:
# pass message.text to bot.py # pass message.text to bot.py
if await spawner.get(hood).publish(Message(message.text)): if await spawner.get(hood).publish(Message(message.text)):
logger.warning("Message was accepted: {0}".format(message.text)) logger.warning('Message was accepted: {0}'.format(message.text))
return {} return {}
else: else:
logger.warning("Message was't accepted: {0}".format(message.text)) logger.warning('Message was\'t accepted: {0}'.format(message.text))
raise HTTPException( raise HTTPException(
status_code=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS status_code=status.HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS
) )
logger.warning( logger.warning(
"Someone is trying to submit an email without the correct API secret" 'Someone is trying to submit an email without the correct API secret'
) )
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)

View file

@ -129,7 +129,7 @@ class TwitterBot(Censor):
remove_indices.update(range(url.indices[0], url.indices[1] + 1)) remove_indices.update(range(url.indices[0], url.indices[1] + 1))
for symbol in entities.symbols: for symbol in entities.symbols:
remove_indices.update(range(symbol.indices[0], symbol.indices[1] + 1)) remove_indices.update(range(symbol.indices[0], symbol.indices[1] + 1))
filtered_text = "" filtered_text = ''
for index, character in enumerate(text): for index, character in enumerate(text):
if index not in remove_indices: if index not in remove_indices:
filtered_text += character filtered_text += character

View file

@ -130,8 +130,8 @@ async def twitter_create(response: Response, hood=Depends(get_hood)):
request_token = await get_oauth_token( request_token = await get_oauth_token(
config['twitter']['consumer_key'], config['twitter']['consumer_key'],
config['twitter']['consumer_secret'], config['twitter']['consumer_secret'],
callback_uri="{0}/dashboard/twitter-callback?hood={1}".format( callback_uri='{0}/dashboard/twitter-callback?hood={1}'.format(
config["frontend_url"], hood.id config['frontend_url'], hood.id
), ),
) )
if request_token['oauth_callback_confirmed'] != 'true': if request_token['oauth_callback_confirmed'] != 'true':

View file

@ -111,7 +111,7 @@ async def admin_register(values: BodyAdmin):
admin = await Admin.objects.filter(email=values.email).all() admin = await Admin.objects.filter(email=values.email).all()
if admin: if admin:
raise HTTPException(status_code=status.HTTP_409_CONFLICT) raise HTTPException(status_code=status.HTTP_409_CONFLICT)
body = '{0}/confirm?token={1}'.format(config["frontend_url"], register_token) body = '{0}/confirm?token={1}'.format(config['frontend_url'], register_token)
logger.debug(body) logger.debug(body)
email.send_email( email.send_email(
to=values.email, to=values.email,
@ -183,7 +183,9 @@ async def admin_reset_password(values: BodyEmail):
admin = await Admin.objects.filter(email=values.email).all() admin = await Admin.objects.filter(email=values.email).all()
if not admin: if not admin:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
body = '{0}/password-reset?token={1}'.format(config["frontend_url"], register_token) body = '{0}/password-reset?token={1}'.format(
config['frontend_url'], register_token
)
logger.debug(body) logger.debug(body)
email.send_email( email.send_email(
to=values.email, to=values.email,

View file

@ -9,7 +9,7 @@ from fastapi import status
from pytest import fixture from pytest import fixture
@fixture(scope="function") @fixture(scope='function')
def email_row(client, hood_id, auth_header): def email_row(client, hood_id, auth_header):
response = client.post( response = client.post(
'/api/hoods/{0}/email/'.format(hood_id), '/api/hoods/{0}/email/'.format(hood_id),

View file

@ -41,8 +41,8 @@ def test_email_subscribe_unsubscribe(client, hood_id, receive_email):
def test_email_message(client, hood_id, trigger_id, email_row): def test_email_message(client, hood_id, trigger_id, email_row):
body = { body = {
'text': "test", 'text': 'test',
'author': "test@localhost", 'author': 'test@localhost',
'secret': email_row['secret'], 'secret': email_row['secret'],
} }
response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body) response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body)
@ -78,6 +78,6 @@ test
--AqNPlAX243a8sip3B7kXv8UKD8wuti-- --AqNPlAX243a8sip3B7kXv8UKD8wuti--
""" """
proc = subprocess.run( proc = subprocess.run(
["kibicara_mda", "hood"], stdout=subprocess.PIPE, input=mail, encoding='ascii' ['kibicara_mda', 'hood'], stdout=subprocess.PIPE, input=mail, encoding='ascii'
) )
assert proc.returncode == 0 assert proc.returncode == 0

View file

@ -18,6 +18,6 @@ def test_email_delete_unauthorized(client, hood_id, email_row):
def test_email_message_unauthorized(client, hood_id, email_row): def test_email_message_unauthorized(client, hood_id, email_row):
body = {"text": "test", "author": "author", "secret": "wrong"} body = {'text': 'test', 'author': 'author', 'secret': 'wrong'}
response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body) response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body)
assert response.status_code == status.HTTP_401_UNAUTHORIZED assert response.status_code == status.HTTP_401_UNAUTHORIZED

View file

@ -32,8 +32,8 @@ def test_email_subscribe_confirm_wrong_hood(client):
def test_email_message_wrong(client, hood_id, email_row): def test_email_message_wrong(client, hood_id, email_row):
body = { body = {
'text': "", 'text': '',
'author': "test@localhost", 'author': 'test@localhost',
'secret': email_row['secret'], 'secret': email_row['secret'],
} }
response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body) response = client.post('/api/hoods/{0}/email/messages/'.format(hood_id), json=body)