Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    guillermohs9
    @guillermohs9:matrix.org
    [m]
    Is there any working example on how to broadcast from the server to all connected clients? Currently I'm using something very similar to something I picked up from SO: https://pastebin.com/XtEjyB7S
    2 replies
    I mean something to start from
    Dimitri Demarkus
    @Gowixx
    Hey guys, i was wondering if there was a library available in quart that is compatible w/ cloudflare.
    Ex: It changes the request.access_route ip to request.headers.get("CF-Connecting-IP") and blocks all requests if they are not from cloudflares IPs
    When I used flask for a project, I also used https://github.com/cs91chris/flask_cloudflare_remote, and it worked fine.
    Im wondering how I could either: 1.) use flask_cloudflare_remote in a way that is compatible to e used with quart
    or either, if there is another method that I could use
    Dimitri Demarkus
    @Gowixx
    Also, what's the difference w/ request.headers['REMOTE_ADDR'] request.access_route request.remote_addr? and is there a way to change them globally
    Phil Jones
    @pgjones
    access_route uses the X-Forwarded-For if present
    I think flask_patch would work with Flask-CloudflareRemote
    It is a fairly simple extension though - easy to adapt to Quart
    Marc Ludwig
    @befedo

    hi there,

    I have two plotly.dash applications which where based on flask and want to host them with hypercorn like so:

    from hypercorn.config import Config
    from hypercorn.middleware import AsyncioWSGIMiddleware
    from hypercorn.middleware.dispatcher import AsyncioDispatcherMiddleware
    
    from asyncio import run
    from hypercorn.asyncio import serve
    
    config = Config()
    config.bind = ["localhost:8080"]
    
    foo_app = AsyncioWSGIMiddleware(foo.server)
    bar_app = AsyncioWSGIMiddleware(bar.server)
    
    dispatcher = AsyncioDispatcherMiddleware({
        "/foo": foo_app,
        "/bar": bar_app,
    })
    
    run(serve(dispatcher, config))

    But I get hypercorn.utils.LifespanTimeoutError: Timeout whilst awaiting startup.. what am I doing wrong?

    Thanks for your time ... :)

    Phil Jones
    @pgjones
    I think there is a bug in the dispatcher middleware - does it work for the wsgi apps individually?
    Marc Ludwig
    @befedo
    @pgjones yes, running a single app works like expected.
    Dimitri Demarkus
    @Gowixx

    I think flask_patch would work with Flask-CloudflareRemote

    What's the difference with Flask Patch and Quart?

    2 replies
    Dimitri Demarkus
    @Gowixx

    The documentation regarding broadcasting to multiple websocket clients here https://pgjones.gitlab.io/quart/tutorials/websocket_tutorial.html#broadcasting has an implementation where it creates a queue for each connected client and the broadcast() function loops over the queues in order to send messages, which works fine, but recently I have started using the library asyncio_multisubscriber_queue which is quite nice;

    from asyncio_multisubscriber_queue import MultisubscriberQueue
    
    broadcast = MultisubscriberQueue() 
    
    
    @app.websocket('/api/v2/ws')
    async def ws(queue):
        async for data in broadcast.subscribe():   # blocking until there is a message
            await websocket.send(data)
    
    
    await broadcast.put("Hello")

    This works with multiple connected websocket clients. It doesn't require a decorator and also doesn't need the broadcast function. (under the hood it most likely still creates a queue for each connected client, it is just abstracted away). Just FYI.

    Im guessing this just echos back what the user is saying and then sends "Hello" to all websockets?

    2 replies
    Dimitri Demarkus
    @Gowixx
    Is there a way to use async functions inside of templates?
    Ex; I have
    @app.context_processor
    async def get_everything():
        return dict(
            example = 'yes'
        )
    And i am interested in doing:
    <h1>
        {{ await get_everything() }}
    </h1>
    However, I get the AttributeError of:
    TemplateSyntaxError expected token 'end of print statement', got 'get_everything'
    Phil Jones
    @pgjones

    await is implicit in jinja templates

    <h1>
        {{ get_everything() }}
    </h1>

    should work

    Dimitri Demarkus
    @Gowixx

    await is implicit in jinja templates

    <h1>
        {{ get_everything() }}
    </h1>

    should work

    Returns UndefinedError 'get_everything' is undefined...

    Dimitri Demarkus
    @Gowixx
    fixed it, was using it wrong
    Florian Apolloner
    @apollo13
    Hi, I am using hypercorn with trio and am trying to get lifespan.shutdown events on ctrl+c -- currently it fails rather early https://dpaste.org/UsTtY/raw do you have any hints?
    Oh I think my lifespan implementation is broken
    ah yes, one to many return statements where there should not be any :)
    Prasanna Venkadesh
    @PrasannaVenkadesh
    What is the recommended way to introduce API versioning in Quart without duplicating the blueprint modules? Today, I have a folder full of blueprints.
    Phil Jones
    @pgjones
    I'm not sure what you are asking - but you can register the same blueprint more than once (each with a different url_prefix)
    shantanoo
    @shantanoo:matrix.org
    [m]
    Is it possible to use socketio.js client with quart? Have been using flask-socketio. Any pointers to sample/boiler plate would be nice.
    Hari Hara Prasad
    @hhp-the-maestro
    how to run my quart application in my external ip or how to make it visible across different networks from my machine
    1 reply
    othertheguy
    @othertheguy
    is there a way to use Quart with multiprocessing? to be explicit, I want to start a Quart app on a separate process that is able to talk with the rest of the application via multiprocessing.Queue
    othertheguy
    @othertheguy
    I found it myself:
    @app.route("/help", methods=['GET'])
    async def help_all_calls(self):
        return "HELP MESSAGE"
    
    async def manipulate_data():
        while True:
            await asyncio.sleep(0.01)
    
    def do_serve_data():
        loop = asyncio.new_event_loop()
        loop.create_task(app.run_task())
        loop.run_until_complete(manipulate_data())
    
    if __name__ == "__main__":
        data_serve_process = multiprocessing.Process(target=do_serve_data)
        data_serve_process.start()
    hope it helps someone :)
    Phil Jones
    @pgjones
    I think you'd find these docs on how to run hypercorn programmatically useful.
    1 reply
    shaakaud
    @shaakaud
    I am seeing this issue "ImportError: cannot import name 'json' from 'itsdangerous' " in hypercorn. I am using Hypercorn==0.13.2 and Quart==0.17.0. Anyone faced this issue and is there any workaround ?
    Phil Jones
    @pgjones
    Could you try updating all the dependencies? I think one of the dependencies changed
    mte
    @mte0
    hey there, im in the process of converting my sync flask app to an async quart app, what ratelimiting can i use? currently using from flask_limiter import Limiter from flask_limiter.util import get_remote_address
    and defining this at the start
    limiter = Limiter( application, key_func=get_remote_address, default_limits=["1000 per day", "30 per minute"] )
    any other tips for me to follow while converting?
    Phil Jones
    @pgjones
    Quart-Rate-Limiter should be good
    It also has default limits,
    rate_limiter = RateLimiter(
        default_limits=[RateLimit(1000, timedelta(days=1))]
    )
    Steve Moss
    @stevemossovo

    I'm migrating from Flask to Quart and trying to sort out authentication. I previously had decorators on the function calls for each route that would do that, but have realised it is causing errors. How can I get this to work with Quart?

    The pattern is something like:

    @app.route("/get_foo", methods=["GET"])
    @oauth(auth0=["Default"], keycloak=[])
    async def get_foo():
        return await response(jsonify(bar))

    Commenting out gets it working, so obviously something with the @oauth decorator?

    @app.route("/get_foo", methods=["GET"])
    # @oauth(auth0=["Default"], keycloak=[])
    async def get_foo():
        return await response(jsonify(bar))
    Steve Moss
    @stevemossovo
    :point_up: June 2, 2022 5:48 PM
    I have a feeling I may need to reimplement using https://async-oauthlib.readthedocs.io/en/latest/
    Daniel Knell
    @danielknell
    took a stab at adding dependency injection to various parts of quart via the injector library: https://pypi.org/project/quart-injector/
    Dilip Rajkumar
    @diliprk

    Greetings to this wonderful Gitter community for quart.

    I am trying to build a plotly-dash app that interfaces with a MongoDB collection where data is continuously written at asynchronous time intervals. I followed this tutorial to set up WebSockets with MongoDB, and this is the output I get.
    https://cdn.discordapp.com/attachments/931545568931631194/983232389763448852/unknown.png .

    The dash app needs to plot the equity field on the y-axis and time on the x-axis.
    But I don't know how to connect this WebSocket to Dash. Will quart python package be of any help for my requirement?
    Would be grateful for any guidance on this issue, as information on the internet to set up a WebSocket connection between MongoDB and Dash is very scarce?
    I am also willing to contribute my code for a demo article or tutorial which can be published in medium or in your website so that future users can refer to the same should a similar requirement arise in the future for other users?

    Looking forward to your reply.

    Best Regards,
    Dilip

    Yannick Einsweiler
    @yiga2
    @stevemossovo take a look at quart-auth (orquart-login). Also you can implement your own wrapper if none fits the bill + share with the libs maintainer so they may consider integrating.
    Joe Black
    @joeblackwaslike

    Any suggestions on how to fix Quart.add_background_task’s behavior when passed a sync function? Whenever I do that with an async function, it behaves as expected, it’s run concurrently (verified via datadog APM traces) whenever I pass it a sync function, it blocks the main thread and runs immediately or sometime before the response is returned. When I try to wrap the sync function in an async wrapper like this:

    async def wrapper():
        await run_sync(time.sleep)(5)
    
    current_app.add_background_task(wrapper)

    It’s never actually executed (not sure why)

    Phil Jones
    @pgjones

    I've not been certain how best to support sync background tasks and so it does block, see docs.
    I had been thinking of using run_sync though, as you've done - so I'm not sure why it doesn't work. The following works for me:

    import time                                                                                                                                                                                                 
    
    from quart import Quart
    from quart.utils import run_sync
    
    app = Quart(__name__)
    
    def timo(duration):
        print("Start")
        time.sleep(duration)
        print("End")
    
    async def wrapper():
        await run_sync(timo)(5)
    
    @app.get("/")
    async def index():
        app.add_background_task(wrapper)
        return "Hi"
    
    app.run()

    With output

     * Serving Quart app 'tgitter'
     * Environment: production
     * Please use an ASGI server (e.g. Hypercorn) directly in production
     * Debug mode: False
     * Running on http://127.0.0.1:5000 (CTRL + C to quit)
    [2022-06-26 10:37:30,187] Running on http://127.0.0.1:5000 (CTRL + C to quit)
    Start
    [2022-06-26 10:37:34,793] 127.0.0.1:59268 GET / 1.1 200 2 3088
    End
    Joe Black
    @joeblackwaslike
    @pgjones I’m not sure what the difference is in my use case, there is alot of added complexity, but thanks for the minimal case, it indeed works and I’ll try to hunt down where its going wrong