Skip to content

Commit

Permalink
Merge pull request #85 from Gustry/fstring
Browse files Browse the repository at this point in the history
Bulk conversion to fstring
  • Loading branch information
Gustry authored Aug 13, 2024
2 parents 01e4fcf + 5ab19e0 commit 9818afb
Show file tree
Hide file tree
Showing 11 changed files with 110 additions and 133 deletions.
24 changes: 12 additions & 12 deletions lizmap_server/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def write_json_response(data: Dict[str, str], response: QgsServerResponse, code:
""" Write data as JSON response. """
response.setStatusCode(code)
response.setHeader("Content-Type", "application/json")
Logger.info("Sending JSON response : {}".format(data))
Logger.info(f"Sending JSON response : {data}")
response.write(json.dumps(data))


Expand Down Expand Up @@ -71,7 +71,7 @@ def find_layer(layer_name: str, project: QgsProject) -> Optional[QgsMapLayer]:

if not found:
Logger.warning(
"The layer '{}' has not been found in the project '{}'".format(layer_name, project.fileName()))
f"The layer '{layer_name}' has not been found in the project '{project.fileName()}'")
return None

found: QgsMapLayer
Expand Down Expand Up @@ -123,7 +123,7 @@ def get_lizmap_config(qgis_project_path: str) -> Union[Dict, None]:
return None

last_modified = Path(config_path).stat().st_mtime
logger.info("Fetching {} cfg file with last modified timestamp : {}".format(config_path, last_modified))
logger.info(f"Fetching {config_path} cfg file with last modified timestamp : {last_modified}")
return _get_lizmap_config(config_path, last_modified)


Expand Down Expand Up @@ -198,22 +198,22 @@ def get_lizmap_layer_login_filter(config: Dict, layer_name: str) -> Union[Dict,
# Check loginFilteredLayers for layer
if layer_name not in login_filtered_layers or not login_filtered_layers[layer_name]:
# Lizmap config has no options
logger.info("Layer {} has no loginFilteredLayers".format(layer_name))
logger.info(f"Layer {layer_name} has no loginFilteredLayers")
return None

# get loginFilteredLayers for layer to check it
cfg_layer_login_filter = login_filtered_layers[layer_name]

# Check loginFilteredLayers for layer is dict
if not isinstance(cfg_layer_login_filter, dict):
logger.warning("loginFilteredLayers for layer {} is not dict".format(layer_name))
logger.warning(f"loginFilteredLayers for layer {layer_name} is not dict")
return None

if 'layerId' not in cfg_layer_login_filter or \
'filterAttribute' not in cfg_layer_login_filter or \
'filterPrivate' not in cfg_layer_login_filter:
# loginFilteredLayers for layer not well formed
logger.warning("loginFilteredLayers for layer {} not well formed".format(layer_name))
logger.warning(f"loginFilteredLayers for layer {layer_name} not well formed")
return None

return cfg_layer_login_filter
Expand All @@ -234,7 +234,7 @@ def get_lizmap_groups(handler: QgsRequestHandler) -> Tuple[str]:
user_groups = headers.get('X-Lizmap-User-Groups')
if user_groups is not None:
groups = [g.strip() for g in user_groups.split(',')]
logger.info("Lizmap user groups in request headers : {}".format(','.join(groups)))
logger.info(f"Lizmap user groups in request headers : {','.join(groups)}")
else:
logger.info("No request headers provided")

Expand All @@ -251,7 +251,7 @@ def get_lizmap_groups(handler: QgsRequestHandler) -> Tuple[str]:
user_groups = params.get('LIZMAP_USER_GROUPS')
if user_groups is not None:
groups = [g.strip() for g in user_groups.split(',')]
logger.info("Lizmap user groups in parameters : {}".format(','.join(groups)))
logger.info(f"Lizmap user groups in parameters : {','.join(groups)}")

# noinspection PyTypeChecker
return tuple(groups)
Expand All @@ -272,7 +272,7 @@ def get_lizmap_user_login(handler: QgsRequestHandler) -> str:
user_login = headers.get('X-Lizmap-User')
if user_login is not None:
login = user_login
logger.info("Lizmap user login in request headers : {}".format(login))
logger.info(f"Lizmap user login in request headers : {login}")
else:
logger.info("No request headers provided")

Expand All @@ -288,7 +288,7 @@ def get_lizmap_user_login(handler: QgsRequestHandler) -> str:
user_login = params.get('LIZMAP_USER')
if user_login is not None:
login = user_login
logger.info("Lizmap user login in parameters : {}".format(login))
logger.info(f"Lizmap user login in parameters : {login}")

return login

Expand Down Expand Up @@ -341,7 +341,7 @@ def is_editing_context(handler: QgsRequestHandler) -> bool:
editing_context = headers.get('X-Lizmap-Edition-Context')
if editing_context is not None:
result = to_bool(editing_context)
logger.info("Lizmap editing context is found in request headers : {}".format(result))
logger.info(f"Lizmap editing context is found in request headers : {result}")
return result

logger.info("No editing context found in request headers")
Expand All @@ -351,7 +351,7 @@ def is_editing_context(handler: QgsRequestHandler) -> bool:
result = params.get('LIZMAP_EDITION_CONTEXT')
if result is not None:
result = to_bool(result)
logger.info("Lizmap editing context is found in parameters : {}".format(result))
logger.info(f"Lizmap editing context is found in parameters : {result}")
return result

logger.info("No lizmap editing context filter in parameters : default value false")
Expand Down
2 changes: 1 addition & 1 deletion lizmap_server/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self, code: str, msg: str, response_code: int = 500) -> None:
self.msg = msg
self.code = code
self.response_code = response_code
Logger.critical("{} request error {}: {}".format(self.service, code, msg))
Logger.critical(f"{self.service} request error {code}: {msg}")

