Skip to content

Commit

Permalink
Format code using Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
amotl committed Mar 31, 2024
1 parent dee9696 commit 2725137
Show file tree
Hide file tree
Showing 14 changed files with 174 additions and 79 deletions.
10 changes: 8 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,14 @@ jobs:
pip install --requirement=requirements-test.txt
pip install --editable=.[service]
- name: Run tests
run: pytest
- name: Run linters
if: matrix.python-version != '3.6' && matrix.python-version != '3.7'
run: |
poe lint
- name: Run software tests
run: |
poe test
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v4
Expand Down
1 change: 1 addition & 0 deletions apicast/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""Access bee flight forecast information published by Deutscher Wetterdienst (DWD)"""

__appname__ = "apicast"
__version__ = "0.8.6"
27 changes: 16 additions & 11 deletions apicast/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@
# (c) 2020-2021 Andreas Motl <[email protected]>
# License: GNU Affero General Public License, Version 3
import logging
from typing import List, Dict
from typing import Dict, List

from fastapi import FastAPI, Query
from fastapi.responses import HTMLResponse, PlainTextResponse

from apicast import __appname__, __version__
from apicast.core import (DwdBeeflightForecast, dwd_copyright, dwd_source,
producer_link, producer_name)
from apicast.core import (
DwdBeeflightForecast,
dwd_copyright,
dwd_source,
producer_link,
producer_name,
)
from apicast.format import Formatter

app = FastAPI()
Expand All @@ -21,9 +26,11 @@

@app.get("/", response_class=HTMLResponse)
def index():

appname = f"{__appname__} {__version__}"
description = "Apicast acquires bee flight forecast information published by Deutscher Wetterdienst (DWD)."
description = (
"Apicast acquires bee flight forecast information "
"published by Deutscher Wetterdienst (DWD)."
)

data_index_items = []
for location in dbf.get_station_slugs():
Expand All @@ -44,7 +51,7 @@ def index():
</div>
<div style="clear: both"/>
</li>
"""
""" # noqa: E501
data_index_items.append(item)

data_index_items_html = "\n".join(data_index_items)
Expand Down Expand Up @@ -105,12 +112,12 @@ def index():
</ul>
</body>
</html>
"""
""" # noqa: E501


@app.get("/robots.txt", response_class=PlainTextResponse)
def robots():
return f"""
return """
User-agent: *
Disallow: /beeflight/
""".strip()
Expand All @@ -135,7 +142,6 @@ def beeflight_forecast_by_slug(
format: str = Query(default="json"),
translate: bool = Query(default=False),
):

station_slug = f"{state}/{station}"

