diff --git a/.devcontainer/devcontainer.env b/.devcontainer/devcontainer.env new file mode 100644 index 0000000..9843ca8 --- /dev/null +++ b/.devcontainer/devcontainer.env @@ -0,0 +1,2 @@ +PORT_PREFIX=${PORT_PREFIX} +CONTAINER_PREFIX=${USER} diff --git a/.devcontainer/python-3.10/devcontainer.json b/.devcontainer/python-3.10/devcontainer.json new file mode 100644 index 0000000..0b23638 --- /dev/null +++ b/.devcontainer/python-3.10/devcontainer.json @@ -0,0 +1,57 @@ +{ + "name": "python-3.10", + "dockerComposeFile": [ + "./docker-compose.yml" + ], + "service": "python-3.10", + "forwardPorts": [], + "shutdownAction": "stopCompose", + "workspaceFolder": "/workspaces/weatherman", + "remoteEnv": {}, + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "installOhMyZsh": true, + "configureZshAsDefaultShell": true, + "username": "vscode", + "userUid": "1000", + "userGid": "1000" + }, + "ghcr.io/devcontainers/features/node:1": {}, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest", + "ppa": true + }, + "ghcr.io/devcontainers/features/git-lfs:1": {}, + "ghcr.io/robbert229/devcontainer-features/postgresql-client:1": {} + }, + "updateContentCommand": "bash .devcontainer/setup.sh", + "postCreateCommand": [], + "customizations": { + "vscode": { + "settings": { + "python.linting.enabled": true, + "python.testing.pytestEnabled": true, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "always" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.vscode-pylance" + }, + "editor.rulers": [ + 80 + ] + }, + "extensions": [ + "ms-python.python", + "ms-toolsai.jupyter", + "ms-toolsai.vscode-jupyter-cell-tags", + "ms-toolsai.jupyter-keymap", + "ms-toolsai.jupyter-renderers", + "ms-toolsai.vscode-jupyter-slideshow", + "ms-python.vscode-pylance" + ] + } + } +} diff --git a/.devcontainer/python-3.10/docker-compose.yml b/.devcontainer/python-3.10/docker-compose.yml new file mode 100644 index 0000000..52d6c6e --- /dev/null +++ b/.devcontainer/python-3.10/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +services: + python-3.10: # nosemgrep + image: mcr.microsoft.com/devcontainers/python:3.10 + container_name: $USER-python-3.10-weatherman + volumes: + - ../../:/workspaces/weatherman:cached + command: sleep infinity + env_file: + - ../devcontainer.env + platform: linux/amd64 + networks: + - weatherman-network + +networks: + weatherman-network: + name: "${USER}-weatherman-network" diff --git a/.devcontainer/python-3.11/devcontainer.json b/.devcontainer/python-3.11/devcontainer.json new file mode 100644 index 0000000..ba5d3c8 --- /dev/null +++ b/.devcontainer/python-3.11/devcontainer.json @@ -0,0 +1,57 @@ +{ + "name": "python-3.11", + "dockerComposeFile": [ + "./docker-compose.yml" + ], + "service": "python-3.11", + "forwardPorts": [], + "shutdownAction": "stopCompose", + "workspaceFolder": "/workspaces/weatherman", + "remoteEnv": {}, + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "installOhMyZsh": true, + "configureZshAsDefaultShell": true, + "username": "vscode", + "userUid": "1000", + "userGid": "1000" + }, + "ghcr.io/devcontainers/features/node:1": {}, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest", + "ppa": true + }, + "ghcr.io/devcontainers/features/git-lfs:1": {}, + "ghcr.io/robbert229/devcontainer-features/postgresql-client:1": {} + }, + "updateContentCommand": "bash .devcontainer/setup.sh", + "postCreateCommand": [], + "customizations": { + "vscode": { + "settings": { + "python.linting.enabled": true, + "python.testing.pytestEnabled": true, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "always" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.vscode-pylance" + }, + "editor.rulers": [ + 80 + ] + }, + "extensions": [ + "ms-python.python", + "ms-toolsai.jupyter", + "ms-toolsai.vscode-jupyter-cell-tags", + "ms-toolsai.jupyter-keymap", + "ms-toolsai.jupyter-renderers", + "ms-toolsai.vscode-jupyter-slideshow", + "ms-python.vscode-pylance" + ] + } + } +} diff --git a/.devcontainer/python-3.11/docker-compose.yml b/.devcontainer/python-3.11/docker-compose.yml new file mode 100644 index 0000000..ab720e9 --- /dev/null +++ b/.devcontainer/python-3.11/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +services: + python-3.11: # nosemgrep + image: mcr.microsoft.com/devcontainers/python:3.11 + container_name: $USER-python-3.11-weatherman + volumes: + - ../../:/workspaces/weatherman:cached + command: sleep infinity + env_file: + - ../devcontainer.env + platform: linux/amd64 + networks: + - weatherman-network + +networks: + weatherman-network: + name: "${USER}-weatherman-network" diff --git a/.devcontainer/python-3.12/devcontainer.json b/.devcontainer/python-3.12/devcontainer.json new file mode 100644 index 0000000..d07c388 --- /dev/null +++ b/.devcontainer/python-3.12/devcontainer.json @@ -0,0 +1,57 @@ +{ + "name": "python-3.12", + "dockerComposeFile": [ + "./docker-compose.yml" + ], + "service": "python-3.12", + "forwardPorts": [], + "shutdownAction": "stopCompose", + "workspaceFolder": "/workspaces/weatherman", + "remoteEnv": {}, + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "installOhMyZsh": true, + "configureZshAsDefaultShell": true, + "username": "vscode", + "userUid": "1000", + "userGid": "1000" + }, + "ghcr.io/devcontainers/features/node:1": {}, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest", + "ppa": true + }, + "ghcr.io/devcontainers/features/git-lfs:1": {}, + "ghcr.io/robbert229/devcontainer-features/postgresql-client:1": {} + }, + "updateContentCommand": "bash .devcontainer/setup.sh", + "postCreateCommand": [], + "customizations": { + "vscode": { + "settings": { + "python.linting.enabled": true, + "python.testing.pytestEnabled": true, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "always" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.vscode-pylance" + }, + "editor.rulers": [ + 80 + ] + }, + "extensions": [ + "ms-python.python", + "ms-toolsai.jupyter", + "ms-toolsai.vscode-jupyter-cell-tags", + "ms-toolsai.jupyter-keymap", + "ms-toolsai.jupyter-renderers", + "ms-toolsai.vscode-jupyter-slideshow", + "ms-python.vscode-pylance" + ] + } + } +} diff --git a/.devcontainer/python-3.12/docker-compose.yml b/.devcontainer/python-3.12/docker-compose.yml new file mode 100644 index 0000000..b82388c --- /dev/null +++ b/.devcontainer/python-3.12/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +services: + python-3.12: # nosemgrep + image: mcr.microsoft.com/devcontainers/python:3.12 + container_name: $USER-python-3.12-weatherman + volumes: + - ../../:/workspaces/weatherman:cached + command: sleep infinity + env_file: + - ../devcontainer.env + platform: linux/amd64 + networks: + - weatherman-network + +networks: + weatherman-network: + name: "${USER}-weatherman-network" diff --git a/.devcontainer/python-3.9/devcontainer.json b/.devcontainer/python-3.9/devcontainer.json new file mode 100644 index 0000000..79c6aff --- /dev/null +++ b/.devcontainer/python-3.9/devcontainer.json @@ -0,0 +1,57 @@ +{ + "name": "python-3.9", + "dockerComposeFile": [ + "./docker-compose.yml" + ], + "service": "python-3.9", + "forwardPorts": [], + "shutdownAction": "stopCompose", + "workspaceFolder": "/workspaces/weatherman", + "remoteEnv": {}, + "features": { + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "installOhMyZsh": true, + "configureZshAsDefaultShell": true, + "username": "vscode", + "userUid": "1000", + "userGid": "1000" + }, + "ghcr.io/devcontainers/features/node:1": {}, + "ghcr.io/devcontainers/features/git:1": { + "version": "latest", + "ppa": true + }, + "ghcr.io/devcontainers/features/git-lfs:1": {}, + "ghcr.io/robbert229/devcontainer-features/postgresql-client:1": {} + }, + "updateContentCommand": "bash .devcontainer/setup.sh", + "postCreateCommand": [], + "customizations": { + "vscode": { + "settings": { + "python.linting.enabled": true, + "python.testing.pytestEnabled": true, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "always" + }, + "[python]": { + "editor.defaultFormatter": "ms-python.vscode-pylance" + }, + "editor.rulers": [ + 80 + ] + }, + "extensions": [ + "ms-python.python", + "ms-toolsai.jupyter", + "ms-toolsai.vscode-jupyter-cell-tags", + "ms-toolsai.jupyter-keymap", + "ms-toolsai.jupyter-renderers", + "ms-toolsai.vscode-jupyter-slideshow", + "ms-python.vscode-pylance" + ] + } + } +} diff --git a/.devcontainer/python-3.9/docker-compose.yml b/.devcontainer/python-3.9/docker-compose.yml new file mode 100644 index 0000000..74a54e8 --- /dev/null +++ b/.devcontainer/python-3.9/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +services: + python-3.9: # nosemgrep + image: mcr.microsoft.com/devcontainers/python:3.9 + container_name: $USER-python-3.9-weatherman + volumes: + - ../../:/workspaces/weatherman:cached + command: sleep infinity + env_file: + - ../devcontainer.env + platform: linux/amd64 + networks: + - weatherman-network + +networks: + weatherman-network: + name: "${USER}-weatherman-network" diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh new file mode 100644 index 0000000..f4f165e --- /dev/null +++ b/.devcontainer/setup.sh @@ -0,0 +1,8 @@ +# update pip +pip install --upgrade pip + +# install dev packages +pip install -e ".[dev]" + +# install pre-commit hook if not installed already +pre-commit install diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9e5161e --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +__pycache__ +dist +.idea +venv* +.venv* +.env +.env* +*.lock +.vscode +.pypirc +.pytest_cache +.ruff_cache +.mypy_cache +.coverage* +.cache +htmlcov +token +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..1f1329f --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,49 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + exclude: | + (?x)^( + docs/docs/SUMMARY.md| + docs/docs/en/api/.meta.yml + )$ + - id: check-yaml + exclude: "docs/mkdocs.yml" + - id: check-added-large-files + exclude: | + (?x)^( + blog/package-lock.json + )$ + + - repo: local + hooks: + - id: lint + name: Linter + entry: "scripts/lint-pre-commit.sh" + language: python + # language_version: python3.9 + types: [python] + require_serial: true + verbose: true + + - repo: local + hooks: + - id: static-analysis + name: Static analysis + entry: "scripts/static-pre-commit.sh" + language: python + # language_version: python3.9 + types: [python] + require_serial: true + verbose: true + + - repo: https://github.com/Yelp/detect-secrets + rev: v1.5.0 + hooks: + - id: detect-secrets + args: ["--baseline", ".secrets.baseline"] + exclude: package.lock.json diff --git a/.secrets.baseline b/.secrets.baseline new file mode 100644 index 0000000..517c3d4 --- /dev/null +++ b/.secrets.baseline @@ -0,0 +1,127 @@ +{ + "version": "1.5.0", + "plugins_used": [ + { + "name": "ArtifactoryDetector" + }, + { + "name": "AWSKeyDetector" + }, + { + "name": "AzureStorageKeyDetector" + }, + { + "name": "Base64HighEntropyString", + "limit": 4.5 + }, + { + "name": "BasicAuthDetector" + }, + { + "name": "CloudantDetector" + }, + { + "name": "DiscordBotTokenDetector" + }, + { + "name": "GitHubTokenDetector" + }, + { + "name": "GitLabTokenDetector" + }, + { + "name": "HexHighEntropyString", + "limit": 3.0 + }, + { + "name": "IbmCloudIamDetector" + }, + { + "name": "IbmCosHmacDetector" + }, + { + "name": "IPPublicDetector" + }, + { + "name": "JwtTokenDetector" + }, + { + "name": "KeywordDetector", + "keyword_exclude": "" + }, + { + "name": "MailchimpDetector" + }, + { + "name": "NpmDetector" + }, + { + "name": "OpenAIDetector" + }, + { + "name": "PrivateKeyDetector" + }, + { + "name": "PypiTokenDetector" + }, + { + "name": "SendGridDetector" + }, + { + "name": "SlackDetector" + }, + { + "name": "SoftlayerDetector" + }, + { + "name": "SquareOAuthDetector" + }, + { + "name": "StripeDetector" + }, + { + "name": "TelegramBotTokenDetector" + }, + { + "name": "TwilioKeyDetector" + } + ], + "filters_used": [ + { + "path": "detect_secrets.filters.allowlist.is_line_allowlisted" + }, + { + "path": "detect_secrets.filters.common.is_ignored_due_to_verification_policies", + "min_level": 2 + }, + { + "path": "detect_secrets.filters.heuristic.is_indirect_reference" + }, + { + "path": "detect_secrets.filters.heuristic.is_likely_id_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_lock_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_not_alphanumeric_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_potential_uuid" + }, + { + "path": "detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign" + }, + { + "path": "detect_secrets.filters.heuristic.is_sequential_string" + }, + { + "path": "detect_secrets.filters.heuristic.is_swagger_file" + }, + { + "path": "detect_secrets.filters.heuristic.is_templated_secret" + } + ], + "results": {}, + "generated_at": "2024-06-11T08:06:05Z" +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..35445a7 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..8889088 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,74 @@ +> **_NOTE:_** This is an auto-generated file. Please edit docs/docs/en/getting-started/contributing/CONTRIBUTING.md instead. + +# Development + +After cloning the project, you'll need to set up the development environment. Here are the guidelines on how to do this. + +## Virtual Environment with `venv` + +Create a virtual environment in a directory using Python's `venv` module: + +```bash +python -m venv venv +``` + +That will create a `./venv/` directory with Python binaries, allowing you to install packages in an isolated environment. + +## Activate the Environment + +Activate the new environment with: + +```bash +source ./venv/bin/activate +``` + +Ensure you have the latest pip version in your virtual environment: + +```bash +python -m pip install --upgrade pip +``` + +## Installing Dependencies + +After activating the virtual environment as described above, run: + +```bash +pip install -e ".[dev]" +``` + +This will install all the dependencies and your local **WeatherMan** in your virtual environment. + +### Using Your local **WeatherMan** + +If you create a Python file that imports and uses **WeatherMan**, and run it with the Python from your local environment, it will use your local **WeatherMan** source code. + +Whenever you update your local **WeatherMan** source code, it will automatically use the latest version when you run your Python file again. This is because it is installed with `-e`. + +This way, you don't have to "install" your local version to be able to test every change. + +## Running Tests + +### Pytest + +To run tests with your current **WeatherMan** application and Python environment, use: + +```bash +pytest tests +# or +./scripts/test.sh +# with coverage output +./scripts/test-cov.sh +``` + +In your project, you'll find some *pytest marks*: + +* **slow** +* **all** + +By default, running *pytest* will execute "not slow" tests. + +To run all tests use: + +```bash +pytest -m 'all' +``` diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5fe64f4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2023 onwards] AIRT Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..b246179 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,33 @@ +# Security Policy + +Security and stability are paramount for WeatherMan. + +Learn more below. 👇 + +## Versions + +The latest version of WeatherMan is actively supported. + +We strongly encourage you to write tests for your application and regularly update your WeatherMan version after confirming that your tests pass. This ensures you benefit from the latest features, bug fixes, and **security updates**. + +## Reporting a Vulnerability + +If you suspect a security issue, even if you are uncertain, please report it promptly. However, **do not create a public issue**. + +To responsibly report a security concern, navigate to the Security tab of the repository and click on *"Report a vulnerability"*. + +![Screenshot of repo security tab showing "Report a vulnerability" button](https://github.com/encode/.github/raw/master/img/github-demos-private-vulnerability-reporting.png) + +Alternatively, you can send an email to: [info@airt.ai](info@airt.ai). + +Ensure your report contains sufficient detail. As with standard issue reports, a minimal, reproducible example expedites issue resolution. + +## Public Discussions + +Please restrain from publicly discussing potential security vulnerabilities. 🙊 + +It is advisable to engage in private discussions and seek solutions first to minimize potential impact. + +--- + +Thanks for your help! diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a5f7e49 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,253 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "weatherman" +description = "WeatherMan: an API to use with FastAgency" +readme = "README.md" +authors = [ + { name = "airt", email = "info@airt.ai" }, +] + +keywords = ["autogen", "multi-agent", "LLM", "AI", "autonomous agents"] + +requires-python = ">=3.9" + +classifiers = [ + "Development Status :: 2 - Pre-Alpha", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + "Topic :: Software Development :: Libraries :: Application Frameworks", + "Topic :: Software Development :: Libraries :: Python Modules", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development", + "Typing :: Typed", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: System Administrators", + "Environment :: Web Environment", + "Framework :: AsyncIO", + "Framework :: Pydantic", + "Framework :: Pydantic :: 2", +] + +dynamic = ["version"] + +dependencies = [ + "pydantic>=2.3,<3", + "fastapi>=0.110.2", + "python-weather==2.0.3", +] + +[project.optional-dependencies] +# public distributions + +server = [ + "uvicorn==0.30.1", +] + +# dev dependencies +lint = [ + "types-PyYAML", + "types-setuptools", + "types-ujson", + "types-Pygments", + "types-docutils", + "mypy==1.10.0", + "ruff==0.4.7", + "pyupgrade-directories==0.3.0", + "bandit==1.7.8", + "semgrep==1.71.0", + "pytest-mypy-plugins==3.1.2", +] + +test-core = [ + "coverage[toml]==7.5.3", + "pytest==8.2.1", + "pytest-asyncio==0.23.6", +] + +testing = [ + "weatherman[test-core]", + "weatherman[server]", # Uvicorn is needed for testing +] + +dev = [ + "weatherman[server,lint,testing]", + "pre-commit==3.7.1", + "detect-secrets==1.5.0", +] + +[project.urls] +Tracker = "https://github.com/airtai/weatherman/issues" +Source = "https://github.com/airtai/weatherman" +Discord = "https://discord.gg/qFm6aSqq59" + +[project.scripts] +# weatherman = "weatherman.__main__:cli" + +[tool.hatch.version] +path = "weatherman/__about__.py" + +[tool.hatch.build] +skip-excluded-dirs = true +exclude = [ + "/tests", + "/docs", +] + +[tool.hatch.metadata] +allow-direct-references = true + +[tool.hatch.build.targets.wheel] +only-include = ["weatherman"] + +[tool.hatch.build.targets.wheel.sources] +"src" = "" +# "scripts" = "weatherman/templates" + +[tool.mypy] + +files = ["weatherman", "tests"] + +strict = true +python_version = "3.9" +ignore_missing_imports = true +install_types = true +non_interactive = true +plugins = [ + "pydantic.mypy", +] + +# from https://blog.wolt.com/engineering/2021/09/30/professional-grade-mypy-configuration/ +disallow_untyped_defs = true +no_implicit_optional = true +check_untyped_defs = true +warn_return_any = true +show_error_codes = true +warn_unused_ignores = false + +disallow_incomplete_defs = true +disallow_untyped_decorators = true +disallow_any_unimported = false + +[tool.ruff] +fix = true +line-length = 88 +# target-version = 'py39' +include = ["weatherman/**/*.py", "weatherman/**/*.pyi", "tests/**/*.py", "pyproject.toml"] +exclude = ["docs/docs_src"] + +[tool.ruff.lint] +select = [ + "E", # pycodestyle errors https://docs.astral.sh/ruff/rules/#error-e + "W", # pycodestyle warnings https://docs.astral.sh/ruff/rules/#warning-w + "C90", # mccabe https://docs.astral.sh/ruff/rules/#mccabe-c90 + "N", # pep8-naming https://docs.astral.sh/ruff/rules/#pep8-naming-n + "D", # pydocstyle https://docs.astral.sh/ruff/rules/#pydocstyle-d + "I", # isort https://docs.astral.sh/ruff/rules/#isort-i + "F", # pyflakes https://docs.astral.sh/ruff/rules/#pyflakes-f + "ASYNC", # flake8-async https://docs.astral.sh/ruff/rules/#flake8-async-async + "C4", # flake8-comprehensions https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4 + "B", # flake8-bugbear https://docs.astral.sh/ruff/rules/#flake8-bugbear-b + "Q", # flake8-quotes https://docs.astral.sh/ruff/rules/#flake8-quotes-q + "T20", # flake8-print https://docs.astral.sh/ruff/rules/#flake8-print-t20 + "SIM", # flake8-simplify https://docs.astral.sh/ruff/rules/#flake8-simplify-sim + "PT", # flake8-pytest-style https://docs.astral.sh/ruff/rules/#flake8-pytest-style-pt + "PTH", # flake8-use-pathlib https://docs.astral.sh/ruff/rules/#flake8-use-pathlib-pth + "TCH", # flake8-type-checking https://docs.astral.sh/ruff/rules/#flake8-type-checking-tch + "RUF", # Ruff-specific rules https://docs.astral.sh/ruff/rules/#ruff-specific-rules-ruf + "PERF", # Perflint https://docs.astral.sh/ruff/rules/#perflint-perf +] + +ignore = [ + "E501", # line too long, handled by formatter later + "D100", "D101", "D102", "D103", "D104", +# "C901", # too complex +] + +[tool.ruff.lint.isort] +case-sensitive = true + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint.pydocstyle] +convention = "google" + +[tool.ruff.lint.flake8-bugbear] + +[tool.pytest.ini_options] +minversion = "7.0" +addopts = "-q -m 'not slow'" +testpaths = [ + "tests", +] +markers = [ + "slow", + "all", +] + +[tool.coverage.run] +parallel = true +branch = true +concurrency = [ + "multiprocessing", + "thread" +] +source = [ + "weatherman", +# "tests", +] +context = '${CONTEXT}' +omit = [ + "**/__init__.py", +] + +[tool.coverage.report] +show_missing = true +skip_empty = true +sort = "miss" + +exclude_also = [ + "if __name__ == .__main__.:", + "self.logger", + "def __repr__", + "lambda: None", + "from .*", + "import .*", + '@(abc\.)?abstractmethod', + "raise NotImplementedError", + 'raise AssertionError', + 'logger\..*', + "pass", + '\.\.\.', +] +omit = [ + '*/__about__.py', + '*/__main__.py', + '*/__init__.py', +] + +[tool.bandit] + +[tool.black] + +line-length = 88 + +extend-exclude = """ +/( + docs/docs_src + | some_other_dir +)/ +""" diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100755 index 0000000..b9be303 --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,64 @@ +#!/bin/bash + + +check_variable() { + if [[ -z "${!1}" ]]; then + echo "ERROR: $1 variable must be defined, exiting" + exit -1 + fi +} + +check_variable "TAG" +check_variable "GITHUB_USERNAME" +check_variable "GITHUB_PASSWORD" +check_variable "DOMAIN" +check_variable "DATABASE_URL" +check_variable "PY_DATABASE_URL" +check_variable "AZURE_API_VERSION" +check_variable "AZURE_API_ENDPOINT" +check_variable "AZURE_GPT35_MODEL" +check_variable "AZURE_OPENAI_API_KEY" +check_variable "TOGETHER_API_KEY" + + +if [ ! -f key.pem ]; then + echo "ERROR: key.pem file not found" + exit -1 +fi + + +ssh_command="ssh -o StrictHostKeyChecking=no -i key.pem azureuser@$DOMAIN" + +container_name="fastagency" +log_file="${container_name}.log" + +echo "INFO: Capturing docker container logs" +$ssh_command "docker logs $container_name >> $log_file 2>&1 || echo 'No container logs to capture'" + +# Check if log file size exceeds 1GB (1073741824 bytes) and trim if necessary +$ssh_command "if [ \$(stat -c%s \"$log_file\") -ge 1073741824 ]; then echo 'Log file size exceeds 1GB, trimming...'; tail -c 1073741824 \"$log_file\" > \"$log_file.tmp\" && mv \"$log_file.tmp\" \"$log_file\"; fi" + +echo "INFO: stopping already running docker containers" +$ssh_command "export PORT='$PORT' && docker compose down || echo 'No containers available to stop'" +$ssh_command "docker container prune -f || echo 'No stopped containers to delete'" + +echo "INFO: SCPing docker-compose.yaml" +scp -i key.pem ./docker-compose.yaml azureuser@$DOMAIN:/home/azureuser/docker-compose.yaml +scp -i key.pem -r ./etc azureuser@$DOMAIN:/home/azureuser + +echo "INFO: pulling docker image" +$ssh_command "echo $GITHUB_PASSWORD | docker login -u '$GITHUB_USERNAME' --password-stdin '$REGISTRY'" +$ssh_command "docker pull ghcr.io/$GITHUB_REPOSITORY:'$TAG'" +sleep 10 + +echo "Deleting old image" +$ssh_command "docker system prune -f || echo 'No images to delete'" + +echo "INFO: starting docker containers" + +$ssh_command "export GITHUB_REPOSITORY='$GITHUB_REPOSITORY' TAG='$TAG' container_name='$container_name' \ + DOMAIN='$DOMAIN' PY_DATABASE_URL='$PY_DATABASE_URL' DATABASE_URL='$DATABASE_URL' \ + AZURE_API_VERSION='$AZURE_API_VERSION' AZURE_API_ENDPOINT='$AZURE_API_ENDPOINT' \ + AZURE_GPT35_MODEL='$AZURE_GPT35_MODEL' AZURE_OPENAI_API_KEY='$AZURE_OPENAI_API_KEY' \ + TOGETHER_API_KEY='$TOGETHER_API_KEY' \ + && docker compose up -d" diff --git a/scripts/lint-pre-commit.sh b/scripts/lint-pre-commit.sh new file mode 100755 index 0000000..37747f3 --- /dev/null +++ b/scripts/lint-pre-commit.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +# from: https://jaredkhan.com/blog/mypy-pre-commit + +# A script for running mypy, +# with all its dependencies installed. + +set -o errexit + +# Change directory to the project root directory. +cd "$(dirname "$0")"/.. + +# Install the dependencies into the mypy env. +# Note that this can take seconds to run. +# In my case, I need to use a custom index URL. +# Avoid pip spending time quietly retrying since +# likely cause of failure is lack of VPN connection. +pip install --editable ".[dev]" \ + --retries 1 \ + --no-input \ + --quiet + +# Run on all files, +# ignoring the paths passed to this script, +# so as not to miss type errors. +# My repo makes use of namespace packages. +# Use the namespace-packages flag +# and specify the package to run on explicitly. +# Note that we do not use --ignore-missing-imports, +# as this can give us false confidence in our results. +# mypy fastagency +./scripts/lint.sh diff --git a/scripts/lint.sh b/scripts/lint.sh new file mode 100755 index 0000000..77f15cb --- /dev/null +++ b/scripts/lint.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +echo "Running pyup_dirs..." +pyup_dirs --py38-plus --recursive fastagency examples tests docs + +echo "Running ruff linter (isort, flake, pyupgrade, etc. replacement)..." +ruff check + +echo "Running ruff formater (black replacement)..." +ruff format + +# echo "Running black..." +# black fastagency examples tests docs diff --git a/scripts/publish.sh b/scripts/publish.sh new file mode 100755 index 0000000..d1faba9 --- /dev/null +++ b/scripts/publish.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +hatch clean +hatch build +hatch publish diff --git a/scripts/run_server.sh b/scripts/run_server.sh new file mode 100755 index 0000000..b8ae53a --- /dev/null +++ b/scripts/run_server.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +uvicorn weatherman.app:app --workers 2 --host 0.0.0.0 --proxy-headers diff --git a/scripts/static-analysis.sh b/scripts/static-analysis.sh new file mode 100755 index 0000000..4d092e5 --- /dev/null +++ b/scripts/static-analysis.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -e + +echo "Running mypy..." +# mkdir -p . +mypy + +echo "Running bandit..." +bandit -c pyproject.toml -r fastagency + +echo "Running semgrep..." +semgrep scan --config auto --error diff --git a/scripts/static-pre-commit.sh b/scripts/static-pre-commit.sh new file mode 100755 index 0000000..f6956f1 --- /dev/null +++ b/scripts/static-pre-commit.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +# taken from: https://jaredkhan.com/blog/mypy-pre-commit + +# A script for running mypy, +# with all its dependencies installed. + +set -o errexit + +# Change directory to the project root directory. +cd "$(dirname "$0")"/.. + +# Install the dependencies into the mypy env. +# Note that this can take seconds to run. +# In my case, I need to use a custom index URL. +# Avoid pip spending time quietly retrying since +# likely cause of failure is lack of VPN connection. +pip install --editable ".[dev]" \ + --retries 1 \ + --no-input \ + --quiet + +# Run on all files, +# ignoring the paths passed to this script, +# so as not to miss type errors. +# My repo makes use of namespace packages. +# Use the namespace-packages flag +# and specify the package to run on explicitly. +# Note that we do not use --ignore-missing-imports, +# as this can give us false confidence in our results. +# mypy fastagency +./scripts/static-analysis.sh diff --git a/scripts/test-cov.sh b/scripts/test-cov.sh new file mode 100755 index 0000000..9ff60a5 --- /dev/null +++ b/scripts/test-cov.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash + +bash scripts/test.sh "$@" + +coverage combine +coverage report + + +rm .coverage* diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..69cfd4d --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash + +# coverage run -m pytest -x --ff "$@" || \ +# coverage run -m pytest -x --ff "$@" || \ +coverage run -m pytest -x --ff "$@" diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..f8ea757 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the project.""" diff --git a/tests/app/test_app.py b/tests/app/test_app.py new file mode 100644 index 0000000..2b7dc26 --- /dev/null +++ b/tests/app/test_app.py @@ -0,0 +1,32 @@ +import datetime + +from fastapi.testclient import TestClient + +from weatherman.app import app + +client = TestClient(app) + + +def test_weather_route() -> None: + response = client.get("/?city=Chennai") + assert response.status_code == 200 + resp_json = response.json() + assert resp_json.get("city") == "Chennai" + assert resp_json.get("temperature") > 0 + + assert len(resp_json.get("daily_forecasts")) > 0 + daily_forecasts = resp_json.get("daily_forecasts") + assert isinstance(daily_forecasts, list) + + first_daily_forecast = daily_forecasts[0] + assert ( + first_daily_forecast.get("forecast_date") == datetime.date.today().isoformat() + ) + assert first_daily_forecast.get("temperature") > 0 + assert len(first_daily_forecast.get("hourly_forecasts")) > 0 + + first_hourly_forecast = first_daily_forecast.get("hourly_forecasts")[0] + assert isinstance(first_hourly_forecast, dict) + assert first_hourly_forecast.get("forecast_time") is not None + assert first_hourly_forecast.get("temperature") > 0 # type: ignore + assert first_hourly_forecast.get("description") is not None diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..e69de29 diff --git a/weatherman/__about__.py b/weatherman/__about__.py new file mode 100644 index 0000000..be2181d --- /dev/null +++ b/weatherman/__about__.py @@ -0,0 +1,3 @@ +"""An API to use with FastAgency.""" + +__version__ = "0.0.0dev0" diff --git a/weatherman/__init__.py b/weatherman/__init__.py new file mode 100644 index 0000000..4d69251 --- /dev/null +++ b/weatherman/__init__.py @@ -0,0 +1,3 @@ +"""An API to use with FastAgency.""" + +from .__about__ import __version__ # noqa: F401 diff --git a/weatherman/app.py b/weatherman/app.py new file mode 100644 index 0000000..e0b7bec --- /dev/null +++ b/weatherman/app.py @@ -0,0 +1,72 @@ +import datetime +import logging +from os import environ +from typing import List + +import python_weather +from fastapi import FastAPI +from pydantic import BaseModel + +logging.basicConfig(level=logging.INFO) + +host = environ.get("DOMAIN", "localhost") +port = 9000 +protocol = "http" if host == "localhost" else "https" + +app = FastAPI( + servers=[ + {"url": f"{protocol}://{host}:{port}", "description": "Weather app server"} + ] +) + + +class HourlyForecast(BaseModel): + forecast_time: datetime.time + temperature: int + description: str + + +class DailyForecast(BaseModel): + forecast_date: datetime.date + temperature: int + hourly_forecasts: List[HourlyForecast] + + +class Weather(BaseModel): + city: str + temperature: int + daily_forecasts: List[DailyForecast] + + +@app.get("/") +async def get_weather(city: str) -> Weather: + async with python_weather.Client(unit=python_weather.METRIC) as client: + # fetch a weather forecast from a city + weather = await client.get(city) + + daily_forecasts = [] + # get the weather forecast for a few days + for daily in weather.daily_forecasts: + hourly_forecasts = [ + HourlyForecast( + forecast_time=hourly.time, + temperature=hourly.temperature, + description=hourly.description, + ) + for hourly in daily.hourly_forecasts + ] + daily_forecasts.append( + DailyForecast( + forecast_date=daily.date, + temperature=daily.temperature, + hourly_forecasts=hourly_forecasts, + ) + ) + + weather_response = Weather( + city=city, + temperature=weather.temperature, + daily_forecasts=daily_forecasts, + hourly_forecasts=hourly_forecasts, + ) + return weather_response