From d64fe31e1feb3317ee4243e8b58df4b16b2b1f08 Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 17:29:02 -0700 Subject: [PATCH 1/8] Add python-dotenv --- requirements.txt | 1 + src/spokanetech/settings.py | 3 +++ 2 files changed, 4 insertions(+) diff --git a/requirements.txt b/requirements.txt index 25d97e9f..85ef0809 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,4 +9,5 @@ django-storages[azure]==1.14.2 Django==5.0.1 gunicorn==21.2.0 psycopg[binary]==3.1.17 +python-dotenv==1.0.1 sqlparse==0.4.4 diff --git a/src/spokanetech/settings.py b/src/spokanetech/settings.py index c15dd517..ff11f834 100644 --- a/src/spokanetech/settings.py +++ b/src/spokanetech/settings.py @@ -14,6 +14,9 @@ from pathlib import Path import dj_database_url +from dotenv import load_dotenv + +load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent From cebebf18fd8cb5f4521c908b72bd0cca01338ae7 Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 17:34:37 -0700 Subject: [PATCH 2/8] Update CONTRIBUTING.md and .env.template --- .env.template | 5 ++++- .github/CONTRIBUTING.md | 6 ++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/.env.template b/.env.template index 1f1a59db..647136d6 100644 --- a/.env.template +++ b/.env.template @@ -5,7 +5,10 @@ DJANGO_SECRET_KEY= # Change if you don't want to use the default sqlite database DATABASE_URL= -# Set to true and populate AZURE_* values to use Azure storage for static and media files +# Set USE_AZURE=true and populate AZURE values to use Azure storage for static and media files USE_AZURE=false AZURE_ACCOUNT_NAME= AZURE_ACCOUNT_KEY= + +CELERY_BROKER_URL= +DISCORD_WEBHOOK_URL= diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 6273c9a6..e4dcdfcf 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -62,6 +62,12 @@ cd SpokaneTech_Py python -m venv venv source venv/bin/activate pip install -r requirements.txt -r requirements/dev.txt +``` + + `python-dotenv` will automatically load values in the `.env` file when Django's `manage.py` is used. Create a `.env` file from the template (**note: `.env` should never be checked in to source control!**): + +```shell +cp .env.template .env ``` Run Django migrations: From 1616f88112a7bd2e41ed8ff727cc626a546ce888 Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 18:43:13 -0700 Subject: [PATCH 3/8] Add settings.CELERY_ENABLED --- src/spokanetech/celery.py | 26 ++++++++++++-------------- src/spokanetech/settings.py | 12 ++++++++++-- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/spokanetech/celery.py b/src/spokanetech/celery.py index e625b69f..47875eca 100644 --- a/src/spokanetech/celery.py +++ b/src/spokanetech/celery.py @@ -3,20 +3,18 @@ from celery import Celery from celery.schedules import crontab -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spokanetech.settings") - -app = Celery("core") -app.config_from_object("django.conf:settings", namespace="CELERY") -app.autodiscover_tasks() +from django.conf import settings -app.conf.beat_schedule = { - "Send Events to Discord": { - "task": "web.tasks.send_events_to_discord", - "schedule": crontab(day_of_week="mon"), - }, -} +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "spokanetech.settings") +if settings.CELERY_ENABLED: + app = Celery("core") + app.config_from_object("django.conf:settings", namespace="CELERY") + app.autodiscover_tasks() -@app.task(bind=True, ignore_result=True) -def debug_task(self): - print(f"Request: {self.request!r}") + app.conf.beat_schedule = { + "Send Events to Discord": { + "task": "web.tasks.send_events_to_discord", + "schedule": crontab(day_of_week="mon"), + }, + } diff --git a/src/spokanetech/settings.py b/src/spokanetech/settings.py index ff11f834..b94aabfc 100644 --- a/src/spokanetech/settings.py +++ b/src/spokanetech/settings.py @@ -106,7 +106,7 @@ DATABASES = { "default": dj_database_url.config( - default=f"sqlite:////{BASE_DIR}/db.sqlite3", + default="sqlite:///db.sqlite3", conn_max_age=600, conn_health_checks=True, ), @@ -188,7 +188,15 @@ # Celery -CELERY_BROKER_URL = os.environ["CELERY_BROKER_URL"] +try: + CELERY_BROKER_URL = os.environ["CELERY_BROKER_URL"] + CELERY_ENABLED = True +except KeyError: + if IS_DEVELOPMENT: + CELERY_ENABLED = False + else: + raise + CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", "django-db") CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" From 90b1abaad4b6b3f314670bbab55fbf2f55147a89 Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 18:43:23 -0700 Subject: [PATCH 4/8] Add DATABASE_URL value to .env.template --- .env.template | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.env.template b/.env.template index 647136d6..0afd303c 100644 --- a/.env.template +++ b/.env.template @@ -3,7 +3,7 @@ SPOKANE_TECH_DEV=true DJANGO_SECRET_KEY= # Change if you don't want to use the default sqlite database -DATABASE_URL= +DATABASE_URL="sqlite:///db.sqlite3" # Set USE_AZURE=true and populate AZURE values to use Azure storage for static and media files USE_AZURE=false From 25cc86dc1e8d20c6dda086b497bd6499472a00ec Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 18:54:49 -0700 Subject: [PATCH 5/8] Remove extraneous space in CONTRIBUTING.md --- .envrc | 1 + .github/CONTRIBUTING.md | 2 +- .vscode/settings.json | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 .envrc create mode 100644 .vscode/settings.json diff --git a/.envrc b/.envrc new file mode 100644 index 00000000..fe7c01aa --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +dotenv diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e4dcdfcf..4d967c4c 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -64,7 +64,7 @@ source venv/bin/activate pip install -r requirements.txt -r requirements/dev.txt ``` - `python-dotenv` will automatically load values in the `.env` file when Django's `manage.py` is used. Create a `.env` file from the template (**note: `.env` should never be checked in to source control!**): +`python-dotenv` will automatically load values in the `.env` file when Django's `manage.py` is used. Create a `.env` file from the template (**note: `.env` should never be checked in to source control!**): ```shell cp .env.template .env diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..4219879a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,9 @@ +{ + "python.testing.pytestArgs": [ + "--reuse-db", + "-vv", + "src" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true +} From 2c934df3e9380478e08a614768125adc401a1c1a Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 19:44:40 -0700 Subject: [PATCH 6/8] Add docs link to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7a87ba51..fcb19c27 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ # Spokane Tech Home of [SpokaneTech.org](https://SpokaneTech.org), an online hub for Spokane's tech events and groups. It's not just a website; it's a community-driven, open-source initiative aimed at fostering learning and collaboration among aspiring and seasoned tech enthusiasts. + +Please visit our [docs](https://spokanetech.github.io/SpokaneTech_Py/) to learn how to get started working on SpokaneTech_Py! From faf9158f848d66275707cd48cca0338fe2cc832a Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 20:04:46 -0700 Subject: [PATCH 7/8] Revamp CONTRIBUTING.md --- .github/CONTRIBUTING.md | 104 ---------------------------- docs/CONTRIBUTING.md | 150 +++++++++++++++++++++++++++++++++++++++- mkdocs.yml | 3 + 3 files changed, 151 insertions(+), 106 deletions(-) delete mode 100644 .github/CONTRIBUTING.md diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index 4d967c4c..00000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,104 +0,0 @@ -# Contributing to SpokaneTech_Py - ---8<-- [start:intro] -First off, thank you for considering contributing to SpokaneTech_Py! - -The following is a set of guidelines for contributing to this project. These are just guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. ---8<-- [start:end] - -## Table of Contents - -- [Table of Contents](#table-of-contents) -- [Code of Conduct](#code-of-conduct) -- [How Can I Contribute?](#how-can-i-contribute) - - [Reporting Bugs](#reporting-bugs) - - [Suggesting Enhancements](#suggesting-enhancements) - - [Pull Requests](#pull-requests) -- [Development](#development) -- [Style Guide](#style-guide) -- [License](#license) - ---8<-- [start:mkdocs] -## Code of Conduct - -This project and everyone participating in it are governed by the [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [maintainer email]. - -## How Can I Contribute? - -### Reporting Bugs - -- Before creating bug reports, please check the [existing issues](https://github.com/SpokaneTech/SpokaneTech_Py/issues) as you might find that the issue has already been reported. -- When creating a bug report, please include a clear and concise description of the problem and steps to reproduce it. - -### Suggesting Enhancements - -- Before creating enhancement suggestions, please check the [list of open issues](https://github.com/SpokaneTech/SpokaneTech_Py/issues) as you might find that the suggestion has already been made. -- When creating an enhancement suggestion, please provide a detailed description and, if possible, an implementation proposal. - -### Pull Requests - -- Provide a clear and concise description of your pull request. -- Ensure you have tested your changes thoroughly. -- Add/update unittests as necessary. -- Make sure code quality tools run successfully. - - Merging contributions requires passing the checks configured with the CI. This includes running tests, linters, and other code quality tools successfully on the currently officially supported Python and Django versions. - -## Development - -You can contribute to this project by forking it from GitHub and sending pull requests. - -First [fork](https://help.github.com/en/articles/fork-a-repo) the -[repository](https://github.com/SpokaneTech/SpokaneTech_Py) and then clone it: - -```shell -git clone git@github.com:/SpokaneTech_Py.git -``` - -Create a virtual environment and install dependencies: - -```shell -cd SpokaneTech_Py -python -m venv venv -source venv/bin/activate -pip install -r requirements.txt -r requirements/dev.txt -``` - -`python-dotenv` will automatically load values in the `.env` file when Django's `manage.py` is used. Create a `.env` file from the template (**note: `.env` should never be checked in to source control!**): - -```shell -cp .env.template .env -``` - -Run Django migrations: -```shell -cd src -python manage.py migrate -``` - -Create a Django superuser: -```shell -cd src -python manage.py createsuperuser -``` - -Run the Django development web server locally: -```shell -cd src -python manage.py runserver -``` - -Unit tests are located in each Django app under the tests directory and can be executed via pytest: -```shell -pytest -``` - - -## Style Guide - -Follow the coding style outlined in the [style guide](STYLE_GUIDE.md). - -## License - -By contributing, you agree that your contributions will be licensed under the [GNU-3 license](LICENSE.md). ---8<-- [start:end] diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index a69f198b..0a74b34d 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -1,3 +1,149 @@ # Contributing ---8<-- ".github/CONTRIBUTING.md:intro" ---8<-- ".github/CONTRIBUTING.md:mkdocs" + +First off, thank you for considering contributing to SpokaneTech_Py! + +The following is a set of guidelines for contributing to this project. These are just guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. + +## Code of Conduct + +This project and everyone participating in it are governed by the [Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [organizers@spokanetech.org](mailto:organizers@spokanetech.org). + +## How Can I Contribute? + +### Reporting Bugs + +- Before creating bug reports, please check the [existing issues](https://github.com/SpokaneTech/SpokaneTech_Py/issues) as you might find that the issue has already been reported. +- When creating a bug report, please include a clear and concise description of the problem and steps to reproduce it. + +### Suggesting Enhancements + +- Before creating enhancement suggestions, please check the [list of open issues](https://github.com/SpokaneTech/SpokaneTech_Py/issues) as you might find that the suggestion has already been made. +- When creating an enhancement suggestion, please provide a detailed description and, if possible, an implementation proposal. + +### Pull Requests + +- Provide a clear and concise description of your pull request. +- Ensure you have tested your changes thoroughly. +- Add/update unittests as necessary. +- Make sure code quality tools run successfully. +- Merging contributions requires passing the checks configured with the CI. This includes running tests, linters, and other code quality tools successfully on the currently officially supported Python and Django versions. + +## Development + +You can contribute to this project by forking it from GitHub and sending pull requests. + +First [fork](https://help.github.com/en/articles/fork-a-repo) the +[repository](https://github.com/SpokaneTech/SpokaneTech_Py) and then clone it: + +```shell +git clone git@github.com:/SpokaneTech_Py.git +``` + +Create a virtual environment and install dependencies: + +```shell +cd SpokaneTech_Py +python -m venv venv +source venv/bin/activate +pip install -r requirements.txt -r requirements/dev.txt +``` + +`python-dotenv` will automatically load values in the `.env` file when Django's `manage.py` is used. Create a `.env` file from the template (**note: `.env` should never be checked in to source control!**): + +```shell +cp .env.template .env +``` + +Run Django migrations: +```shell +cd src +python manage.py migrate +``` + +Create a Django superuser: +```shell +cd src +python manage.py createsuperuser +``` + +Run the Django development web server locally: +```shell +cd src +python manage.py runserver +``` + +Unit tests are located in each Django app under the tests directory and can be executed via pytest: + +```shell +pytest +``` + +
+Full walkthrough + +Generated using script. The highlighted lines are commands that should be ran in your terminal. Some output is truncated for brevity and is designated by "...". + +```bash linenums="1" hl_lines="1 2 3 15 16 17 30 36" +$ python -m venv venv +$ source venv/bin/activate +(venv) $ pip install -r requirements.txt -r requirements/dev.txt +Collecting asgiref==3.7.2 + Using cached asgiref-3.7.2-py3-none-any.whl (24 kB) +Collecting celery[redis]==5.3.6 + Using cached celery-5.3.6-py3-none-any.whl (422 kB) +Collecting discord.py==2.3.2 + Using cached discord.py-2.3.2-py3-none-any.whl (1.1 MB) +... +Installing collected packages: xlwt, webencodings, wcwidth, pytz, paginate, drf-dynamic-fields, cron-descriptor, watchdog, vine, urllib3, tzdata, typing-extensions, tomli, tinycss2, sqlparse, six, regex, redis, pyyaml, python-dotenv, pygments, pycparser, psycopg-binary, prompt-toolkit, pluggy, platformdirs, pillow, pathspec, packaging, multidict, mkdocs-material-extensions, mergedeep, MarkupSafe, markdown, iniconfig, idna, hurry.filesize, frozenlist, exceptiongroup, defusedxml, colorama, click, charset-normalizer, certifi, billiard, babel, attrs, async-timeout, yarl, requests, pyyaml-env-tag, python-dateutil, pytest, pymdown-extensions, psycopg, Jinja2, isodate, gunicorn, cssselect2, click-repl, click-plugins, click-didyoumean, cffi, asgiref, amqp, aiosignal, python-crontab, pytest-django, kombu, ghp-import, freezegun, Django, cryptography, cairocffi, azure-core, aiohttp, model-bakery, mkdocs, djangorestframework, django-timezone-field, django-storages, django-filter, dj-database-url, discord.py, celery, cairosvg, azure-storage-blob, mkdocs-material, djangorestframework-filters, django-celery-results, django-celery-beat, django-handyhelpers +Successfully installed Django-5.0.1 Jinja2-3.1.3 MarkupSafe-2.1.5 aiohttp-3.9.3 aiosignal-1.3.1 amqp-5.2.0 asgiref-3.7.2 async-timeout-4.0.3 attrs-23.2.0 azure-core-1.30.1 azure-storage-blob-12.19.1 babel-2.14.0 billiard-4.2.0 cairocffi-1.6.1 cairosvg-2.7.1 celery-5.3.6 certifi-2024.2.2 cffi-1.16.0 charset-normalizer-3.3.2 click-8.1.7 click-didyoumean-0.3.0 click-plugins-1.1.1 click-repl-0.3.0 colorama-0.4.6 cron-descriptor-1.4.3 cryptography-42.0.5 cssselect2-0.7.0 defusedxml-0.7.1 discord.py-2.3.2 dj-database-url-2.1.0 django-celery-beat-2.6.0 django-celery-results-2.5.1 django-filter-24.1 django-handyhelpers-0.3.20 django-storages-1.14.2 django-timezone-field-6.1.0 djangorestframework-3.15.0 djangorestframework-filters-1.0.0.dev0 drf-dynamic-fields-0.4.0 exceptiongroup-1.2.0 freezegun-1.4.0 frozenlist-1.4.1 ghp-import-2.1.0 gunicorn-21.2.0 hurry.filesize-0.9 idna-3.6 iniconfig-2.0.0 isodate-0.6.1 kombu-5.3.5 markdown-3.6 mergedeep-1.3.4 mkdocs-1.5.3 mkdocs-material-9.5.10 mkdocs-material-extensions-1.3.1 model-bakery-1.17.0 multidict-6.0.5 packaging-24.0 paginate-0.5.6 pathspec-0.12.1 pillow-10.2.0 platformdirs-4.2.0 pluggy-1.4.0 prompt-toolkit-3.0.43 psycopg-3.1.17 psycopg-binary-3.1.17 pycparser-2.21 pygments-2.17.2 pymdown-extensions-10.7.1 pytest-8.0.0 pytest-django-4.8.0 python-crontab-3.0.0 python-dateutil-2.9.0.post0 python-dotenv-1.0.1 pytz-2024.1 pyyaml-6.0.1 pyyaml-env-tag-0.1 redis-5.0.3 regex-2023.12.25 requests-2.31.0 six-1.16.0 sqlparse-0.4.4 tinycss2-1.2.1 tomli-2.0.1 typing-extensions-4.10.0 tzdata-2024.1 urllib3-2.2.1 vine-5.1.0 watchdog-4.0.0 wcwidth-0.2.13 webencodings-0.5.1 xlwt-1.3.0 yarl-1.9.4 +WARNING: You are using pip version 22.0.4; however, version 24.0 is available. +You should consider upgrading via the '/Users/user/code/SpokaneTech_Py/venv/bin/python -m pip install --upgrade pip' command. +(venv) $ cp .env.template .env +(venv) $ cd src +(venv) $ src python manage.py migrate +Operations to perform: + Apply all migrations: admin, auth, contenttypes, django_celery_beat, django_celery_results, sessions, web +Running migrations: + Applying contenttypes.0001_initial... OK + Applying auth.0001_initial... OK + Applying admin.0001_initial... OK + Applying admin.0002_logentry_remove_auto_add... OK +... + Applying web.0001_initial... OK + Applying web.0002_techgroup_event_group... OK + Applying web.0003_event_created_at_event_updated_at_and_more... OK + Applying web.0004_event_url... OK +(venv) $ src python manage.py createsuperuser +Username (leave blank to use 'user'): admin +Email address: +Password: +Password (again): +Superuser created successfully. +(venv) $ src python manage.py runserver +Watching for file changes with StatReloader +Performing system checks... +System check identified no issues (0 silenced). +March 22, 2024 - 01:52:19 +Django version 5.0.1, using settings 'spokanetech.settings' +Starting development server at http://127.0.0.1:8000/ +Quit the server with CONTROL-C. +^C +``` + +
+ +## Docs + +When updating the docs locally, use the following command to run the `mkdocs` server: + +```shell +mkdocs serve -w .github -w docs +``` + +## Style Guide + +Follow the coding style outlined in the [style guide](STYLE_GUIDE.md). + +## License + +By contributing, you agree that your contributions will be licensed under the [GNU-3 license](LICENSE.md). diff --git a/mkdocs.yml b/mkdocs.yml index f44dbb36..989e0ef1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -20,6 +20,7 @@ theme: name: Switch to light mode features: - content.code.annotate + - content.code.copy - navigation.indexes - navigation.instant - navigation.top @@ -35,6 +36,8 @@ markdown_extensions: - pymdownx.inlinehilite - pymdownx.snippets - pymdownx.superfences + - toc: + toc_depth: 2 nav: - Home: index.md From 19edfedeea8d7f75bc16fd736467bd4714375fbc Mon Sep 17 00:00:00 2001 From: Joseph Riddle Date: Thu, 21 Mar 2024 20:07:08 -0700 Subject: [PATCH 8/8] Clean up docs in .github --- .github/CODE_OF_CONDUCT.md | 48 ------ .github/STYLE_GUIDE.md | 298 ------------------------------------- docs/CODE_OF_CONDUCT.md | 49 +++++- docs/STYLE_GUIDE.md | 285 ++++++++++++++++++++++++++++++++++- 4 files changed, 331 insertions(+), 349 deletions(-) delete mode 100644 .github/CODE_OF_CONDUCT.md delete mode 100644 .github/STYLE_GUIDE.md diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md deleted file mode 100644 index 72fc3637..00000000 --- a/.github/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,48 +0,0 @@ -# Contributor Code of Conduct - -As contributors and maintainers of this project, and in the interest of -fostering an open and welcoming community, we pledge to respect all people who -contribute through reporting issues, posting feature requests, updating -documentation, submitting pull requests or patches, and other activities. - -We are committed to making participation in this project a harassment-free -experience for everyone, regardless of level of experience, gender, gender -identity and expression, sexual orientation, disability, personal appearance, -body size, race, ethnicity, age, religion, or nationality. - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery -* Personal attacks -* Trolling or insulting/derogatory comments -* Public or private harassment -* Publishing other's private information, such as physical or electronic - addresses, without explicit permission -* Other unethical or unprofessional conduct - -Project maintainers 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, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -By adopting this Code of Conduct, project maintainers commit themselves to -fairly and consistently applying these principles to every aspect of managing -this project. Project maintainers who do not follow or enforce the Code of -Conduct may be permanently removed from the project team. - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting a project maintainer at https://spokanepython.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. Maintainers are -obligated to maintain confidentiality with regard to the reporter of an -incident. - - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 1.3.0, available at [https://www.contributor-covenant.org/version/1/3/0/code-of-conduct.html](https://www.contributor-covenant.org/version/1/3/0/code-of-conduct.html). - -[homepage]: https://www.contributor-covenant.org diff --git a/.github/STYLE_GUIDE.md b/.github/STYLE_GUIDE.md deleted file mode 100644 index 02d9b7a1..00000000 --- a/.github/STYLE_GUIDE.md +++ /dev/null @@ -1,298 +0,0 @@ -# Project Style Guide - ---8<-- [start:intro] -This Python style guide provides conventions and best practices for writing clean and maintainable Python code. Adhering to these guidelines will help ensure consistency across projects and enhance the clarity, maintainability, -and readability of the code. ---8<-- [end:intro] - -## Table of Contents -- [PEP 8](#pep-8) -- [Line Length](#line-length) -- [Naming Conventions](#naming-conventions) -- [Docstrings](#docstrings) -- [Typing](#typing) -- [Virtual Environments](#virtual-environments) - ---8<-- [start:mkdocs] -## PEP 8 - -Adhere to the PEP 8 style guide, which is the style guide for Python code. Please make sure to familiarize yourself with PEP 8 guidelines: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). - -## Line Length - -The maximum line length for code and comments is set to 120 characters. This allows for better readability without excessively long lines. - -## Naming Conventions - -### Classes -- Class names should follow the CamelCase convention. -- Class names should be descriptive and represent a clear concept or object. - -```python linenums="1" hl_lines="1" -class Calculator: - def __init__(self): - # Constructor implementation - - def add(self, x, y): - # Method implementation -``` - -### Functions -- Function names should be lowercase, with words separated by underscores. -- Function names should begin with a verb to indicate the action or operation they perform. - -```python linenums="1" hl_lines="1 5 9" -def calculate_sum(numbers): - """Calculate the sum of a list of numbers.""" - # Function implementation - -def validate_input(user_input): - """Validate user input and return True if valid, False otherwise.""" - # Function implementation - -def process_data(data): - """Process the given data and return the result.""" - # Function implementation -``` - -### Variables -Choosing meaningful and consistent variable names is essential for code readability. Follow these conventions: - -- Use lowercase letters with underscores for variable names (snake_case). -- Be descriptive and use meaningful names to indicate the purpose of the variable. - -```python linenums="1" -# Good variable names -user_name = "John" -num_items = 5 -total_amount = 100.50 - -# Avoid ambiguous or single-letter names -a = "John" # Not recommended -n = 5 # Not recommended -``` - - -- Constants should be in uppercase with underscores. - -```python linenums="1" -MAX_RETRIES = 3 -PI = 3.14159 -``` - -- Avoid using names that shadow built-in functions or keywords. - -```python linenums="1" -# Bad: Don't use 'list' as a variable name -list = [1, 2, 3] - -# Good: Choose a different name -my_list = [1, 2, 3] -``` - -- Use meaningful prefixes and suffixes for variable names where applicable. - -```python linenums="1" -# Prefix 'is_' for boolean variables -is_valid = True - -# Suffix iterators with type (such as '_list') -name_list = ["John", "Mary", "Robert", "Sue"] -``` - -## Docstrings - -Documenting your code is crucial for understanding its functionality and usage. Use Google-style docstrings to provide clear and concise documentation. - -### Module Docstring -- Include a module-level docstring at the beginning of each Python file. -- Use triple double-quotes for multi-line docstrings. - -```python linenums="1" hl_lines="1-4" -"""Module-level docstring. - -This module provides utility functions for handling calculations. -""" - -# Rest of the module code -``` - -### Class Docstring -- Include a class-level docstring immediately below the class definition. -- Briefly describe the purpose and usage of the class. - -```python linenums="1" hl_lines="2-5" -class Calculator: - """A simple calculator class. - - This class provides basic arithmetic operations such as addition and subtraction. - """ - - def __init__(self): - # Constructor implementation -``` - -### Function Docstring -- Include a function-level docstring immediately below the function definition. -- Provide a clear description of the function's purpose, parameters, and return values. - -```python linenums="1" hl_lines="2-9" -def calculate_sum(numbers): - """Calculate the sum of a list of numbers. - - Args: - numbers (list): A list of numerical values. - - Returns: - float: The sum of the input numbers. - """ - # Function implementation - -``` - -## Typing -Python's optional type hints, introduced in PEP 484 and expanded in subsequent PEPs, provide a way to statically indicate the type of variables and function parameters. Proper use of typing can enhance code readability, maintainability, and catch certain types of errors early in the development process. - -### General Guidelines - -#### 1. Use Type Hints - -Type hints should be used consistently to indicate the expected types of variables and function parameters. - -```python linenums="1" hl_lines="1" -def add_numbers(a: int, b: int) -> int: # (1)! - return a + b -``` - -1. There is a function parameter type hint: `: int` and a function return type type hint: `-> int`. - -#### 2. Avoid Redundant Type Hints: - -Avoid providing type hints when the type is obvious from the variable name or the context. - -```python linenums="1" -# Bad -name: str = "John" - -# Good -age = 30 # Type is clear without specifying it -``` - -#### 3. Use Expressive Variable Names - -Choose variable names that convey meaning and make type hints redundant. - -```python linenums="1" -def calculate_area(length: float, width: float) -> float: - return length * width -``` - -#### 4. Be Consistent with Typing Styles - -Choose a consistent style for type hints, either using the ```:``` notation or the ```->``` notation for function return types. - -```python linenums="1" -# Consistent style with `:` -def greet(name: str): - print(f"Hello, {name}!") - -# Consistent style with `->` -def multiply(a: int, b: int) -> int: - return a * b -``` - -### Specific Typing Practices - -#### 1. Type Annotations for Variables - -Use type annotations for variables, especially in cases where the type might not be immediately obvious. - -```python linenums="1" -count: int = 0 -``` - -#### 2. Type Annotations for Function Parameters and Return Types - -Clearly annotate the types of function parameters and return types. - -```python linenums="1" -def calculate_total(items: List[float]) -> float: - return sum(items) -``` - -#### 3. Type Aliases - -Create readable and self-documenting type aliases for complex types. - -```python linenums="1" hl_lines="1-2" -Coordinates = tuple[float, float] -PointList = list[Coordinates] - -def plot_points(points: PointList) -> None: - # Plotting logic here -``` - -#### 4. Union Types - -Use [Union](https://docs.python.org/3/library/typing.html#typing.Union) types when a variable or parameter can have multiple types. - -```python linenums="1" hl_lines="3" -from typing import Union - -def display_value(value: Union[int, float, str]) -> None: - print(value) -``` - -#### 5. Type Hinting in Generics - -Use generic types when working with containers or collections. - -```python linenums="1" -def process_data(data: list[tuple[str, int]]) -> None: - # Processing logic here -``` - -#### 6. Callable Types - -Clearly annotate callable types using [Callable](https://docs.python.org/3/library/typing.html#typing.Callable) from the typing module. - - -```python linenums="1" -from typing import Callable - -def apply_function(func: Callable[[int, int], int], a: int, b: int) -> int: - return func(a, b) -``` - -## Virtual Environments - -### Introduction - -A virtual environment is a self-contained directory that contains a Python interpreter and allows you to install and manage project-specific dependencies. Use a virtual environment to isolate project dependencies and avoid conflicts with system-wide packages. - -Python 3 provides a built-in module for creating virtual environments: [venv](https://docs.python.org/3/library/venv.html). - -### Creating a Virtual Environment -To create a virtual environment, use the following command at the **root** of the repository: - -```shell -python -m venv venv -``` - -### Activating the Virtual Environment -Once the virtual environment is created, activate it in your terminal using the appropriate command for your operating system: - -For Windows: - -```powershell -venv\Scripts\activate -``` - -For Mac and Linux (including WSL): - -```shell -source venv/bin/activate -``` - -
---8<-- [end:mkdocs] diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md index 3030b9b2..72fc3637 100644 --- a/docs/CODE_OF_CONDUCT.md +++ b/docs/CODE_OF_CONDUCT.md @@ -1 +1,48 @@ ---8<-- ".github/CODE_OF_CONDUCT.md" +# Contributor Code of Conduct + +As contributors and maintainers of this project, and in the interest of +fostering an open and welcoming community, we pledge to respect all people who +contribute through reporting issues, posting feature requests, updating +documentation, submitting pull requests or patches, and other activities. + +We are committed to making participation in this project a harassment-free +experience for everyone, regardless of level of experience, gender, gender +identity and expression, sexual orientation, disability, personal appearance, +body size, race, ethnicity, age, religion, or nationality. + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery +* Personal attacks +* Trolling or insulting/derogatory comments +* Public or private harassment +* Publishing other's private information, such as physical or electronic + addresses, without explicit permission +* Other unethical or unprofessional conduct + +Project maintainers 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, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to +fairly and consistently applying these principles to every aspect of managing +this project. Project maintainers who do not follow or enforce the Code of +Conduct may be permanently removed from the project team. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting a project maintainer at https://spokanepython.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. Maintainers are +obligated to maintain confidentiality with regard to the reporter of an +incident. + + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.3.0, available at [https://www.contributor-covenant.org/version/1/3/0/code-of-conduct.html](https://www.contributor-covenant.org/version/1/3/0/code-of-conduct.html). + +[homepage]: https://www.contributor-covenant.org diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md index 7f0cb737..d6ea5cdd 100644 --- a/docs/STYLE_GUIDE.md +++ b/docs/STYLE_GUIDE.md @@ -1,3 +1,284 @@ # Style Guide ---8<-- ".github/STYLE_GUIDE.md:intro" ---8<-- ".github/STYLE_GUIDE.md:mkdocs" + +This Python style guide provides conventions and best practices for writing clean and maintainable Python code. Adhering to these guidelines will help ensure consistency across projects and enhance the clarity, maintainability, +and readability of the code. + +## PEP 8 + +Adhere to the PEP 8 style guide, which is the style guide for Python code. Please make sure to familiarize yourself with PEP 8 guidelines: [PEP 8 -- Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). + +## Line Length + +The maximum line length for code and comments is set to 120 characters. This allows for better readability without excessively long lines. + +## Naming Conventions + +### Classes +- Class names should follow the CamelCase convention. +- Class names should be descriptive and represent a clear concept or object. + +```python linenums="1" hl_lines="1" +class Calculator: + def __init__(self): + # Constructor implementation + + def add(self, x, y): + # Method implementation +``` + +### Functions +- Function names should be lowercase, with words separated by underscores. +- Function names should begin with a verb to indicate the action or operation they perform. + +```python linenums="1" hl_lines="1 5 9" +def calculate_sum(numbers): + """Calculate the sum of a list of numbers.""" + # Function implementation + +def validate_input(user_input): + """Validate user input and return True if valid, False otherwise.""" + # Function implementation + +def process_data(data): + """Process the given data and return the result.""" + # Function implementation +``` + +### Variables +Choosing meaningful and consistent variable names is essential for code readability. Follow these conventions: + +- Use lowercase letters with underscores for variable names (snake_case). +- Be descriptive and use meaningful names to indicate the purpose of the variable. + +```python linenums="1" +# Good variable names +user_name = "John" +num_items = 5 +total_amount = 100.50 + +# Avoid ambiguous or single-letter names +a = "John" # Not recommended +n = 5 # Not recommended +``` + + +- Constants should be in uppercase with underscores. + +```python linenums="1" +MAX_RETRIES = 3 +PI = 3.14159 +``` + +- Avoid using names that shadow built-in functions or keywords. + +```python linenums="1" +# Bad: Don't use 'list' as a variable name +list = [1, 2, 3] + +# Good: Choose a different name +my_list = [1, 2, 3] +``` + +- Use meaningful prefixes and suffixes for variable names where applicable. + +```python linenums="1" +# Prefix 'is_' for boolean variables +is_valid = True + +# Suffix iterators with type (such as '_list') +name_list = ["John", "Mary", "Robert", "Sue"] +``` + +## Docstrings + +Documenting your code is crucial for understanding its functionality and usage. Use Google-style docstrings to provide clear and concise documentation. + +### Module Docstring +- Include a module-level docstring at the beginning of each Python file. +- Use triple double-quotes for multi-line docstrings. + +```python linenums="1" hl_lines="1-4" +"""Module-level docstring. + +This module provides utility functions for handling calculations. +""" + +# Rest of the module code +``` + +### Class Docstring +- Include a class-level docstring immediately below the class definition. +- Briefly describe the purpose and usage of the class. + +```python linenums="1" hl_lines="2-5" +class Calculator: + """A simple calculator class. + + This class provides basic arithmetic operations such as addition and subtraction. + """ + + def __init__(self): + # Constructor implementation +``` + +### Function Docstring +- Include a function-level docstring immediately below the function definition. +- Provide a clear description of the function's purpose, parameters, and return values. + +```python linenums="1" hl_lines="2-9" +def calculate_sum(numbers): + """Calculate the sum of a list of numbers. + + Args: + numbers (list): A list of numerical values. + + Returns: + float: The sum of the input numbers. + """ + # Function implementation + +``` + +## Typing +Python's optional type hints, introduced in PEP 484 and expanded in subsequent PEPs, provide a way to statically indicate the type of variables and function parameters. Proper use of typing can enhance code readability, maintainability, and catch certain types of errors early in the development process. + +### General Guidelines + +#### 1. Use Type Hints + +Type hints should be used consistently to indicate the expected types of variables and function parameters. + +```python linenums="1" hl_lines="1" +def add_numbers(a: int, b: int) -> int: # (1)! + return a + b +``` + +1. There is a function parameter type hint: `: int` and a function return type type hint: `-> int`. + +#### 2. Avoid Redundant Type Hints: + +Avoid providing type hints when the type is obvious from the variable name or the context. + +```python linenums="1" +# Bad +name: str = "John" + +# Good +age = 30 # Type is clear without specifying it +``` + +#### 3. Use Expressive Variable Names + +Choose variable names that convey meaning and make type hints redundant. + +```python linenums="1" +def calculate_area(length: float, width: float) -> float: + return length * width +``` + +#### 4. Be Consistent with Typing Styles + +Choose a consistent style for type hints, either using the ```:``` notation or the ```->``` notation for function return types. + +```python linenums="1" +# Consistent style with `:` +def greet(name: str): + print(f"Hello, {name}!") + +# Consistent style with `->` +def multiply(a: int, b: int) -> int: + return a * b +``` + +### Specific Typing Practices + +#### 1. Type Annotations for Variables + +Use type annotations for variables, especially in cases where the type might not be immediately obvious. + +```python linenums="1" +count: int = 0 +``` + +#### 2. Type Annotations for Function Parameters and Return Types + +Clearly annotate the types of function parameters and return types. + +```python linenums="1" +def calculate_total(items: List[float]) -> float: + return sum(items) +``` + +#### 3. Type Aliases + +Create readable and self-documenting type aliases for complex types. + +```python linenums="1" hl_lines="1-2" +Coordinates = tuple[float, float] +PointList = list[Coordinates] + +def plot_points(points: PointList) -> None: + # Plotting logic here +``` + +#### 4. Union Types + +Use [Union](https://docs.python.org/3/library/typing.html#typing.Union) types when a variable or parameter can have multiple types. + +```python linenums="1" hl_lines="3" +from typing import Union + +def display_value(value: Union[int, float, str]) -> None: + print(value) +``` + +#### 5. Type Hinting in Generics + +Use generic types when working with containers or collections. + +```python linenums="1" +def process_data(data: list[tuple[str, int]]) -> None: + # Processing logic here +``` + +#### 6. Callable Types + +Clearly annotate callable types using [Callable](https://docs.python.org/3/library/typing.html#typing.Callable) from the typing module. + + +```python linenums="1" +from typing import Callable + +def apply_function(func: Callable[[int, int], int], a: int, b: int) -> int: + return func(a, b) +``` + +## Virtual Environments + +### Introduction + +A virtual environment is a self-contained directory that contains a Python interpreter and allows you to install and manage project-specific dependencies. Use a virtual environment to isolate project dependencies and avoid conflicts with system-wide packages. + +Python 3 provides a built-in module for creating virtual environments: [venv](https://docs.python.org/3/library/venv.html). + +### Creating a Virtual Environment +To create a virtual environment, use the following command at the **root** of the repository: + +```shell +python -m venv venv +``` + +### Activating the Virtual Environment +Once the virtual environment is created, activate it in your terminal using the appropriate command for your operating system: + +For Windows: + +```powershell +venv\Scripts\activate +``` + +For Mac and Linux (including WSL): + +```shell +source venv/bin/activate +```