简体   繁体   中英

Python FastApi GET loop

Good day for everyone, its my first request in this service, so i am glad to see all of you^^

I am have some trouble with FastApi.

I have raspberry pi 3, and barcode scanner with USB interface, i now how get data with while loop, but i am need to get this data from request, so i am write async script for this:

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from services.barcode import barcode_reader

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
barcode = ""

async def get_barcode():
    try:
        while True:
            # barcode = barcode_reader()
            if barcode != "":
                return barcode
    except KeyboardInterrupt:
        pass

@app.get("/barcode")
async def read_barcode():
    return await get_barcode()
    

@app.post("/barcode/{barcodeStr}")
async def write_barcode(barcodeStr: str):
    barcode = barcodeStr
    return "success"

But when I make a GET request, I cannot put data with a POST request, in the future I will have many more methods that will be executed constantly and I would not like one method to block the entire API.

Help me please ^^

Just looking at the code you've provided, I'm not sure how you expect the barcode reader to work. You're not providing it with input, so I can't see how it would be able to process the barcode.

You are taking in the barcodeStr path parameter in your POST route, so I'm assuming that's how you want your service to work. It also seems that your get_barcode coroutine doesn't use return a Future or Task. In that case, you're correct in that it would most likely be a blocking operation.

If your barcode reader service is calling an external API or is an IO-bound function in general, then using the async/await syntax can avoid blocking the event loop.

Your code could potentially be re-written like so:

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from services.barcode import barcode_reader

app = FastAPI()
app.add_middleware(
    CORSMiddleware, 
    allow_origins=["*"], 
    allow_credentials=True, 
    allow_methods=["*"], 
    allow_headers=["*"]
)

async def process_barcode(barcode_str: str) -> int:
    """
    Assume this returns a product id.
    """
    try:
        while True:
            barcode_id = await barcode_reader(barcode_str)
            if barcode_id:
                return barcode_id
    except KeyboardInterrupt:
        pass
    

@app.post("/barcode/{barcodeStr}", response_model=int)
async def write_barcode(barcodeStr: str):
    product_id = await process_barcode(barcodeStr)
    return product_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM