Code Monkey home page Code Monkey logo

starlette-web's Introduction

starlette_web

starlette_web is a native-asynchronous web-framework, based on Starlette and inspired by Django and its ecosystem. It aims to provide most of the relevant features of Django in async-all-the-way setting.

Its priorities, from most important to least important, are as follows:

  • Providing a strict ecosystem - all parts of framework are aimed to work well together and follow same ideas. In a way, this goes against idea of mini-frameworks like Starlette, which favor a lot of contrib plug-ins, written by different authors. Developer must follow the conventions of the framework in most cases.
  • Robustness - starlette_web is written with anyio and aims to follow principles of structured concurrency.
  • Feature completeness - while the aim is not to cover all the Django ecosystem (especially, because a lot of it is legacy), many useful libraries are included.
  • Cross-platform support - most of the features are supported for both POSIX and Windows systems. However, a number of contrib modules aim specifically at certain OS, and obviously it's mostly Linux.
  • Speed - while framework is being used in multiple projects without speed issues, speed is not properly benchmarked. Probably, the framework is slower than all other async Python frameworks, though not by a large amount.

SQLAlchemy is used as framework's database toolkit and ORM.
Marshmallow is used for (de)serialization in API.
OpenAPI documentation (redoc) can be autogenerated with apispec contrib module.

The framework is not well suited for novice users. It assumes prior knowledge of Django and async development in Python.

The framework is in active development stage, so expect some breaking changes.

Installation, usage and supported features

Installation and deploy instructions are in docs/howto section.

For supported features, see docs/README.md section.

See tests for more examples of usage.

Code borrowing

starlette-web borrows/adopts a lot of code from other open-source Python libraries. List of libraries is given in the docs, with links to repositories and licences.

starlette-web's People

Contributors

dmitryburnaev avatar dolamroth avatar merser4 avatar toiletsandpaper avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar

Forkers

toiletsandpaper

starlette-web's Issues

Rework contrib.apispec

Some ideas may be fetched from:

Targets:

  • add introspection for path parameters
  • inherit from Maschmallow.Schema for custom registering schema
  • additional parameters for Schema, such as description
  • possibility to add additional schemas "method_name_schema", such as "post_request_schema"
  • process scopes for security schemas (or just stick to permission classes ?)
  • cache OpenApiView (with #5)
  • etc

Issues at startup

  • Default installed apps do not match default libraries, installed without extra dependencies (comment out default installed apps)
  • Default asgi.py in project root must setdefault STARLETTE_SETTINGS_MODULE before call to get_app
  • If there is import error in installed apps. app is not getting imported, resulting in incorrect error message. Maybe import modules in initialize method?
  • Alembic errors on migrate/makemigrations are incomprehencible. Maybe add makemigrations/migrate management commands?

Anyio compatability

Starlette itself is anyio-compatible. However, underlying implementations of low-level libraries are mostly not.

  • With current scheme, SQLAlchemy is main core part, which is not anyio-compatible.
  • Anyio-compatible websockets are available, if using hypercorn (beta, as of right now) + anysocks/asyncwebsockets. However, so far these are less reliable/feature-complete than asyncio implementation.
  • There is no DB engines (at least for Postgres) with anyio, but there are separate implementations for asyncio and trio
    • pg-purepy exists, but it is not feature-complete
    • trio-pg is just wrapper around asyng pg
  • Same for redis / mqtt / rmq
  • There is anyio implementation for SMTP https://pypi.org/project/smtpproto/

Desireable contrib libraries to have around for production

Move to Tortoise ORM and fastapi-admin

All pros and cons must be carefully decided.

Requirements:

Additional requirements:

FastAPI-admin seems to be more feature complete, than starlette_admin, but has a hard requirement for Tortoise ORM.

Additional point to consider is that Tortoise ORM basically autocommit all-the-way-through, similar to Django ORM.

  • Pros: simplicity (i.e., managing files with SQLAlchemy in a non-autocommit mode is a daunting task, to say at least https://github.com/jowilf/sqlalchemy-file), no need to pass session in every query, easier processing of triggers
  • Cons: worse performance, worse data isolation

Will probably require to move from marshmallow to pydantic, but needs consideration. Pydantic is widely reported to be faster and more feature complete, but marshmallow is said to be more customizable. However, it was pointed out, that Pydantic reliance on Python typing features may be a limitation in certain tasks.

Refactor settings.DATABASE and settings.DATABASE_DSN

While at it, also move from initializing app with session maker in each command, but provide a global application object.

Redo settings.DATABASE -> settings.DATABASES and provide global variable connections, in the same manner as Django

ConnectionHandler is a wrapper around project sessionmaker(s). This will be a step for #21
https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html

# using example from "Custom Vertical Partitioning"

import random

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlalchemy.orm import Session

# construct async engines w/ async drivers
engines = {
    'leader':create_async_engine("sqlite+aiosqlite:///leader.db"),
    'other':create_async_engine("sqlite+aiosqlite:///other.db"),
    'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"),
    'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"),
}

class RoutingSession(Session):
    def get_bind(self, mapper=None, clause=None, **kw):
        # within get_bind(), return sync engines
        if mapper and issubclass(mapper.class_, MyOtherClass):
            return engines['other'].sync_engine
        elif self._flushing or isinstance(clause, (Update, Delete)):
            return engines['leader'].sync_engine
        else:
            return engines[
                random.choice(['follower1','follower2'])
            ].sync_engine

# apply to AsyncSession using sync_session_class
AsyncSessionMaker = async_sessionmaker(
    sync_session_class=RoutingSession
)

Support validation for constance

Validation for constance has sense if it is used in admin panel, and has not much sense otherwise.

This issue requires the following task to be performed before:

  • adapt admin panel into framework
  • make custom admin page for constance
  • allow custom widgets for admin-panel and various data types

Validation should be done by making base class ConstanceType, which defines .clear() method, and widget for admin-panel.

Fix CamelCaseStarletteParser

    async def _async_load_location_data(self, schema, req, location):
        data = await super()._async_load_location_data(schema, req, location)
        return underscoreize(data, no_underscore_before_number=True)

Develop common.files

Targets for 0.2:

  • Filesystem storage
  • SFTPStorage (with aiosftp)
  • S3 Storage (with aioboto3/aiobotocore)

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.