Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    Adam Hopkins
    @ahopkins
    I would, however highly recommend Redis instead. It is meant for this sort of scalable key/value store
    Rado Kozmer
    @rkozmer
    @ahopkins Thank you!
    Rado Kozmer
    @rkozmer
    Hi! One question regarding sanic-jwt. What is the proper way to get user's identity in the protected route? Thanks.
    Rado Kozmer
    @rkozmer
    Ok, found it.
    spaced
    @spaced
    Hi: sanic: topic endless running response (video stream). how can i close the response and exit?
    Adam Hopkins
    @ahopkins
    @app.post("/")
    async def test(request):
        async def sample_streaming_fn(response):
            await response.write("\nfoo 1")
            await asyncio.sleep(1)
            await response.write("\nbar 22")
            await asyncio.sleep(1)
            await response.write("\nfoo 333")
            await asyncio.sleep(1)
            await response.write("\nbar 4444")
            response.protocol.close()
    
        return stream(sample_streaming_fn, chunked=False)
    I think response.protocol.close() is what you are looking for.
    You can also just exit out of your loop. That would close it, eventually
    It would stay open as long as your KEEP_ALIVE
    so, calling explicit closing may be what you are after.
    Francisco Benavides
    @fbenavides69
    Does any one here have experience launching Sanic application as a Docker instance in Azure Cloud?
    Arran Corbett
    @arrancorbett
    Not azure @fbenavides69 but have in both GCP and AWS
    1 reply
    Adam Hopkins
    @ahopkins
    Any specific questions or issues you are encountering?
    Justin
    @Paladiamors
    I've been playing around with using sanic as a headless server for a CRM that handles authentication, writing posts and managing resources like images with a react front end. Anyone here know of any sanic compatible modules with this functionality?
    Adam Hopkins
    @ahopkins
    what functionality specifically?
    authentication?
    Justin
    @Paladiamors
    Something that implements a blog posting api, handles image uploads and handles basic image manipulations. Something like the wagtail layer on top of django.
    Headless CRMS seem to be the new rage at the moment now that I've been picking up some react (and indeed that react is pretty nice). I guess it's a well known space so was curious if there were any modules being developed for sanic already.
    I might take a look at taking a well known architecture / model and just write a plugin.
    Adam Hopkins
    @ahopkins
    I'm not aware of anything like that. Maybe take a look on GitHub? https://github.com/topics/sanic
    Francisco Benavides
    @fbenavides69
    Hi guys, is there a production ready implementation of Sanic+Swagger? OpenAPI? Thanks! (what tooling do you use for this?)
    Adam Hopkins
    @ahopkins
    Have you seen sanic-openapi?
    1 reply
    Francisco Benavides
    @fbenavides69
    yes I have, is it the oficial?
    Ashley Sommer
    @ashleysommer
    Hi @fbenavides69
    There is Sanic-Restplus, is a port of Flask-Restplus. I use it in a couple of API services at my workplace. Downside is it only supports Swagger/OpenAPI 2.0, doesn't have any OpenAPI 3.0 features.
    1 reply
    liuzhichao
    @csrftoken
    Hello, every one, please help me.
    I want to start a sanic service by a thread.
    but close the server have a question
    Traceback (most recent call last):
    File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/main.py", line 65, in <module>
    app.stop()
    File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/app.py", line 40, in stop
    self.api_service.stop()
    File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/web/
    init.py", line 53, in stop
    self.
    loop.run_until_complete(close_task)
    File "uvloop/loop.pyx", line 1450, in uvloop.loop.Loop.run_until_complete
    File "uvloop/loop.pyx", line 1443, in uvloop.loop.Loop.run_until_complete
    File "uvloop/loop.pyx", line 1351, in uvloop.loop.Loop.run_forever
    File "uvloop/loop.pyx", line 480, in uvloop.loop.Loop._run
    RuntimeError: this event loop is already running.
    liuzhichao
    @csrftoken
    import uvloop
    import asyncio
    import logging
    from functools import partial
    
    from threading import Thread
    
    from conf import settings
    
    from .app import app
    
    
    class ApiService:
    
        def __init__(self, host, port):
            self.host = host
            self.port = port
    
            self.__server = None
            self.__loop = None
    
        def run(self):
            self.__loop = uvloop.new_event_loop()
            thread = Thread(target=partial(self._thread_main, self.__loop), name="api-service")
            thread.setDaemon(True)
            thread.start()
    
        def _thread_main(self, loop):
            logging.info("ApiService Listening on http://{}:{}".format(self.host, self.port))
            asyncio.set_event_loop(loop)
            serv_coro = app.create_server(
                host=self.host, port=self.port, return_asyncio_server=True, debug=settings.DEBUG
            )
    
            serv_task = asyncio.ensure_future(serv_coro, loop=self.__loop)
            self.__server = self.__loop.run_until_complete(serv_task)
            self.__server.after_start()
            self.__loop.run_forever()
    
        def stop(self):
            if self.__loop is None or self.__server is None:
                return
    
            self.__loop.run_coroutine_threadsafe(self.__loop.stop)
            self.__server.before_stop()
    
            # Wait for server to close
            close_task = self.__server.close()
            self.__loop.run_until_complete(close_task)
    
            # Complete all tasks on the loop
            for connection in self.__server.connections:
                connection.close_if_idle()
            self.__server.after_stop()
    Here is my code.
    Adam Hopkins
    @ahopkins
    what is the goal here? Certainly not an orthodox way to run the server.
    liuzhichao
    @csrftoken
    but What if child threads start and close
    Adam Hopkins
    @ahopkins
    I don't understand the question. Before getting into implementation strategies, can you let me know what you are trying to achieve?
    let's continue in the thread in the forum
    liuzhichao
    @csrftoken
    loop Can't shut down
    liuzhichao
    @csrftoken
    I call the stop method,but loop’s state is running
    image.png
    M@hs@
    @sogand145
    Hey Guys!
    I want to make a web server with sanic, but I don`t know how can manage sessions by server,
    I only stored sessions in the db, how can manage them by server efficienly?
    How should I set configuration in the server-side?
    Thanks a lot
    Adam Hopkins
    @ahopkins
    I don't know much about this project, other than it does exist
    But, if it is not something that would interest you, it is very simple to build your own with the usage of middleware (see Sanic docs)
    M@hs@
    @sogand145

    https://github.com/xen/sanic_session

    Thanks a lot, I read about them :)

    M@hs@
    @sogand145

    Hey Guys!
    I have a question!
    I`ve used sanic_session, but I have some routes that do not need to check session, like send_code or register or login
    how can I prevent running this middleware code?

    async def save_session(request, response):
                """After each request save the session, pass
                the response to set client cookies.
                """
                await self.interface.save(request, response)

    and please help me in this issue: I want to use two database in my application, is it ok to have session_ids in both postgres (in sessions table) and in redis?
    and when user registeres, the session id that I generated save in redis and postgres and redis is responsible to manage them?
    so that in each request if there is the same session in redis, the user can do anything, but if not user can't access and direct to login page

    Adam Hopkins
    @ahopkins

    how can I prevent running this middleware code?

    You have a few options, and it sort of depends upon how/what you are building.

    The easiest would be to simply check the request object
    @app.middleware("response")
    async def save_session(request, response):
        print(f"{request.path=}")
        print(f"{request.endpoint=}")
    Another would be to use blueprints
    app = Sanic("__BASE__")
    bp = Blueprint("session stuff")
    
    async def fake_save(*args):
        print(f"Saving... {args=}")
    
    @bp.middleware("response")
    async def save_session(request, response):
        await fake_save(request, response)
    
    @app.get("/nosession")
    async def nosession(request):
        return text("No session.")
    
    @bp.get("/session")
    async def session(request):
        return text("Yes session.")
    
    app.blueprint(bp)
    M@hs@
    @sogand145
    app = Sanic("__BASE__")
    bp = Blueprint("session stuff")
    
    async def fake_save(*args):
        print(f"Saving... {args=}")
    
    @bp.middleware("response")
    async def save_session(request, response):
        await fake_save(request, response)
    
    @app.get("/nosession")
    async def nosession(request):
        return text("No session.")
    
    @bp.get("/session")
    async def session(request):
        return text("Yes session.")
    
    app.blueprint(bp)
    cool 👍
    both solutions are great, thank you so much 🙏
    Adam Hopkins
    @ahopkins
    :+1:
    Gonzalo
    @GonzaloTorreras
    I am new to async and sanic, I have been googling but can't find a solution to this:
    I am trying to put a heavy task under add_task, and get back the return tho can't find how to do it (or if its the way to do it, I may need to change the logic there):
    app.websocket("/ws")
    async def mws(request, ws):
        while True:
         ...
        r = app.add_task( heavyTask(x) )
       if r:
         ...