SQLAlchemy Admin for Starlette/FastAPI

Build Status Publish Status Coverage Package version Supported Python versions


SQLAlchemy Admin for Starlette/FastAPI

SQLAdmin is a flexible Admin interface for SQLAlchemy models.

Main features include:


Documentation: https://aminalaee.github.io/sqladmin

Source Code: https://github.com/aminalaee/sqladmin

Online Demo: Demo


Installation

$ pip install sqladmin

Quickstart

Let's define an example SQLAlchemy model:

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()
engine = create_engine(
    "sqlite:///example.db",
    connect_args={"check_same_thread": False},
)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String)


Base.metadata.create_all(engine)  # Create tables

If you want to use SQLAdmin with FastAPI:

from fastapi import FastAPI
from sqladmin import Admin, ModelAdmin


app = FastAPI()
admin = Admin(app, engine)


class UserAdmin(ModelAdmin, model=User):
    column_list = [User.id, User.name]


admin.register_model(UserAdmin)

Or if you want to use SQLAdmin with Starlette:

from sqladmin import Admin, ModelAdmin
from starlette.applications import Starlette


app = Starlette()
admin = Admin(app, engine)


class UserAdmin(ModelAdmin, model=User):
    column_list = [User.id, User.name]


admin.register_model(UserAdmin)

Now visiting /admin on your browser you can see the SQLAdmin interface.

Related projects and inspirations

  • Flask-Admin Admin interface for Flask supporting different database backends and ORMs. This project has inspired SQLAdmin extensively and most of the features and configurations are implemented the same.
  • FastAPI-Admin Admin interface for FastAPI which works with TortoiseORM.
  • Dashboard Admin interface for ASGI frameworks which works with the orm package.
