Where communities thrive

  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
    Basically I'm looking for a current_user in a websocket context
    Phil Jones
    Not yet, see pgjones/quart-auth#9
    thank you!
    Penguin Master

    @pgjones sorry for the late reply, but here's my code:

    from quart import Quart, websocket
    from functools import wraps
    import asyncio
    app = Quart(__name__)
    connected_websockets = set()
    def collect_websocket(func):
        async def wrapper(*args, **kwargs):
            global connected_websockets
            queue = asyncio.Queue()
                return await func(queue, *args, **kwargs)
        return wrapper
    async def broadcast(message):
        for queue in connected_websockets:
            queue.put_nowait("New connection")
    async def ws(queue):
        while True:
            data = await websocket.receive()
            await broadcast(data)
    if __name__ == "__main__":
        app.run(host="", port=8080)

    You can ignore the host="", that's just there because it's on replit

    Phil Jones
    In this code you receive data from the websocket connections and place "New connection" (ignoring the data) on a queue, but you never read the data from the queue. The connected_websockets set will contain a queue for each websocket connection though. What are you hoping will happen?
    Phil Jones
    @7185 see pgjones/quart-auth@68b6786 - could you say if this solves your need?
    @pgjones yes, this is exactly what I wanted, thank you!

    Hi, everyone.
    I've just started using quart for my tests, I'm using this simple code :

    def start_app():
        from keyboard import press
        import quart
        app = quart.Quart(__name__)
        @app.route("/api", methods=["POST"])
        async def json():
            return {"hello": "quart world"}

    and it's working fine, except that I always get these unwanted messages when it starts:

    • Serving Quart app 'main'
    • Environment: production
    • Please use an ASGI server (e.g. Hypercorn) directly in production
    • Debug mode: False
    • Running on http://myhost:5000 (CTRL + C to quit)
      [2021-04-05 18:19:07,784] Running on http://myhost:5000 (CTRL + C to quit).

    Can anyone please tell me how to disable them?
    I've tried

    logging.getLogger('app.serving').disabled = True
    logging.getLogger('quart.serving').disabled = True
    logging.getLogger('app.serving').propagate = False
    logging.getLogger('quart.serving').propagate = False

    nothing helps

    Phil Jones
    Probably best for you to make use of the run_task method to fully control how quart runs
    Thank you, I see there are some options for changing the look of the logging:
    config = HyperConfig()
    config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s"
    config.accesslog = create_serving_logger()
    but how can I disable the logging entirely (temporarily)?
    Phil Jones
    I think if you remove the accesslog line it will disable all loggers

    thank you, it worked in combination with
    sys.stdout = open(os.devnull, 'w')
    sys.stderr = open(os.devnull, "w")

    but I actually wanted to start this function in background via this code:

    import multiprocess as mp
    proc = mp.Process(target=start_app, args=())

    and that still doesn't work because besides those lines I'm also getting an empty line in console (the app waiting for the requests I guess).

    Is there a way to start/stop the quart app in background?

    Phil Jones
    Yea, you can use asyncio.run(app.run_task(...)) in the start_app function
    No, I mean I need the start_app function to be running in the background
    and then be able to stop it at certain point
    I was able to run the start_app function in the background but only when I moved start_app function into a separate py file, imported and run it like this:
    import mock_service_app
    import multiprocessing as mp
    proc = mp.Process(target=mock_service_app.start_app, args=())
    proc = mp.Process(target=start_app, args=(), initializer=mute)
    are there any working examples of how to use startup/shutdown described in:
    Phil Jones
    There is an example here for my website

    Thank you,
    I see


    is there also an example on how to shutdown it?

    Phil Jones
    Something like this?
    Ernesto Ruge
    @povar81 I just pushed an project where I used before and after serving as a global extension: https://github.com/openbikebox/open-bike-box-connect/blob/master/webapp/common/amqp_queue.py . Perhaps this is an inspiration, too? :)
    András Mózes
    @the-infinity Nice work! A great inspiration source :smile:
    Phil Jones
    Phil Jones
    @the-infinity Hopefully you don't need jsonify anymore (can just return a dict) e.g. here.
    Ernesto Ruge
    @pgjones thanks for the hint! The configure_error_handlers is somehow a standard block which is in all my Flask / Quart projects, but without jsonify it's even more beautiful. Does it respect the JSON encoder I set here without jsonify: https://github.com/openbikebox/connect/blob/master/webapp/common/filter.py#L13 ?
    Thank you.
    I need a solution so that my start_app can be started in background in pytest in one case
    and then to be able to read data coming to the start_app in another case
    (and then stop it in yet another case - but that one I've already figured out via psutils)
    Phil Jones
    @the-infinity it should do (bug if it doesn't)
    hi, how do i use sqlite3 or ORM like peewee (sqlite3) with quart?
    was looking @ https://aiosqlite.omnilib.dev/en/stable/ but couldn't find any example
    Phil Jones
    Hi @shantanoo:matrix.org there isn't anything particularly special you need to do. Which aspects are you unsure about? Here is an sqlite example and pgjones/quart#35 is a good discussion.
    5 replies
    Montassar Ben Dhifallah
    hello everyone,
    I am new to quart.
    I want to get multiple files from a request. In flask, I used to use request.files.getlist("file")
    What is the equivalent in quart ?
    Phil Jones
    (await request.files).getlist("file") should work
    but asyncpg seems nice
    Montassar Ben Dhifallah
    @pgjones thank you so much !
    hi, I'm moving some code from flask to quart. In flask with gevent we had a way to obtain the port that was opened by the internal socket (configured with port 0 basically). Is there a way to do the same with quart (asyncio) + hypercorn? Thank you
    Montassar Ben Dhifallah

    hey everyone!
    hope you are all well
    I am trying to learn how to make an ML-based web app using Quart.
    I want to build an application that can handle prediction of a batch of images. I want to divide the batch into small chunks, make predictions and return the response to the user. This process should be done until the last chunk
    I thought of making an async recursive api call. All I want to do is to make it recursively return the response.

    Any help is appreciated.
    This is the function that I want to call it recursively.

    @app.route('/predict', methods=['POST'])
    async def predict():
        if request.method == 'POST':
            has_files = (await request.files).get("file", None)
        if has_files:
            files = (await request.files).getlist("file")
            responses= {}
            # split files into small chunks to place here !
            for file, i in zip(files, range(len(files))):
                img_bytes = file.read()
                class_id, class_name = await get_prediction(model=model,
                                                      imagenet_class_index= imagenet_class_index)
                responses[i] = {'class_id': class_id, 'class_name': class_name}
            return await render_template("results.html", text=str(responses))
            return await render_template("results.html", text="please upload image!")
    Phil Jones
    Would something using Server Sent Events, SSE, be what you need? https://gitlab.com/pgjones/quart/-/tree/master/examples/broadcast
    Ahmad Kurdi
    Hello, I would like to ask how can I make my Quart API await for API Calls before opening new connections? Cause every time a request is sent to the Quart app, it processes it and opens a new connection after it's done automatically, even if there is no API calls which leads to timeout after 60s. Thank you.
    I have previously opened a GitLab issue: pgjones/quart#409
    Phil Jones
    I've responded, but I don't fully understand what the issue is

    @pgjones when using websocket.close() from latest quart (from master branch), i get an error because quart is trying to close the websocket again in handle_websocket

    I made a hotfix for hypercorn that forces only one websocket.close event to be executed, ignoring the rest. I did this in hypercorn because quart is not aware of the websocket state, and so it can not know if the websocket has closed (or is in the process of doing so), does this make sense? Is it correct to MR this fix?

    Another question: Is hypercorn going to support HTTP&Websockets ASGI 2.3? reason is not a blocker on my webapp development, but it is wanted in the future (this would also mean support for 2.2, since hypercorn is currently on 2.1)

    whenever there is any error or exception anywhere in my app, quart just stops working -- but it doesn't crash.
    trio's nurseries break and stop accepting tasks, HTTP requests time out without logging anything to the server
    and so on
    what am I doing wrong?
    I imagine there is a way to catch all exceptions by default and show them to the user and go on
    this is the code (if it matters, probably not): https://github.com/lnbits/lnbits
    Phil Jones
    @lun-4 I think that is a good solution, but I'll check pgjones/quart#410.
    Yep, Hypercorn will support 2.3 when I next release it