Running code or function after serve


#1

Hi everyone,

I’m trying to use GINO with apistar and for that I need to run some code after serve within the event loop. ¿How can I accomplish this with apistar?.

Thanks for any pointers.


#2

I’m not familiar with GINO, but for things that happen after you process a request, I would recommend investigating hooks.

https://docs.apistar.com/api-guide/event-hooks/


#3

Thanks for the response. I was not clear enough in my question. GINO requires some initialization, that means that after app.serve, I need to execute some connection code only once, not per request (or response).

I think event hooks are not the place for this.


#4

Several months ago I ran into the same problem using asynpg in APIStar.
I solved the issue using a Component to track the connection state. It wasn’t ideal, but it worked well. The basics are this:

  1. When the component is instantiated, set up the initial connection state, get settings and what not, but don’t connect. The async loop hasn’t started yet. At this time create the instance of the object that will be used to interact with GINO, the persistent client instance.

  2. On the component resolve return the persistent client instance.

  3. The persistent client instance will check the connection to the DB before using it and if it doesn’t exist, creates it. At this point the async loop is running and you can setup the connection/pool.

Here is this pattern based on the old Component, so it would need to be adjusted for the updated Component class:


#5

Ah, now I understand.

There doesn’t look to be a ready place to do what you’re after, since app.serve calls werkzeug.run_simple(host, port, self, **
options) .

Of course, there may be some additional functionality as a part of werkzeug that might have a call back after commencing the server.

If you could run the code shortly before the app.serve, that would be easier, but I guess there might be some functionality that is relying on the server actually running.


#6

Many thanks. I think this approach will work for me :slight_smile: