Make APIs easy and fast.
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
from unittest.mock import MagicMock

# Determine the absolute path to the directory containing the python modules.
_pysrc = os.path.abspath(os.path.join(os.path.abspath(__file__), "..", "..", ".."))

# Insert it into the path.
sys.path.insert(0, _pysrc)

# Now we can import local modules.
import ildiz  # noqa

# -- Document __init__ methods by default. --------------------------------
# This section was added to allow __init__() to be documented automatically.
# You can comment this section out to go back to the default behavior.
# See: http://stackoverflow.com/questions/5599254


def skip(app, what, name, obj, skip, options):
    if name == "__init__":
        return False
    return skip


def setup(app):
    app.connect("autodoc-skip-member", skip)


class Mock(MagicMock):
    @classmethod
    def __getattr__(cls, name):
        return MagicMock()


MOCK_MODULES = [
    "numpy",
    "scipy",
    "sklearn",
    "matplotlib",
    "matplotlib.pyplot",
    "scipy.interpolate",
    "scipy.special",
    "math",
    "pandas",
]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode", "sphinx.ext.githubpages"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "ildiz"
copyright = "2023, ildiz"
author = "Sayfulla Mirxalikov"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# version = ildiz.__version__
# The full version, including alpha/beta/rc tags.
# release = ildiz.__release__

# The full version, including alpha/beta/rc tags

release = ildiz.__release__

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.

# fmt: off
  # noqa
# fmt: on
html_theme = "alabaster"

html_theme_options = {
    "logo": "logo.png",
    "github_user": "ildiz",
    "github_repo": "ildiz",
}
# fmt: off
  # noqa
  # noqa
# fmt: on

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
    "**": [
        "about.html",
        "navigation.html",
        "relations.html",  # needs 'show_related': True theme option to display
        "searchbox.html",
        "donate.html",
    ]
}

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "ildizdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (
        master_doc,
        "ildiz.tex",
        "ildiz Documentation",
        "ildiz",
        "manual",
    )
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (
        master_doc,
        "ildiz",
        "ildiz Documentation",
        [author],
        1,
    )
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        master_doc,
        "ildiz",
        "ildiz Documentation",
        author,
        "ildiz",
        "One line description of project.",
        "Miscellaneous",
    )
]

docs/source/conf.py
ildiz/ildiz
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Crud API maker from yaml file.

.. currentmodule:: ildiz
.. moduleauthor:: Sayfulla Mirxalikov <mirxoliqov.sayfulla@gmail.com>
"""

from .version import __version__, __release__  # noqa

ildiz/__init__.py
ildiz/ildiz
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import click

from .utils import create_database, create_server
from .__init__ import __version__



@click.group()
def cli():
    """CRUD API maker from yaml file."""
    pass


@cli.command()
def initdb():
    """It creates database from schema.yaml file."""
    if "schema.yaml" in os.listdir(os.getcwd()):
        click.echo("Database is creating...")
        create_database()
        click.echo("Your database created.")
    else:
        click.echo("schema.yaml not found!")

@cli.command()
def server():
    """You can start your CRUD API server."""
    if "database.db" in os.listdir(os.getcwd()):
        create_server()
    else:
        click.echo("database.db not found!")


@cli.command()
def version():
    """Get the library version."""
    click.echo(click.style(f"{__version__}", bold=True))

ildiz/cli.py
ildiz/ildiz
def create_database():
    import sqlite3
    import yaml

    with open("schema.yaml") as file:
        schema = yaml.safe_load(file)

    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()

    for table_name, fields in schema.items():
        create_query = f"CREATE TABLE IF NOT EXISTS {table_name} ("

        for field, field_type in fields.items():
            create_query += f"{field} {field_type}, "

        create_query = create_query.rstrip(", ") + ")"
        print(create_query)
        cursor.execute(create_query)

    conn.commit()
    conn.close()


def create_server():
    from fastapi import FastAPI, HTTPException
    from sqlite_utils import Database
    import uvicorn

    app = FastAPI()
    db = Database("database.db")

    @app.get("/api/{table_name}")
    async def get_all_records(table_name: str):
        table = db[table_name]
        return table.rows

    @app.get("/api/{table_name}/{record_id}", status_code=200)
    async def get_record(table_name: str, record_id: int) -> dict:
        table = db[table_name]
        try:
            return table.get(record_id)
        except:
            raise HTTPException(status_code=404, detail="Not found.")

    @app.post("/api/{table_name}", status_code=201)
    async def create_record(table_name: str, record: dict):
        table = db[table_name]
        try:
            table.insert(record)
            return record
        except:
            raise HTTPException(status_code=400, detail="Bad request.")

    @app.put("/api/{table_name}/{record_id}")
    async def update_record(table_name: str, record_id: int, record: dict):
        table = db[table_name]
        try:
            table.update(record_id, record)
            return record
        except:
            raise HTTPException(status_code=400, detail="Bad request.")

    @app.delete("/api/{table_name}/{record_id}")
    async def delete_record(table_name: str, record_id: int) -> dict:
        table = db[table_name]
        try:
            table.delete(record_id)
            return {"msg": f"Deleted #{record_id} from {table_name}"}
        except:
            raise HTTPException(status_code=404, detail="Not found.")

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="debug")

ildiz/utils.py
ildiz/ildiz
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This module contains project version information.

.. currentmodule:: ildiz.version
.. moduleauthor:: Sayfulla Mirxalikov <mirxoliqov.sayfulla@gmail.com>
"""