Comments
  • add the login function

    add the login function

    I tried adding the login function. Including the following:

    1. A User model
    2. A script to create a user
    3. Reads the fields required for user-generated passwords from. Env.
    4. Login html can use i18n and Chinese.

    Now there has some question: 1.I don't know how to create an executable with setup.py.(I can only use poetry to create a program by tool.poetry.scripts) 2. Most of this update is from my old project.But it need deeply test. 3. Doc need update.

    In new version,you need create a .env in project's root.And .env need this data(like this): SECRET_KEY=aawinjwol;egbfnjek bnl DATABASE_URL=sqlite:///example.db

    If you want to create a manager: bash

    sqladmin username password
    
  • fix docstring issues by adding an explicit handler

    fix docstring issues by adding an explicit handler

    Long story short: fixes #104.

    Locking the dependency uses mkdocstrings's so-called "experimental" handler for docstring parsing. The new one properly parses the docstring in this case whereas the legacy one does not.

  • SQLModel support

    SQLModel support

    Discussed in https://github.com/aminalaee/sqladmin/discussions/56

    Originally posted by JonasKs February 16, 2022 Hi! This looks awesome, Iโ€™m definitely going to test it out!

    Since this support SQLAlchemy, will it also support SQLModel? ๐Ÿ˜Š

    As suggested by @JonasKs, I did test SQLAdmin with SQLModel but it needs a few tweaks to make it work. I'll get to it after we have the minimum functionality like #24 done.

  • Add form-specific functionality to ModelAdmin

    Add form-specific functionality to ModelAdmin

    I added the following attributes to ModelAdmin:

    • form
    • form_base_class
    • form_args
    • form_columns
    • form_excluded_columns
    • form_overrides

    All of these attributes emulate their respective functionality in the Flask-Admin API: https://flask-admin.readthedocs.io/en/latest/api/mod_model/

    This PR addresses issue #96.

    --

    Note that I abstracted out the get_{x}_columns() functionality in ModelAdmin. Let me know if you want me to revert this back to being repetitive.


    ~~As of writing, there is one thing currently missing from my PR: the scaffolding does not make use of column_labels. This is something I will hope to finish up soon!~~

    Let me know what other changes you want me to make.

  • sort doesn't work after adding custom labels.

    sort doesn't work after adding custom labels.

    Checklist

    • [X] The bug is reproducible against the latest release or master.
    • [X] There are no similar issues or pull requests to fix it yet.

    Describe the bug

    Thank you for this awesome repo. It saved me a lot of time. I have faced a weird bug. Here goes my model. class UserAdmin(ModelAdmin, model=UserModel.User): column_list = [UserModel.User.id, UserModel.User.last_name, UserModel.User.first_name, UserModel.User.email] column_sortable_list = [UserModel.User.last_name,UserModel.User.first_name,UserModel.User.email] column_labels = dict(id='ID',last_name='Last Name', first_name='First Name',email='Email Address')

    It worked perfectly until I added custom_labels. Now when ever I click on the table header, it returns with an error saying "Model User has no attribute 'Email address' "

    This should sort using original field name, not with the label.

    Steps to reproduce the bug

    No response

    Expected behavior

    No response

    Actual behavior

    No response

    Debugging material

    No response

    Environment

    • OS: ubuntu 20.04
    • python 3.7.10
    • fastapi 0.63
    • sqladmin 0.1.7
    • SQLAlchemy 1.4.32

    Additional context

    No response

  • Refactor `forms.py` (Work in progress)

    Refactor `forms.py` (Work in progress)

    Objectives

    This PR is a refactor of forms.py.

    The immediate objectives of this refactor are listed in the section titled "Code Changes".

    The longer-term objective of this refactor is to move toward using AdminAttributes internally. A lot of the code right now is hard to manage because there is no concept that relates a single SQLA/wtforms field/column/property. Ultimately, a List[AdminAttribute] should be generated by the ModelAdmin() instance, instead of inside get_model_form().

    In my opinion, more and more parsing/app logic should move toward AdminAttribute internals, and then the rest of the code can focus more on the core framework logic. Right now, a lot of parsing, and generation of defaults, is being handled at multiple parts of the code. AdminAttribute can be a single spot for all the "ugly but necessary" stuff, and the rest of the code (the parts we want to actually add features) will be cleaner as a result.

    Code Changes

    Consistent typing:

    • Create a ConverterCallback type with a sensible signature. (In this case, pulled from Flask-Admin's pattern.)
    • Apply the signature to decorated @converts(...) methods.
    • wtforms has very weird typing (or rather, a lack of typing). I added a type for the wtforms validators. I got the type right (check wtforms/validators.py), but it's unclear whether this is appropriate.

    Renames

    Converter Callbacks

    The main purpose of the renaming in this refactor is to enforce the distinction between a converter and a converter callback. The class is called ModelConverter, which implies that a ModelConverter() object is the converter. But, in the code, get_converter() does not get a converter instance, it gets a callable that is not a converter per se (based on the convention that a ModelConverter is a converter.

    To have consistent naming, the function should be called a "converter callback," to distinguish it from the converter class. All references to the decorated functions should then make clear that these are "converter callbacks" and not mere "converters."

    • ModelConverterBase.get_converter() --> ModelConverterBase.get_callback()
    • ModelConverterBase.converters --> ModelConverterBase._callbacks
    • Create a type called ConverterCallback to reinforce both the concept and the signature.

    Property vs attribute

    mapper.attrs misleadingly returns objects of type Union[ColumnProperty, RelationshipProperty]. I think we should move toward referring to objects with this typing as props. In the function get_model_form, I adhere to this behavior. (Although I don't make any additional changes in the rest of the code.)

  • chore: Improve Code Style

    chore: Improve Code Style

    @aminalaee I like the Idea behind SQLAdmin, I will add some features to it in the future and I will use it in one of my projects soon, While I read the code I found some parts that could be refactored and enhanced to be better.

    If you have any questions, we could discuss them!

  • Handling for sqlalchemy_utils EmailType and IPAddressType

    Handling for sqlalchemy_utils EmailType and IPAddressType

    Currently if an EmailType or IPAddressType from sqlalchemy_utils is used it causes the entire admin to crash. Improved this feature by adding integrating validators from wtforms. Fixes #148

    Note: I did need to add a dependency, email-validators. See the following stack overflow post for why this was necessary: https://stackoverflow.com/questions/61356834/wtforms-install-email-validator-for-email-validation-support

  • Fix Export unlimited rows

    Fix Export unlimited rows

    Right now if you don't specify export_max_rows then only 10 rows are exported. An example here: https://python-sqladmin.herokuapp.com/admin/user/list

    The reason this happened is that we rely on the pagination and pagination will do a few checks before setting page and page_size options and won't allow unlimited rows.

    I added a different query for this behaviour.

    I'll add some tests for it.

  • Boolean field checkbox doesn't work

    Boolean field checkbox doesn't work

    Discussed in https://github.com/aminalaee/sqladmin/discussions/86

    Originally posted by maxiaojunwolf March 15, 2022 here is my ORM Field:

        picture = Column(Boolean, default=False)
    

    20220315-224244

  • Accept JSON type

    Accept JSON type

    Checklist

    • [X] There are no similar issues or pull requests for this yet.

    Is your feature related to a problem? Please describe.

    I want to be able to show JSON column in detail page.

    Could not find field converter for column questions (<class 'sqlalchemy.dialects.postgresql.json.JSON'>).

    Describe the solution you would like.

    No response

    Describe alternatives you considered

    No response

    Additional context

    No response

  • Many to many field setup error

    Many to many field setup error

    Checklist

    • [X] The bug is reproducible against the latest release or master.
    • [X] There are no similar issues or pull requests to fix it yet.

    Describe the bug

    I am trying to update m2m field in form but i am getting error "sqlalchemy.exc.InvalidRequestError: Can't attach instance another instance with key is already present in this session"

    Steps to reproduce the bug

    No response

    Expected behavior

    No response

    Actual behavior

    No response

    Debugging material

    No response

    Environment

    Macos , python 3.9

    Additional context

    No response

  • There is no way to customize object_list for form_args.

    There is no way to customize object_list for form_args.

    Checklist

    • [X] There are no similar issues or pull requests for this yet.

    Is your feature related to a problem? Please describe.

    I want to set up a custom objects_list for the QuerySelectField field, but I can't because this property is overridden in the ModelConverter.convert method.

    Describe the solution you would like.

    No response

    Describe alternatives you considered

    No response

    Additional context

    No response

  • Now the json field is only for viewing and printing. Automatic generation is needed.

    Now the json field is only for viewing and printing. Automatic generation is needed.

    Checklist

    • [X] There are no similar issues or pull requests for this yet.

    Is your feature related to a problem? Please describe.

    There are: class JSONField(fields.TextAreaField): Necessary: class JSONField(fields.FileField):

    Describe the solution you would like.

    In the web forms I have configured https://accent-starlette.github.io/starlette-files/handling_files/ file = sa.Column(FileType.as_mutable(sa.JSON), nullable=True) views.py The result is excellent In the admin area of the coma

    Describe alternatives you considered

    Alternative solution: I have not found.

    Additional context

    Now the json field is only for viewing and printing. Automatic generation is needed.

  • Support for .with_variant() types

    Support for .with_variant() types

    Checklist

    • [X] There are no similar issues or pull requests for this yet.

    Is your feature related to a problem? Please describe.

    When using BigIntegers in sqlalchemy together with "with_variant", e.g. Column(BigInteger().with_variant(Integer, "sqlite")) the error "Could not find field converter for column id (<class 'sqlalchemy.sql.type_api.Variant'>)" is thrown.

    Describe the solution you would like.

    No response

    Describe alternatives you considered

    Using form_overrides seems to work fine as workaround however native support would be much appreciated :)

    Additional context

    No response

  • Lazy support

    Lazy support

    Checklist

    • [x] There are no similar issues or pull requests for this yet.

    Is your feature related to a problem? Please describe.

    Hello. In my project I have a lot relationships with lazy="dynamic". But sqladmin don't supports it

    Describe the solution you would like.

    I would like to see setting in config like load_lazys . If if is True load all relationships

    Describe alternatives you considered

    No response

    Additional context

    No response

fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability
fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability

FastAPI2 Admin Introduction fastapi-admin2 is an upgraded fastapi-admin, that supports ORM dialects, true Dependency Injection and extendability. Now

May 4, 2022
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

May 11, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

May 19, 2022
Opentracing support for Starlette and FastApi
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Apr 15, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Feb 16, 2021
Prometheus exporter for Starlette and FastAPI

starlette_exporter Prometheus exporter for Starlette and FastAPI. The middleware collects basic metrics: Counter: starlette_requests_total Histogram:

Feb 13, 2021
Opentracing support for Starlette and FastApi
Opentracing support for Starlette and FastApi

Starlette-OpenTracing OpenTracing support for Starlette and FastApi. Inspired by: Flask-OpenTracing OpenTracing implementations exist for major distri

Feb 11, 2021
Adds simple SQLAlchemy support to FastAPI

FastAPI-SQLAlchemy FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful help

May 10, 2022
๐Ÿš€ Cookiecutter Template for FastAPI + React Projects. Using PostgreSQL, SQLAlchemy, and Docker
๐Ÿš€   Cookiecutter Template for FastAPI + React Projects.  Using PostgreSQL, SQLAlchemy, and Docker

FastAPI + React ยท A cookiecutter template for bootstrapping a FastAPI and React project using a modern stack. Features FastAPI (Python 3.8) JWT authen

May 16, 2022
๐Ÿš€ Cookiecutter Template for FastAPI + React Projects. Using PostgreSQL, SQLAlchemy, and Docker
๐Ÿš€   Cookiecutter Template for FastAPI + React Projects.  Using PostgreSQL, SQLAlchemy, and Docker

FastAPI + React ยท A cookiecutter template for bootstrapping a FastAPI and React project using a modern stack. Features FastAPI (Python 3.8) JWT authen

Feb 19, 2021
Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker.

FastAPI + SQLModel + Alembic Sample FastAPI project that uses async SQLAlchemy, SQLModel, Postgres, Alembic, and Docker. Want to learn how to build th

May 10, 2022
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

May 2, 2021
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

May 14, 2022
Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

May 17, 2022
Starlette middleware for Prerender

Prerender Python Starlette Starlette middleware for Prerender Documentation: https://BeeMyDesk.github.io/prerender-python-starlette/ Source Code: http

Jul 27, 2020
Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automatically use request headers such as x-request-id or x-correlation-id.

starlette context Middleware for Starlette that allows you to store and access the context data of a request. Can be used with logging so logs automat

Feb 16, 2021
Prometheus integration for Starlette.

Starlette Prometheus Introduction Prometheus integration for Starlette. Requirements Python 3.6+ Starlette 0.9+ Installation $ pip install starlette-p

Feb 13, 2021
Dead simple CSRF security middleware for Starlette โญ and Fast API โšก

csrf-starlette-fastapi Dead simple CSRF security middleware for Starlette โญ and Fast API โšก Will work with either a <input type="hidden"> field or ajax

Apr 15, 2022
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.
:rocket: CLI tool for FastAPI. Generating new FastAPI projects & boilerplates made easy.

Project generator and manager for FastAPI. Source Code: View it on Github Features ?? Creates customizable project boilerplate. Creates customizable a

May 21, 2022