def formatResponse(self, response: QgsServerResponse) -> None:
""" Format error response
Expand Down
56 changes: 28 additions & 28 deletions lizmap_server/expression_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def executeRequest(self, request: QgsServerRequest, response: QgsServerResponse,
except Exception:
raise ExpressionServiceError(
"Bad request error",
"Invalid POST DATA for '{}'".format(reqparam),
f"Invalid POST DATA for '{reqparam}'",
400)

if reqparam == 'EVALUATE':
Expand Down Expand Up @@ -141,7 +141,7 @@ def evaluate(params: Dict[str, str], response: QgsServerResponse, project: QgsPr
if not layer:
raise ExpressionServiceError(
"Bad request error",
"Invalid LAYER parameter for 'Evaluate': {} provided".format(layer_name),
f"Invalid LAYER parameter for 'Evaluate': {layer_name} provided",
400)

# get expressions
Expand All @@ -153,17 +153,17 @@ def evaluate(params: Dict[str, str], response: QgsServerResponse, project: QgsPr
"Bad request error",
"Invalid 'Evaluate' REQUEST: EXPRESSION or EXPRESSIONS parameter is mandatory",
400)
expressions = '["{}"]'.format(expression)
expressions = f'["{expression}"]'

# try to load expressions list or dict
try:
exp_json = json.loads(expressions)
except Exception:
logger.critical(
"JSON loads expressions '{}' exception:\n{}".format(expressions, traceback.format_exc()))
f"JSON loads expressions '{expressions}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'Evaluate' REQUEST: EXPRESSIONS '{}' are not well formed".format(expressions),
f"Invalid 'Evaluate' REQUEST: EXPRESSIONS '{expressions}' are not well formed",
400)

# create expression context
Expand Down Expand Up @@ -192,11 +192,11 @@ def evaluate(params: Dict[str, str], response: QgsServerResponse, project: QgsPr
exp.setAreaUnits(project.areaUnits())

if exp.hasParserError():
exp_parser_errors.append('Error "{}": {}'.format(e, exp.parserErrorString()))
exp_parser_errors.append(f'Error "{e}": {exp.parserErrorString()}')
continue

if not exp.isValid():
exp_parser_errors.append('Expression not valid "{}"'.format(e))
exp_parser_errors.append(f'Expression not valid "{e}"')
continue

exp.prepare(exp_context)
Expand Down Expand Up @@ -245,16 +245,16 @@ def evaluate(params: Dict[str, str], response: QgsServerResponse, project: QgsPr
geojson = json.loads(features)
except Exception:
logger.critical(
"JSON loads features '{}' exception:\n{}".format(features, traceback.format_exc()))
f"JSON loads features '{features}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'Evaluate' REQUEST: FEATURES '{}' are not well formed".format(features),
f"Invalid 'Evaluate' REQUEST: FEATURES '{features}' are not well formed",
400)

if not geojson or not isinstance(geojson, list) or len(geojson) == 0:
raise ExpressionServiceError(
"Bad request error",
"Invalid 'Evaluate' REQUEST: FEATURES '{}' are not well formed".format(features),
f"Invalid 'Evaluate' REQUEST: FEATURES '{features}' are not well formed",
400)

if 'type' not in geojson[0] or geojson[0]['type'] != 'Feature':
Expand All @@ -279,7 +279,7 @@ def evaluate(params: Dict[str, str], response: QgsServerResponse, project: QgsPr
if not feature_list:
raise ExpressionServiceError(
"Bad request error",
"Invalid FEATURES for 'Evaluate': not GeoJSON features array provided\n{}".format(features),
f"Invalid FEATURES for 'Evaluate': not GeoJSON features array provided\n{features}",
400)

# Extend layer fields with this provided in GeoJSON Features
Expand Down Expand Up @@ -363,7 +363,7 @@ def replace_expression_text(
if not layer:
raise ExpressionServiceError(
"Bad request error",
"Invalid LAYER parameter for 'ReplaceExpressionText': {} provided".format(layer_name),
f"Invalid LAYER parameter for 'ReplaceExpressionText': {layer_name} provided",
400)

# get strings
Expand All @@ -375,17 +375,17 @@ def replace_expression_text(
"Bad request error",
"Invalid 'ReplaceExpressionText' REQUEST: STRING or STRINGS parameter is mandatory",
400)
strings = '["{}"]'.format(the_string)
strings = f'["{the_string}"]'

# try to load expressions list or dict
try:
str_json = json.loads(strings)
except Exception:
logger.critical(
"JSON loads strings '{}' exception:\n{}".format(strings, traceback.format_exc()))
f"JSON loads strings '{strings}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'ReplaceExpressionText' REQUEST: STRINGS '{}' are not well formed".format(strings),
f"Invalid 'ReplaceExpressionText' REQUEST: STRINGS '{strings}' are not well formed",
400)

# get features
Expand Down Expand Up @@ -443,16 +443,16 @@ def replace_expression_text(
geojson = json.loads(features)
except Exception:
logger.critical(
"JSON loads features '{}' exception:\n{}".format(features, traceback.format_exc()))
f"JSON loads features '{features}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'Evaluate' REQUEST: FEATURES '{}' are not well formed".format(features),
f"Invalid 'Evaluate' REQUEST: FEATURES '{features}' are not well formed",
400)

if not geojson or not isinstance(geojson, list) or len(geojson) == 0:
raise ExpressionServiceError(
"Bad request error",
"Invalid 'Evaluate' REQUEST: FEATURES '{}' are not well formed".format(features),
f"Invalid 'Evaluate' REQUEST: FEATURES '{features}' are not well formed",
400)

if ('type' not in geojson[0]) or geojson[0]['type'] != 'Feature':
Expand Down Expand Up @@ -571,7 +571,7 @@ def get_feature_with_form_scope(
if not layer:
raise ExpressionServiceError(
"Bad request error",
"Invalid LAYER parameter for 'VirtualField': {} provided".format(layer_name),
f"Invalid LAYER parameter for 'VirtualField': {layer_name} provided",
400)

# get filter
Expand All @@ -595,7 +595,7 @@ def get_feature_with_form_scope(
geojson = json.loads(form_feature)
except Exception:
logger.critical(
"JSON loads form feature '{}' exception:\n{}".format(form_feature, traceback.format_exc()))
f"JSON loads form feature '{form_feature}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'GetFeatureWithFormScope' REQUEST: FORM_FEATURE '{}' are not well formed".format(
Expand Down Expand Up @@ -654,7 +654,7 @@ def get_feature_with_form_scope(
geojson = json.loads(parent_feature)
except Exception:
logger.critical(
"JSON loads form feature '{}' exception:\n{}".format(parent_feature, traceback.format_exc()))
f"JSON loads form feature '{parent_feature}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'GetFeatureWithFormScope' REQUEST: PARENT_FEATURE '{}' are not well formed".format(
Expand Down Expand Up @@ -792,7 +792,7 @@ def virtualFields(params: Dict[str, str], response: QgsServerResponse, project:
if not layer:
raise ExpressionServiceError(
"Bad request error",
"Invalid LAYER parameter for 'VirtualFields': {} provided".format(layer_name),
f"Invalid LAYER parameter for 'VirtualFields': {layer_name} provided",
400)

# get virtuals
Expand All @@ -808,16 +808,16 @@ def virtualFields(params: Dict[str, str], response: QgsServerResponse, project:
vir_json = json.loads(virtuals)
except Exception:
logger.critical(
"JSON loads virtuals '{}' exception:\n{}".format(virtuals, traceback.format_exc()))
f"JSON loads virtuals '{virtuals}' exception:\n{traceback.format_exc()}")
raise ExpressionServiceError(
"Bad request error",
"Invalid 'VirtualFields' REQUEST: VIRTUALS '{}' are not well formed".format(virtuals),
f"Invalid 'VirtualFields' REQUEST: VIRTUALS '{virtuals}' are not well formed",
400)

if not isinstance(vir_json, dict):
raise ExpressionServiceError(
"Bad request error",
"Invalid 'VirtualFields' REQUEST: VIRTUALS '{}' are not well formed".format(virtuals),
f"Invalid 'VirtualFields' REQUEST: VIRTUALS '{virtuals}' are not well formed",
400)

# create expression context
Expand All @@ -841,11 +841,11 @@ def virtualFields(params: Dict[str, str], response: QgsServerResponse, project:
exp.setAreaUnits(project.areaUnits())

if exp.hasParserError():
exp_parser_errors.append('Error "{}": {}'.format(e, exp.parserErrorString()))
exp_parser_errors.append(f'Error "{e}": {exp.parserErrorString()}')
continue

if not exp.isValid():
exp_parser_errors.append('Expression not valid "{}"'.format(e))
exp_parser_errors.append(f'Expression not valid "{e}"')
continue

exp.prepare(exp_context)
Expand Down Expand Up @@ -878,7 +878,7 @@ def virtualFields(params: Dict[str, str], response: QgsServerResponse, project:
if not req_exp.isValid():
raise ExpressionServiceError(
"Bad request error",
"Invalid FILTER for 'VirtualFields' Expression not valid \"{}\"".format(req_filter),
f"Invalid FILTER for 'VirtualFields' Expression not valid \"{req_filter}\"",
400)

req_exp.prepare(exp_context)
Expand Down
Loading

0 comments on commit 9818afb

Please sign in to comment.