kandi background
Explore Kits

starlette | The little ASGI framework that shines 🌟 | Reactive Programming library

 by   encode Python Version: 0.19.1 License: BSD-3-Clause

 by   encode Python Version: 0.19.1 License: BSD-3-Clause

Download this library from

kandi X-RAY | starlette Summary

starlette is a Python library typically used in Programming Style, Reactive Programming applications. starlette has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can install using 'pip install starlette' or download it from GitHub, PyPI.
Starlette is a lightweight ASGI framework/toolkit, which is ideal for building async web services in Python.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • starlette has a highly active ecosystem.
  • It has 6869 star(s) with 602 fork(s). There are 113 watchers for this library.
  • There were 3 major release(s) in the last 12 months.
  • There are 39 open issues and 554 have been closed. On average issues are closed in 345 days. There are 26 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of starlette is 0.19.1
starlette Support
Best in #Reactive Programming
Average in #Reactive Programming
starlette Support
Best in #Reactive Programming
Average in #Reactive Programming

quality kandi Quality

  • starlette has 0 bugs and 0 code smells.
starlette Quality
Best in #Reactive Programming
Average in #Reactive Programming
starlette Quality
Best in #Reactive Programming
Average in #Reactive Programming

securitySecurity

  • starlette has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • starlette code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
starlette Security
Best in #Reactive Programming
Average in #Reactive Programming
starlette Security
Best in #Reactive Programming
Average in #Reactive Programming

license License

  • starlette is licensed under the BSD-3-Clause License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
starlette License
Best in #Reactive Programming
Average in #Reactive Programming
starlette License
Best in #Reactive Programming
Average in #Reactive Programming

buildReuse

  • starlette releases are available to install and integrate.
  • Deployable package is available in PyPI.
  • Build file is available. You can build the component from source.
  • Installation instructions, examples and code snippets are available.
  • starlette saves you 3888 person hours of effort in developing the same functionality from scratch.
  • It has 8930 lines of code, 1006 functions and 64 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
starlette Reuse
Best in #Reactive Programming
Average in #Reactive Programming
starlette Reuse
Best in #Reactive Programming
Average in #Reactive Programming
Top functions reviewed by kandi - BETA

kandi has reviewed starlette and discovered the below as its top functions. This is intended to give you an instant insight into starlette implemented functionality, and help decide if they suit your requirements.

  • Send a GZip message to the client
    • Seek to the given offset
    • Run a function in a threadpool
    • Add the vary header
  • Return a URLPath for this mount
    • Return a new URL
    • Replace parameters in path
  • Register a route
    • Add a route to the router
  • Define a route
    • Add a route to the blueprint
  • Create a URL path for this endpoint
    • Create a URLPath for this path
      • Return cookies
        • Start startup
          • Decorator to add an exception handler
            • Decorate a function to register an event handler
              • Create a Jinja2 environment
                • Wrap a function in a threadpool
                  • Register a websocket route
                    • Decorate a websocket route
                      • Decorator to register a middleware
                        • Parse the given scope
                          • Sends a message
                            • Construct a URL path for this route
                              • Close all files

                                Get all kandi verified functions for this library.

                                Get all kandi verified functions for this library.

                                starlette Key Features

                                A lightweight, low-complexity HTTP web framework.

                                WebSocket support.

                                In-process background tasks.

                                Startup and shutdown events.

                                Test client built on requests.

                                CORS, GZip, Static Files, Streaming responses.

                                Session and Cookie support.

                                100% test coverage.

                                100% type annotated codebase.

                                Few hard dependencies.

                                Compatible with asyncio and trio backends.

                                Great overall performance against independant benchmarks.

                                starlette Examples and Code Snippets

                                See all related Code Snippets

                                Installation

                                copy iconCopydownload iconDownload
                                $ pip3 install starlette
                                

                                Example

                                copy iconCopydownload iconDownload
                                from starlette.applications import Starlette
                                from starlette.responses import JSONResponse
                                from starlette.routing import Route
                                
                                
                                async def homepage(request):
                                    return JSONResponse({'hello': 'world'})
                                
                                routes = [
                                    Route("/", endpoint=homepage)
                                ]
                                
                                app = Starlette(debug=True, routes=routes)
                                

                                Framework or Toolkit

                                copy iconCopydownload iconDownload
                                from starlette.responses import PlainTextResponse
                                
                                
                                async def app(scope, receive, send):
                                    assert scope['type'] == 'http'
                                    response = PlainTextResponse('Hello, world!')
                                    await response(scope, receive, send)
                                

                                How to add depedency overriding in FastAPI testing

                                copy iconCopydownload iconDownload
                                @pytest.fixture()
                                def client():
                                    app.dependency_overrides[ManagerImp.create_record] = over_create_record
                                    with TestClient(app) as test_client:
                                        yield test_client
                                
                                def get_manager():
                                    return ManagerImp()
                                
                                @cbv(router)
                                class ControllerImp(Controller):
                                    manager = Depends(get_manager)
                                
                                app.dependency_overrides[get_manager] = lambda: return MyFakeManager()
                                
                                def get_manager():
                                    return ManagerImp()
                                
                                @cbv(router)
                                class ControllerImp(Controller):
                                    manager = Depends(get_manager)
                                
                                app.dependency_overrides[get_manager] = lambda: return MyFakeManager()
                                

                                dockerfile run in github, having module not found issue

                                copy iconCopydownload iconDownload
                                # pull the official docker image
                                FROM python:3.9.4-slim
                                
                                # install requirements
                                COPY requirements.txt .
                                RUN pip install -r requirements.txt
                                
                                # copy project
                                COPY . .
                                
                                EXPOSE 8715
                                
                                
                                CMD ["python", "-m", "server"]
                                
                                name: Docker Image CI
                                
                                on:
                                  push:
                                    branches: [ master ]
                                  pull_request:
                                    branches: [ master ]
                                
                                jobs:
                                
                                  build:
                                
                                    runs-on: ubuntu-latest
                                    
                                
                                    steps:
                                    - name: Login to GitHub Container Registry
                                      uses: docker/login-action@v1
                                      with:
                                        registry: ghcr.io
                                        username: ${{ github.actor }}
                                        password: ${{ secrets.DOCKER_TOKEN }}
                                    
                                    
                                    - uses: actions/checkout@v3
                                    - name: Build the Docker image
                                      run: |
                                        cd backend/copium_api/
                                        docker build --tag app:latest .
                                        docker run app:latest
                                        docker push app:latest
                                
                                # pull the official docker image
                                FROM python:3.9.4-slim
                                
                                # install requirements
                                COPY requirements.txt .
                                RUN pip install -r requirements.txt
                                
                                # copy project
                                COPY . .
                                
                                EXPOSE 8715
                                
                                
                                CMD ["python", "-m", "server"]
                                
                                name: Docker Image CI
                                
                                on:
                                  push:
                                    branches: [ master ]
                                  pull_request:
                                    branches: [ master ]
                                
                                jobs:
                                
                                  build:
                                
                                    runs-on: ubuntu-latest
                                    
                                
                                    steps:
                                    - name: Login to GitHub Container Registry
                                      uses: docker/login-action@v1
                                      with:
                                        registry: ghcr.io
                                        username: ${{ github.actor }}
                                        password: ${{ secrets.DOCKER_TOKEN }}
                                    
                                    
                                    - uses: actions/checkout@v3
                                    - name: Build the Docker image
                                      run: |
                                        cd backend/copium_api/
                                        docker build --tag app:latest .
                                        docker run app:latest
                                        docker push app:latest
                                

                                Send a fastAPI response without redirecting from HTML form post

                                copy iconCopydownload iconDownload
                                from fastapi import FastAPI, Form, Request
                                from fastapi.templating import Jinja2Templates
                                
                                app = FastAPI()
                                templates = Jinja2Templates(directory="templates")
                                
                                @app.post("/submit")
                                async def submit(request: Request, taskname: str = Form(...), tasknumber: int = Form(...)):
                                    return f'Super resolution completed! task {tasknumber} of {taskname} done'
                                
                                @app.get("/")
                                async def index(request: Request):
                                    return templates.TemplateResponse("index.html", {"request": request})
                                
                                <script type="text/javascript">
                                function submitForm() {
                                    var formElement = document.getElementById('myForm');
                                    var data = new FormData(formElement);
                                
                                    fetch('/submit', {
                                          method: 'POST',
                                          body: data,
                                        })
                                        .then(response => response.text())
                                        .then(data => {
                                          document.getElementById("response_area").innerHTML = data;
                                        })
                                        .catch(error => {
                                          console.error(error);
                                        });
                                }
                                </script>
                                
                                <html>
                                   <head>
                                      <h1><b>Super resolution image treatment</b></h1>   
                                      <body>
                                        <form method="post" id="myForm">
                                            <label for="taskname" style="font-size: 20px">Task name*:</label>
                                            <input type="text" name="taskname" id="taskname" />
                                            <label for="tasknumber" style="font-size: 20px">Task number*:</label>
                                            <input type="number" name="tasknumber" id="tasknumber" />
                                            <b><p style="display:inline"> * Cannot be null</p></b>
                                            <input type="button" value="Start" onclick="submitForm()">
                                         </form>
                                         <div id="response_area"><div>
                                      </body>
                                   </head>
                                </html>
                                
                                from fastapi import FastAPI, Form, Request
                                from fastapi.templating import Jinja2Templates
                                
                                app = FastAPI()
                                templates = Jinja2Templates(directory="templates")
                                
                                @app.post("/submit")
                                async def submit(request: Request, taskname: str = Form(...), tasknumber: int = Form(...)):
                                    return f'Super resolution completed! task {tasknumber} of {taskname} done'
                                
                                @app.get("/")
                                async def index(request: Request):
                                    return templates.TemplateResponse("index.html", {"request": request})
                                
                                <script type="text/javascript">
                                function submitForm() {
                                    var formElement = document.getElementById('myForm');
                                    var data = new FormData(formElement);
                                
                                    fetch('/submit', {
                                          method: 'POST',
                                          body: data,
                                        })
                                        .then(response => response.text())
                                        .then(data => {
                                          document.getElementById("response_area").innerHTML = data;
                                        })
                                        .catch(error => {
                                          console.error(error);
                                        });
                                }
                                </script>
                                
                                <html>
                                   <head>
                                      <h1><b>Super resolution image treatment</b></h1>   
                                      <body>
                                        <form method="post" id="myForm">
                                            <label for="taskname" style="font-size: 20px">Task name*:</label>
                                            <input type="text" name="taskname" id="taskname" />
                                            <label for="tasknumber" style="font-size: 20px">Task number*:</label>
                                            <input type="number" name="tasknumber" id="tasknumber" />
                                            <b><p style="display:inline"> * Cannot be null</p></b>
                                            <input type="button" value="Start" onclick="submitForm()">
                                         </form>
                                         <div id="response_area"><div>
                                      </body>
                                   </head>
                                </html>
                                

                                Python Pydantic Error: TypeError: __init__() takes exactly 1 positional argument (2 given)

                                copy iconCopydownload iconDownload
                                token_data = schemas.TokenData(username=username)
                                

                                fastapi (starlette) RedirectResponse redirect to post instead get method

                                copy iconCopydownload iconDownload
                                    # ...
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                from fastapi import FastAPI, APIRouter, Request
                                from fastapi.responses import RedirectResponse, HTMLResponse
                                
                                
                                router = APIRouter()
                                
                                @router.get('/form')
                                def form():
                                    return HTMLResponse("""
                                    <html>
                                    <form action="/event/create" method="POST">
                                    <button>Send request</button>
                                    </form>
                                    </html>
                                    """)
                                
                                @router.post('/create')
                                async def event_create(
                                        request: Request
                                ):
                                    event = {"id": 123}
                                    redirect_url = request.url_for('get_event', **{'pk': event['id']})
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                
                                @router.get('/{pk}')
                                async def get_event(
                                        request: Request,
                                        pk: int,
                                ):
                                    return f'<html>oi pk={pk}</html>'
                                
                                app = FastAPI(title='Test API')
                                
                                app.include_router(router, prefix="/event")
                                
                                uvicorn --reload --host 0.0.0.0 --port 3000 example:app
                                
                                    # ...
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                from fastapi import FastAPI, APIRouter, Request
                                from fastapi.responses import RedirectResponse, HTMLResponse
                                
                                
                                router = APIRouter()
                                
                                @router.get('/form')
                                def form():
                                    return HTMLResponse("""
                                    <html>
                                    <form action="/event/create" method="POST">
                                    <button>Send request</button>
                                    </form>
                                    </html>
                                    """)
                                
                                @router.post('/create')
                                async def event_create(
                                        request: Request
                                ):
                                    event = {"id": 123}
                                    redirect_url = request.url_for('get_event', **{'pk': event['id']})
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                
                                @router.get('/{pk}')
                                async def get_event(
                                        request: Request,
                                        pk: int,
                                ):
                                    return f'<html>oi pk={pk}</html>'
                                
                                app = FastAPI(title='Test API')
                                
                                app.include_router(router, prefix="/event")
                                
                                uvicorn --reload --host 0.0.0.0 --port 3000 example:app
                                
                                    # ...
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                from fastapi import FastAPI, APIRouter, Request
                                from fastapi.responses import RedirectResponse, HTMLResponse
                                
                                
                                router = APIRouter()
                                
                                @router.get('/form')
                                def form():
                                    return HTMLResponse("""
                                    <html>
                                    <form action="/event/create" method="POST">
                                    <button>Send request</button>
                                    </form>
                                    </html>
                                    """)
                                
                                @router.post('/create')
                                async def event_create(
                                        request: Request
                                ):
                                    event = {"id": 123}
                                    redirect_url = request.url_for('get_event', **{'pk': event['id']})
                                    return RedirectResponse(redirect_url, status_code=303)
                                
                                
                                @router.get('/{pk}')
                                async def get_event(
                                        request: Request,
                                        pk: int,
                                ):
                                    return f'<html>oi pk={pk}</html>'
                                
                                app = FastAPI(title='Test API')
                                
                                app.include_router(router, prefix="/event")
                                
                                uvicorn --reload --host 0.0.0.0 --port 3000 example:app
                                
                                from fastapi import APIRouter, FastAPI, Request, status
                                from fastapi.responses import RedirectResponse, HTMLResponse
                                
                                router = APIRouter()
                                
                                # Endpoint can be accessed at http://127.0.0.1:8000/event/
                                @router.get('/', response_class=HTMLResponse)
                                async def event_create_form(request: Request):
                                    html_content = """
                                    <html>
                                       <body>
                                          <h1>Create an event</h1>
                                          <form method="POST" action="/event/create">
                                             <input type="submit" value="Create Event">
                                          </form>
                                       </body>
                                    </html>
                                    """
                                    return HTMLResponse(content=html_content, status_code=200)
                                    
                                @router.post('/create')
                                async def event_create(request: Request):
                                    event = {"id": 1}
                                    redirect_url = request.url_for('get_event', **{'pk': event['id']})
                                    return RedirectResponse(redirect_url, status_code=status.HTTP_303_SEE_OTHER)    
                                
                                @router.get('/{pk}')
                                async def get_event(request: Request, pk: int):
                                    return {"pk": pk}
                                
                                
                                app = FastAPI()
                                app.include_router(router, prefix="/event")
                                

                                React, getting Uncaught TypeError: Cannot read properties of undefined (reading 'map') on some refreshes

                                copy iconCopydownload iconDownload
                                const [file, setFile] = useState([]);
                                

                                Docker container is starting but isnt giving any response using FastApi

                                copy iconCopydownload iconDownload
                                docker run -dp <host_port>:<container_port> <image>
                                

                                Keep getting CORS policy: No 'Access-Control-Allow-Origin' even with FastAPI CORSMiddleware

                                copy iconCopydownload iconDownload
                                SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
                                
                                ...
                                
                                # Dependency
                                def get_db():
                                    db = SessionLocal()
                                    try:
                                        yield db
                                    finally:
                                        db.close()
                                
                                ...
                                
                                @app.post("/users/{user_id}/items/", response_model=schemas.Item)
                                def create_item_for_user(..., db: Session = Depends(get_db)):
                                    return crud.create_user_item(db=db, item=item, user_id=user_id)
                                

                                FastAPI Hello World Example: Internal Server Error

                                copy iconCopydownload iconDownload
                                ERROR: Cannot install -r requirements.txt (line 5) and starlette==0.18.0
                                because these package versions have conflicting dependencies.
                                
                                The conflict is caused by:
                                The user requested starlette==0.18.0
                                fastapi 0.73.0 depends on starlette==0.17.1
                                

                                Use trio nursery as a generator for Sever Sent Events with FastAPI?

                                copy iconCopydownload iconDownload
                                @router.websocket('/stream')
                                async def runTasks(
                                        websocket: WebSocket
                                ):
                                    # Initialise websocket
                                    await websocket.accept()
                                
                                    # Receive data
                                    tasks = await websocket.receive_json()
                                
                                    async with trio.open_nursery() as nursery:
                                        limit = trio.CapacityLimiter(10)
                                        for task in tasks:
                                            nursery.start_soon(run_task, limit, task, websocket)
                                

                                See all related Code Snippets

                                Community Discussions

                                Trending Discussions on starlette
                                • How to add depedency overriding in FastAPI testing
                                • dockerfile run in github, having module not found issue
                                • Send a fastAPI response without redirecting from HTML form post
                                • Python Pydantic Error: TypeError: __init__() takes exactly 1 positional argument (2 given)
                                • fastapi (starlette) RedirectResponse redirect to post instead get method
                                • React, getting Uncaught TypeError: Cannot read properties of undefined (reading 'map') on some refreshes
                                • Docker container is starting but isnt giving any response using FastApi
                                • Keep getting CORS policy: No 'Access-Control-Allow-Origin' even with FastAPI CORSMiddleware
                                • ModuleNotFoundError when running docker and poetry
                                • FastAPI Hello World Example: Internal Server Error
                                Trending Discussions on starlette

                                QUESTION

                                How to add depedency overriding in FastAPI testing

                                Asked 2022-Apr-12 at 07:52

                                I'm new to FastAPI, I have implemented everything but when it comes to testing the API I can't override a dependency.

                                Here is my code:

                                test_controller.py

                                import pytest
                                from starlette.testclient import TestClient
                                from app.main import app
                                from app.core.manager_imp import ManagerImp
                                
                                
                                @pytest.fixture()
                                def client():
                                    with TestClient(app) as test_client:
                                        yield test_client
                                
                                
                                async def over_create_record():
                                    return {"msg": "inserted successfully"}
                                
                                app.dependency_overrides[ManagerImp.create_record] = over_create_record
                                
                                def test_post(client):
                                    data = {"name": "John", "email": "john@abc.com"}
                                    response = client.post("/person/", json=data)
                                    assert response.status_code == 200
                                    assert response.json() == {"msg": "inserted successfully"}
                                

                                controller.py

                                from app.controllers.v1.controller import Controller
                                from fastapi import status, HTTPException
                                from app.models.taxslip import Person
                                from app.core.manager_imp import ManagerImp
                                from app.core.duplicate_exception import DuplicateException
                                from fastapi_utils.cbv import cbv
                                from fastapi_utils.inferring_router import InferringRouter
                                
                                router = InferringRouter(tags=["Person"]) 
                                @cbv(router)
                                class ControllerImp(Controller):
                                    manager = ManagerImp()
                                
                                    @router.post("/person/")
                                    async def create_record(self, person: Person):
                                        """
                                        Person: A person object
                                        returns response if the person was inserted into the database
                                        """
                                        try:
                                            response = await self.manager.create_record(person.dict())
                                            return response
                                        except DuplicateException as e:
                                            return e
                                

                                manager_imp.py

                                from fastapi import HTTPException, status
                                from app.database.database_imp import DatabaseImp
                                from app.core.manager import Manager
                                from app.core.duplicate_exception import DuplicateException
                                
                                
                                class ManagerImp(Manager):
                                    database = DatabaseImp()
                                    async def create_record(self, taxslip: dict):
                                        try:
                                            response = await self.database.add(taxslip)
                                            return response
                                        except DuplicateException:
                                            raise HTTPException(409, "Duplicate data")
                                

                                In testing I want to override create_record function from ManagerImp class so that I could get this response {"msg": "inserted successfully"}. Basically, I want to mock ManagerImp create_record function. I have tried as you can see in test_controller.py but I still get the original response.

                                ANSWER

                                Answered 2022-Apr-12 at 05:59

                                I think you should put your app.dependency_overrides inside the function with @pytest.fixture. Try to put it inside your client().

                                @pytest.fixture()
                                def client():
                                    app.dependency_overrides[ManagerImp.create_record] = over_create_record
                                    with TestClient(app) as test_client:
                                        yield test_client
                                

                                because every test will run the fresh app, meaning it will reset everything from one to another test and only related things bind with the pytest will effect the test.

                                Source https://stackoverflow.com/questions/71837555

                                Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                Vulnerabilities

                                No vulnerabilities reported

                                Install starlette

                                You'll also want to install an ASGI server, such as uvicorn, daphne, or hypercorn.

                                Support

                                For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                                DOWNLOAD this Library from

                                Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                over 430 million Knowledge Items
                                Find more libraries
                                Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                Explore Kits

                                Save this library and start creating your kit

                                Share this Page

                                share link
                                Consider Popular Reactive Programming Libraries
                                Try Top Libraries by encode
                                Compare Reactive Programming Libraries with Highest Support
                                Compare Reactive Programming Libraries with Highest Quality
                                Compare Reactive Programming Libraries with Highest Security
                                Compare Reactive Programming Libraries with Permissive License
                                Compare Reactive Programming Libraries with Highest Reuse
                                Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                                over 430 million Knowledge Items
                                Find more libraries
                                Reuse Solution Kits and Libraries Curated by Popular Use Cases
                                Explore Kits

                                Save this library and start creating your kit

                                • © 2022 Open Weaver Inc.