try:
Expand Down Expand Up @@ -164,7 +170,7 @@ def beeflight_forecast_by_slug(


def make_json_response(data: List[Dict], location: str = None):
response = {
return {
"meta": {
"source": dwd_source,
"producer": f"{producer_name} - {producer_link}",
Expand All @@ -175,7 +181,6 @@ def make_json_response(data: List[Dict], location: str = None):
},
"data": data,
}
return response


def start_service(listen_address, reload: bool = False):
Expand Down
4 changes: 1 addition & 3 deletions apicast/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def run():
# Start HTTP service with dynamic code reloading
apicast service --reload
"""
""" # noqa: E501

name = f"{__appname__} {__version__}"

Expand Down Expand Up @@ -89,7 +89,6 @@ def run():

# Run command.
if options.stations:

if options.slugs:
result = dbf.get_station_slugs()
print("\n".join(result))
Expand All @@ -106,7 +105,6 @@ def run():


def format_beeflight_forecast(result, format="json"):

if not result.data:
raise ValueError("No data found or unable to parse")

Expand Down
16 changes: 4 additions & 12 deletions apicast/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
See also https://community.hiveeyes.org/t/dwd-prognose-bienenflug/787
"""

import dataclasses
from typing import List

Expand All @@ -20,7 +21,6 @@

from apicast import __appname__, __version__


user_agent = f"{__appname__}/{__version__}"
dwd_source = "https://www.dwd.de/DE/leistungen/biene_flug/bienenflug.html"
dwd_copyright = "© Deutscher Wetterdienst (DWD), Agricultural Meteorology Department"
Expand Down Expand Up @@ -54,15 +54,13 @@ def copy(self):


class DwdBeeflightForecast:

baseurl = "https://www.dwd.de/DE/leistungen/biene_flug/bienenflug.json?cl2Categories_LeistungsId=bienenflug"

session = requests.Session()
session.headers["User-Agent"] = user_agent

@ttl_cache(60 * 60 * 24)
def get_states(self) -> List[State]:

states: List[State] = []

# Request federal states.
Expand All @@ -75,18 +73,16 @@ def get_states(self) -> List[State]:

states.append(state)

# sites.sort(key=operator.attrgetter("label"))
# sites.sort(key=operator.attrgetter("label")) # noqa: ERA001

return states

@ttl_cache(60 * 60 * 24)
def get_stations(self) -> List[Station]:

stations: List[Station] = []

# Request federal states.
for state in self.get_states():

# Request sites.
response = self.session.get(
self.baseurl,
Expand All @@ -111,7 +107,7 @@ def get_stations(self) -> List[Station]:

stations.append(station)

# sites.sort(key=operator.attrgetter("label"))
# sites.sort(key=operator.attrgetter("label")) # noqa: ERA001

return stations

Expand All @@ -130,7 +126,6 @@ def get_station_by_slug(self, slug):

@ttl_cache(60 * 60)
def get_data(self, station: Station) -> Result:

response = self.session.get(
self.baseurl,
params={
Expand All @@ -155,10 +150,7 @@ def get_data(self, station: Station) -> Result:
data = self.parse_html_table(table)

# Ready.
result = Result(
station=station, station_name=station_name, data=data, footnote=footnote
)
return result
return Result(station=station, station_name=station_name, data=data, footnote=footnote)

@staticmethod
def parse_html_table(html):
Expand Down
6 changes: 3 additions & 3 deletions apicast/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ class Formatter:
def __init__(self, result):
self.result = deepcopy(result)
self.data = self.result.data
self.title = u"### Prognose des Bienenfluges in {}".format(self.result.station_name)
self.title = "### Prognose des Bienenfluges in {}".format(self.result.station_name)

def translate(self):
self.title = u"### Beeflight forecast for {}".format(self.result.station_name)
self.title = "### Beeflight forecast for {}".format(self.result.station_name)
for item in self.data:
for index, slot in enumerate(item):
for key, value in self.LABEL_MAP.items():
Expand Down Expand Up @@ -79,9 +79,9 @@ def machinify(self):
item[key] = value
return data

# ruff: noqa: T201
def table_markdown(self):
with io.StringIO() as buffer, redirect_stdout(buffer):

# Report about weather station / observation location
print(self.title)
print()
Expand Down
1 change: 0 additions & 1 deletion apicast/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ def configure_http_logging(options):
def normalize_options(options):
normalized = {}
for key, value in options.items():

# Add primary variant.
key = key.strip("--<>")
normalized[key] = value
Expand Down
94 changes: 94 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
[tool.pytest.ini_options]
addopts = """
-ra -q --verbosity=3
--cov --cov-report=term-missing --cov-report=xml
"""
minversion = "2.0"
log_level = "DEBUG"
log_cli_level = "DEBUG"
testpaths = [
"apicast",
"test",
]
xfail_strict = true

[tool.coverage.run]
source = ["apicast"]

[tool.coverage.report]
show_missing = true
fail_under = 0
omit = [
"test/*",
]

[tool.ruff]
line-length = 100
extend-exclude = [
]

[tool.ruff.lint]
select = [
# Pycodestyle
"E",
"W",
# Pyflakes
"F",
# isort
"I",
# Bandit
"S",
# flake8-quotes
"Q",
# eradicate
"ERA",
# flake8-2020
"YTT",
# print
"T20",
# return
"RET",
# pyupgrade
# "UP",
# flake8-commas
"COM",
# future-annotations
# "FA",
# flake8-type-checking
"TCH",
# flake8-unused-arguments
"ARG",
# flake8-use-pathlib
# "PTH"
]
extend-ignore = [
# Unnecessary `elif` after `return` or `raise` statement.
"RET505",
"RET506",
# No trailing commas.
"COM812"
]
unfixable = ["ERA", "F401", "F841", "T20", "ERA001"]

[tool.ruff.lint.per-file-ignores]
"apicast/cli.py" = ["T201"]
"test/*" = ["S101"]


# ===================
# Tasks configuration
# ===================

[tool.poe.tasks]
format = [
{cmd="ruff format"},
{cmd="ruff check --fix"},
]
lint = [
{cmd="ruff check"},
]
test = [
{cmd="pytest"},
]
build = {cmd="python -m build"}
check = ["lint", "test"]
2 changes: 2 additions & 0 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
datadiff>=2.0,<3
fastapi[test]
marko<3
poethepoet<0.26
pytest>=6.1.0,<8
pytest-cov<6
ruff<0.4;python_version>='3.7'
7 changes: 4 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
import os
from io import open
from setuptools import setup, find_packages

from setuptools import find_packages, setup

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, "README.rst"), encoding="UTF-8").read()
Expand All @@ -10,8 +11,8 @@
name="apicast",
version="0.8.6",
description="Python client and HTTP service to access bee flight forecast "
"information published by Deutscher Wetterdienst (DWD), the "
"federal meteorological service in Germany.",
"information published by Deutscher Wetterdienst (DWD), the "
"federal meteorological service in Germany.",
long_description=README,
license="AGPL 3, EUPL 1.2",
classifiers=[
Expand Down
1 change: 0 additions & 1 deletion test/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from apicast.api import app


client = TestClient(app)


Expand Down
Loading

0 comments on commit 2725137

Please sign in to comment.