Giter Site home page Giter Site logo

luisluii / fastapiquickcrud Goto Github PK

View Code? Open in Web Editor NEW
250.0 6.0 32.0 32.68 MB

Generate CRUD methods in FastApi from an SQLAlchemy schema

Home Page: https://pypi.org/project/fastapi-quickcrud/

License: MIT License

Python 100.00%
postgresql postgres postgresql-database sqlalchemy-python sqlalchemy sqlalchemy-models sqlalchemy-orm-queries sqlalchemy-orm python python-library

fastapiquickcrud's People

Contributors

aebrahim avatar luisluii avatar wasdee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

fastapiquickcrud's Issues

Which FastApi version is required ?

Hi,

I would like to test your module which suits with my needs, but I'm facing out issue with tutorial/sample.py.
When I launch this, I get this error:

.\global_venv\lib\site-packages\fastapi_quickcrud\misc\schema_builder.py:263: UserWarning: The column of id has not default value and it is not nullable and in exclude_listit may throw error when you insert data 
  warnings.warn(
Traceback (most recent call last):
  File "./api/run3.py", line 23, in <module>
    crud_route_parent = generic_sql_crud_router_builder(
  File ".\global_venv\lib\site-packages\fastapi_quickcrud\crud_router.py", line 400, in crud_router_builder
    api = APIRouter(**router_kwargs)
TypeError: __init__() got an unexpected keyword argument 'sql_type'

It seems, the parameter sql_type is not expected by the FastApi class APIRouter. I checked quickly this class on FastAPI github, but I found no change for a while, missed I something ?

Best regards,

Postgres SqlAlchemy model with server defaults and different schema cannot be used

I am using a PostgreSQL 14.2-1 Windows x64 database using pgAdmin to which I am connecting to like so:

engine = create_async_engine(DATABASE_URL,
                             future=True, echo=True,
                             pool_use_lifo=True, pool_pre_ping=True, pool_recycle=7200
                             )
async_session_maker = sessionmaker(engine, class_=AsyncSession,
                                   expire_on_commit=False)

Base: DeclarativeMeta = declarative_base()

Using the following SQL script I have made the table dbo.Quote, like so:

CREATE TABLE dbo.Quote
(
    "ID" bigint GENERATED ALWAYS AS IDENTITY,
    "UUID" uuid NOT NULL DEFAULT gen_random_uuid(),
    "DateCreated" timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "DateModified" timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "IsActive" boolean NOT NULL DEFAULT TRUE,
    "Text" character varying(512) NOT NULL,
    "Author" character varying(126) DEFAULT 'Unknown',
    "Origin" character varying(126) DEFAULT 'Unknown',
    "UserID" bigint,
      CONSTRAINT "FK_Quote_Users" FOREIGN KEY ("UserID")
        REFERENCES auth.users ("ID") MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID,
    PRIMARY KEY ("ID")
);

ALTER TABLE IF EXISTS dbo.Quote
    OWNER to postgres;

I have also developed an SQLAlchemy model for the dbo.Quote postgres table:

class Quote(Base):
    __tablename__ = 'quote'
    __table_args__ = {'schema': 'dbo'}

    ID = Column(BigInteger, Identity(always=True, start=1, increment=1,
                                     minvalue=1, maxvalue=9223372036854775807, cycle=False, cache=1), primary_key=True)
    UUID = Column(UUID, nullable=False, server_default=text("gen_random_uuid()"))
    DateCreated = Column(DateTime(True), nullable=False, server_default=text("CURRENT_TIMESTAMP"))
    DateModified = Column(DateTime(True), nullable=False, server_default=text("CURRENT_TIMESTAMP"))
    IsActive = Column(Boolean, nullable=False, server_default=text("true"))
    Text = Column(String(512), nullable=False)
    Author = Column(String(126), server_default=text("'Unknown'::character varying"))
    Origin = Column(String(126), server_default=text("'Unknown'::character varying"))
    UserID = Column(BigInteger, ForeignKey('auth.users.ID'))
`

I am using an AsyncSession generator, such as you have exemplified in your simple example, namely:
`
async def get_transaction_session() -> AsyncSession:
    async with async_session_maker() as session:
        async with session.begin():
            yield session

and I am adding the crud router builder like so

QuoteCRUDRouter = crud_router_builder(db_model=Quote,
                                      prefix='/quote', tags=['Quote'],

                                      exclude_columns=['UUID','DateCreated','DateModified','IsActive'],
                                      crud_methods=[CrudMethods.CREATE_ONE],

                                      async_mode=True,
                                      autocommit=False,
                                      db_session=get_transaction_session,
                                      )

Finally, when I run

import uvicorn

if __name__ == "__main__":
    uvicorn.run("app.app:app",
                # host="0.0.0.0", # defaults to localhost
                log_level="info", reload=True)

I get the following error

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [14456] using watchgod
Process SpawnProcess-1:
Traceback (most recent call last):
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 297, in _bootstrap
    self.run()
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 99, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\uvicorn\subprocess.py", line 76, in subprocess_started
    target(sockets=sockets)
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\uvicorn\server.py", line 67, in run
    return asyncio.run(self.serve(sockets=sockets))
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 579, in run_until_complete
    return future.result()
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\uvicorn\server.py", line 74, in serve
    config.load()
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\uvicorn\config.py", line 458, in load
    self.loaded_app = import_from_string(self.app)
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\uvicorn\importer.py", line 21, in import_from_string
    module = importlib.import_module(module_str)
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\DELL\Documents\code\fastapi-learning\app\app.py", line 36, in <module>
    db_session=get_transaction_session,
  File "C:\Users\DELL\Documents\code\fastapi-learning\.env\lib\site-packages\fastapi_quickcrud\crud_router.py", line 114, in crud_router_builder
    sql_type, = asyncio.get_event_loop().run_until_complete(async_runner(db_session))
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 566, in run_until_complete
    self.run_forever()
  File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 521, in run_forever
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

Why am I getting this error?

Also, because SQLite does not have schemas, the __table_args__ in the SQLAlchemy model cause a problem, so what is the issue with that as well?

New feature discussion

After the foreign tree feature, I will focus on the Codegen feature, since #6 . Which make it easier for us to develop the API we want than now, you can modify the code to develop your own api based on this project

2022-03-07  9 36 03

The CodeGen feature will not generate with join_foreign_table field

13 mar 2022
The development is quite smooth and no blocking, I thing it can be released after 3 week

should we move some deps to dev deps?

poetry add fastapi-quickcrud                                                                            
Using version ^0.2.4 for fastapi-quickcrud

Updating dependencies
Resolving dependencies... (1.6s)

Because no versions of fastapi-quickcrud match >0.2.4,<0.3.0
 and fastapi-quickcrud (0.2.4) depends on uvicorn (0.17.0), fastapi-quickcrud (>=0.2.4,<0.3.0) requires uvicorn (0.17.0).
And because uvicorn (0.22.0) depends on uvicorn (0.22.0)
 and no versions of uvicorn match >0.22.0,<0.23.0, fastapi-quickcrud (>=0.2.4,<0.3.0) is incompatible with uvicorn (>=0.22.0,<0.23.0).
So, because backend depends on both uvicorn (^0.22.0) and fastapi-quickcrud (^0.2.4), version solving failed.

Use tree-like API for foreign keys.

This is such a cool package, but I ended up not using it because I wanted my API to look like this. I thought I would just leave it as a suggestion.

Suppose I have this in sqlalchemy:

import sqlalchemy as sa

class Account(Base):
    __tablename__ = "account"
    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)

class BlogPost(Base):
    __tablename__ = "blog_post"
    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    account_id = sa.Column(sa.Integer, sa.ForeignKey("account.id"), nullable=False)

class BlogComment(Base)
    __tablename__ = "blog_comment"
    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    blog_id = sa.Column(sa.Integer, sa.ForeignKey("blog_post.id"), nullable=False)

I might want routes like this:

GET /account/<account_id>/post/
{ list of blog posts by the author }
POST /account/<account_id>/post/
# creates a new blog post for the author
GET /post/<post_id>/comment
{ list of comments on the blog post }
GET /account<account_id>/post/<post_id>/comment
{ list of comments on the blog post - not sure how this is compared to the one above }

Anyways, just a thought!

Support for PostgreSQL data types

I created a few SQLAlchemy models containing some PostgreSQL data types such as
from sqlalchemy.dialects.postgresql import BYTEA, INTERVAL, JSONB, UUID

and I encountered the following exception
fastapi_quickcrud.misc.exceptions.ColumnTypeNotSupportedException: The type of column Blob (BYTEA) not supported yet

I haven't tested the other types except for Postgres BYTEA, however, there might be an issue for from sqlalchemy import ARRAY as well.

I want to build a ReactJS app in which I can upload a photo via a FastAPI endpoint and store it in the BYTEA field. Afterwards, I would also like to have a FastAPI endpoint that lists all of the BYTEA entries, which I can use to make a gallery in ReactJS.

class Photo(Base):
    __tablename__ = 'photo'
    __table_args__ = {'schema': 'dbo'}

    ID = Column(BigInteger,
                Identity(always=True, start=1, increment=1, minvalue=1, maxvalue=9223372036854775807, cycle=False,
                         cache=1), primary_key=True)
    UUID_ = Column('UUID', UUID, nullable=False, server_default=text('gen_random_uuid()'))
    DateCreated = Column(DateTime(True), nullable=False, server_default=text('CURRENT_TIMESTAMP'))
    DateModified = Column(DateTime(True), nullable=False, server_default=text('CURRENT_TIMESTAMP'))
    IsActive = Column(Boolean, nullable=False, server_default=text('true'))
    
    Blob = Column(BYTEA, nullable=False)

    ...


PhotoCRUDRouter = crud_router_builder(db_model=Photo,
                                      db_session=get_transaction_session,
                                      prefix='/quote', tags=['Photo'],
                                      exclude_columns=['UUID','DateCreated','DateModified','IsActive'],
                                      async_mode=True,
                                      autocommit=False,
                                      sql_type=SqlType.postgresql,
                                      )
app.include_router(PhotoCRUDRouter)

Extraneous `local_kw` added to mandatory arguments in swagger

Hi all, I've noticed that this seems to appear in the swagger documentation, I've not specified it

image

I've tried posting using thunder client, and without a 'local_kw" a 422 error is returned, however if it's specified we get Session.__init__() got an unexpected keyword argument 'local_kw'

Suggestion

Is it possible to write out all the routers into a python file?
Which would be great while we add more end points for the tags

Docs page cannot open

Root cause:
Compatibility issue between latest version of pydantic and dataclasses

pip install error

Environment: Windows 10 + Python 3.10.1 (x64) (Issue also with 3.7)

Facing the following error while trying to install via pip:

pip install fastapi_quickcrud==0.0.2
Collecting fastapi_quickcrud==0.0.2
  Using cached fastapi_quickcrud-0.0.2.tar.gz (37 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  ERROR: Command errored out with exit status 1:
   command: 'c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\scripts\python.exe' 'c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\Rob-Work\A
ppData\Local\Temp\tmp9kjdrdoz'
       cwd: C:\Users\Rob-Work\AppData\Local\Temp\pip-install-v4nip7h_\fastapi-quickcrud_9c5e5ca136504d1185d5c4dd9e880cca
  Complete output (16 lines):
  Traceback (most recent call last):
    File "c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 363, in <module>
      main()
    File "c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 345, in main
      json_out['return_val'] = hook(**hook_input['kwargs'])
    File "c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 164, in prepare_metadata_for_build_wheel
      return hook(metadata_directory, config_settings)
    File "C:\Users\Rob-Work\AppData\Local\Temp\pip-build-env-4fol05yn\overlay\Lib\site-packages\poetry\core\masonry\api.py", line 44, in prepare_metadata_for_build_wheel
      builder = WheelBuilder(poetry)
    File "C:\Users\Rob-Work\AppData\Local\Temp\pip-build-env-4fol05yn\overlay\Lib\site-packages\poetry\core\masonry\builders\wheel.py", line 57, in __init__
      super(WheelBuilder, self).__init__(poetry, executable=executable)
    File "C:\Users\Rob-Work\AppData\Local\Temp\pip-build-env-4fol05yn\overlay\Lib\site-packages\poetry\core\masonry\builders\builder.py", line 85, in __init__
      self._module = Module(
    File "C:\Users\Rob-Work\AppData\Local\Temp\pip-build-env-4fol05yn\overlay\Lib\site-packages\poetry\core\masonry\utils\module.py", line 63, in __init__
      raise ModuleOrPackageNotFound(
  poetry.core.masonry.utils.module.ModuleOrPackageNotFound: No file/folder found for package fastapiquickcrud
  ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/47/a3/8af39857ce62afcb563fd700be27954ad9d28f6ae19f3e8570182edbf604/fastapi_quickcrud-0.0.2.tar.gz#sha256=e72fd906359072e48a67745e9c4be19b4f1ce92a43d0d3b5c2d2685077b3e5a5 (from https://pypi.org/simple/fasta
pi-quickcrud/) (requires-python:>=3.7). Command errored out with exit status 1: 'c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\scripts\python.exe' 'c:\users\rob-work\pycharmprojects\xconnect.agent\venv310\lib\site-packages\pip\_vendor\pep517\in_process\_
in_process.py' prepare_metadata_for_build_wheel 'C:\Users\Rob-Work\AppData\Local\Temp\tmp9kjdrdoz' Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement fastapi_quickcrud==0.0.2 (from versions: 0.0.1a1, 0.0.1a2, 0.0.1a3, 0.0.1a4, 0.0.1a5, 0.0.1a6, 0.0.1a7, 0.0.1a8, 0.0.1a9, 0.0.1a10, 0.0.1a11, 0.0.1a12, 0.0.1a13, 0.0.1a14, 0.0.1a15, 0.0.1a16, 0.0.1a17, 
0.0.1a18, 0.0.1a19, 0.0.1, 0.0.2)
ERROR: No matching distribution found for fastapi_quickcrud==0.0.2

How to run the FastAPIQuickCRUD is NOT Clear

Dear Sir,
I have installed the FastAPIQuickCRUD and also generator.

BUT How to run and which path IS NOT clear in the README File.

Please guide

Also Where should the user setup the variable SQLALCHEMY

Please reply

Regards,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.