Skip to content

Start adding documentation #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
version: 2
updates:
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "weekly"
target-branch: "develop"
open-pull-requests-limit: 10
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
target-branch: "develop"
76 changes: 76 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
push:
branches: [ "main" ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ "main" ]
schedule:
- cron: '29 12 * * 1'

jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [ 'python' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Use only 'java' to analyze code written in Java, Kotlin or both
# Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support

steps:
- name: Checkout repository
uses: actions/checkout@v4

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.

# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality


# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v3

# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun

# If the Autobuild fails above, remove it and uncomment the following three lines.
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.

# - run: |
# echo "Run, Build Application using script"
# ./location_of_script_within_repo/buildscript.sh

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
20 changes: 20 additions & 0 deletions .github/workflows/dependency-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Dependency Review Action
#
# This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging.
#
# Source repository: https://github.com/actions/dependency-review-action
# Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement
name: 'Dependency Review'
on: [pull_request]

permissions:
contents: read

jobs:
dependency-review:
runs-on: ubuntu-latest
steps:
- name: 'Checkout Repository'
uses: actions/checkout@v4
- name: 'Dependency Review'
uses: actions/dependency-review-action@v3
17 changes: 17 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
name: Linting

on: [push, pull_request, workflow_dispatch]

jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Linting
uses: chartboost/ruff-action@v1
with:
args: check
- name: Check Formatting
uses: chartboost/ruff-action@v1
with:
args: format --check
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,4 @@ cython_debug/

# Custom rules (everything added below won't be overriden by 'Generate .gitignore File' if you use 'Update' option)
test.db
.python-version
77 changes: 77 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
ci:
autofix_commit_msg: "[pre-commit.ci] auto fixes from pre-commit.com hooks [dependabot skip]"
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-yaml
args: [--unsafe]
- id: trailing-whitespace
- id: check-toml
- id: check-merge-conflict
- id: end-of-file-fixer

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.14
hooks:
- id: ruff
name: "lint with ruff"
- id: ruff-format
name: "format with ruff"

- repo: https://github.com/jackdewinter/pymarkdown
rev: 0.9.16
hooks:
- id: pymarkdown
name: "check markdown"
exclude: ^.github/|CHANGELOG
args: [-d, "MD046", scan]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.8.0" # Use the sha / tag you want to point at
hooks:
- id: mypy
name: "Check with Mypy"

- repo: https://github.com/RobertCraigie/pyright-python
rev: v1.1.349
hooks:
- id: pyright
name: "Check with Pyright"
exclude: tests
additional_dependencies: [sqlalchemy, uvicorn, fastapi]

- repo: https://github.com/python-poetry/poetry
rev: "1.7.0"
hooks:
- id: poetry-check
name: "check poetry files"
# - id: poetry-lock

- repo: https://github.com/python-poetry/poetry-plugin-export
rev: "1.6.0"
hooks:
- id: poetry-export
name: "export production dependencies"
args:
[
"--without-hashes",
"-f",
"requirements.txt",
"-o",
"requirements.txt",
"--without",
"dev",
]
- id: poetry-export
name: "export development dependencies"
args:
[
"--without-hashes",
"-f",
"requirements.txt",
"-o",
"requirements-dev.txt",
"--with",
"dev",
]
41 changes: 25 additions & 16 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,49 +1,58 @@
{
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
},
"autoDocstring.startOnNewLine": true,
"beautify.language": {
"html": ["htm", "html", "django-html"]
},
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"emmet.includeLanguages": {
"django-html": "html",
"jinja-html": "html"
},
"emmet.triggerExpansionOnTab": true,
"files.associations": {
"**/*.html": "html",
"**/*.tpl": "jinja",
"**/requirements{/**,*}.{txt,in}": "pip-requirements",
"**/templates/**/*": "django-txt",
"**/templates/**/*.html": "jinja-html"
},
"files.eol": "\n",
"files.exclude": {
"**/.cache": true,
"**/.mypy_cache": true,
"**/.pytest_cache": true,
"**/.ruff_cache": true,
"**/__pycache__": true
},
"git.alwaysSignOff": true,
"git.enableCommitSigning": true,
"html.format.indentHandlebars": true,
"html.format.templating": true,
"markdownlint.ignore": ["CHANGELOG.md"],
"material-icon-theme.languages.associations": {
"jinja-html": "django"
},
"mypy-type-checker.args": ["--strict"],
"mypy-type-checker.importStrategy": "useBundled",
"mypy-type-checker.reportingScope": "workspace",
"python.analysis.autoImportCompletions": true,
"python.analysis.autoImportUserSymbols": true,
"python.analysis.extraPaths": [],
"python.analysis.indexing": true,
"python.analysis.stubPath": "/home/seapagan/stubs",
"python.analysis.typeCheckingMode": "basic",
"python.formatting.blackArgs": ["--line-length=80"],
"python.formatting.provider": "black",
"python.analysis.typeCheckingMode": "off",
"python.languageServer": "Pylance",
"python.linting.enabled": true,
"python.linting.flake8Args": ["--max-line-length=80"],
"python.linting.flake8Enabled": true,
"python.linting.mypyEnabled": false,
"python.linting.pydocstyleArgs": ["--convention=google"],
"python.linting.pylintArgs": [],
"python.linting.pylintEnabled": false,
"python.pythonPath": "./.venv/bin/python",
"isort.args": ["--profile", "black", "--src=${workspaceFolder}"],
"python.testing.pytestArgs": ["tests"],
"python.testing.pytestEnabled": true,
"python.testing.unittestArgs": ["-v", "-s", "./tests", "-p", "*_test.py"],
"python.testing.unittestEnabled": false
"python.testing.unittestEnabled": false,
"ruff.fixAll": false,
"ruff.organizeImports": true
}
2 changes: 1 addition & 1 deletion LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2023 Grant Ramsay
Copyright (c) 2023-2024 Grant Ramsay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Simple example how to use FastAPI with Async SQLAlchemy 2.0 <!-- omit from toc -->
# Using FastAPI with Async SQLAlchemy 2.0 <!-- omit from toc -->

- [Introduction](#introduction)
- [Installation](#installation)
Expand Down Expand Up @@ -109,7 +109,7 @@ This project is licensed under the terms of the MIT license.
```pre
MIT License

Copyright (c) 2023 Grant Ramsay
Copyright (c) 2023-2024 Grant Ramsay

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
50 changes: 37 additions & 13 deletions db.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,57 @@
"""Set up the database connection and session.""" ""
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.orm import declarative_base
from collections.abc import AsyncGenerator
from typing import Any

from sqlalchemy import MetaData
from sqlalchemy.ext.asyncio import (
AsyncSession,
async_sessionmaker,
create_async_engine,
)
from sqlalchemy.orm import DeclarativeBase

DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost/postgres"
# DATABASE_URL = "sqlite+aiosqlite:///./test.db"
# DATABASE_URL = "sqlite+aiosqlite:///./test.db" # noqa: ERA001
# Note that (as far as I can tell from the docs and searching) there is no need
# to add 'check_same_thread=False' to the sqlite connection string, as
# SQLAlchemy version 1.4+ will automatically add it for you when using SQLite.

engine = create_async_engine(DATABASE_URL, echo=False)
Base = declarative_base()
async_session = async_sessionmaker(engine, expire_on_commit=False)

class Base(DeclarativeBase):
"""Base class for SQLAlchemy models.

All other models should inherit from this class.
"""

metadata = MetaData(
naming_convention={
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
)


async_engine = create_async_engine(DATABASE_URL, echo=False)
async_session = async_sessionmaker(async_engine, expire_on_commit=False)


async def get_db():
async def get_db() -> AsyncGenerator[AsyncSession, Any]:
"""Get a database session.

To be used for dependency injection.
"""
async with async_session() as session:
async with session.begin():
yield session
async with async_session() as session, session.begin():
yield session


async def init_models():
async def init_models() -> None:
"""Create tables if they don't already exist.

In a real-life example we would use Alembic to manage migrations.
"""
async with engine.begin() as conn:
# await conn.run_sync(Base.metadata.drop_all)
async with async_engine.begin() as conn:
# await conn.run_sync(Base.metadata.drop_all) # noqa: ERA001
await conn.run_sync(Base.metadata.create_all)
4 changes: 4 additions & 0 deletions docs/explanation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Code Explanation

!!! note "Under Construction"
This section is still to be written.
Loading