__version__ = "0.0.1"  #: the working version
__release__ = "0.0.1"  #: the release version

ildiz/version.py
ildiz/ildiz
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This file is used to create the package we'll publish to PyPI.

.. currentmodule:: setup.py
.. moduleauthor:: Sayfulla Mirxalikov <mirxoliqov.sayfulla@gmail.com>
"""

import importlib.util
import os
from pathlib import Path
from setuptools import setup, find_packages
from codecs import open  # Use a consistent encoding.
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the relevant file
with open(path.join(here, "README.rst"), encoding="utf-8") as f:
    long_description = f.read()

# Get the base version from the library.  (We'll find it in the `version.py`
# file in the src directory, but we'll bypass actually loading up the library.)
vspec = importlib.util.spec_from_file_location(
  "version",
  str(Path(__file__).resolve().parent /
      "ildiz"/"version.py")
)
vmod = importlib.util.module_from_spec(vspec)
vspec.loader.exec_module(vmod)
version = getattr(vmod, "__version__")

# If the environment has a build number set...
if os.getenv("buildnum") is not None:
    # ...append it to the version.
    version = f"{version}.{os.getenv('buildnum')}"

setup(
    name='ildiz',
    description="CRUD API maker from yaml file.",
    long_description=long_description,
    packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),
    version=version,
    install_requires=[
        # Include dependencies here
        "click>=7.0,<8"
    ],
    entry_points="""
    [console_scripts]
    ildiz=ildiz.cli:cli
    """,
    python_requires=">=0.0.1",
    license='MIT',  # noqa
    author='Sayfulla Mirxalikov',
    author_email='mirxoliqov.sayfulla@gmail.com',
    # Use the URL to the github repo.
    url= 'https://github.com/ildiz/ildiz',
    download_url=(
        f'https://github.com/ildiz/'
        f'ildiz/archive/{version}.tar.gz'
    ),
    keywords=[
        # Add package keywords here.
    ],
    # See https://PyPI.python.org/PyPI?%3Aaction=list_classifiers
    classifiers=[
      # How mature is this project? Common values are
      #   3 - Alpha
      #   4 - Beta
      #   5 - Production/Stable
      "Development Status :: 3 - Alpha",

      # Indicate who your project is intended for.
      "Intended Audience :: Developers",
      "Topic :: Software Development :: Libraries",

      # Pick your license.  (It should match "license" above.)
        # noqa
      """License :: OSI Approved :: MIT License""",
        # noqa
      # Specify the Python versions you support here. In particular, ensure
      # that you indicate whether you support Python 2, Python 3 or both.
      "Programming Language :: Python :: 3.8",
    ],
    include_package_data=True
)

setup.py
ildiz/ildiz
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
.. currentmodule:: test_cli
.. moduleauthor:: Sayfulla Mirxalikov <mirxoliqov.sayfulla@gmail.com>

This is the test module for the project's command-line interface (CLI)
module.
"""
# fmt: off
import ildiz.cli as cli
from ildiz import __version__
# fmt: on
from click.testing import CliRunner, Result


# To learn more about testing Click applications, visit the link below.
# http://click.pocoo.org/5/testing/


def test_version_displays_library_version():
    """
    Arrange/Act: Run the `version` subcommand.
    Assert: The output matches the library version.
    """
    runner: CliRunner = CliRunner()
    result: Result = runner.invoke(cli.cli, ["version"])
    assert (
        __version__ in result.output.strip()
    ), "Version number should match library version."


tests/test_cli.py
ildiz/ildiz