nz_21
nz_21

Reputation: 7343

Uvicorn not running sanic "before_server_start"

I have a sanic app like so:



from functools import wraps
import os

from sanic import Sanic
from sanic.response import json

from es_api.client import ElasticEngine
from utils import cleanup

app = Sanic(__name__)

async def setup_es_client(app, loop):
    app.es_client = ElasticEngine.from_bonsai("xkcd_production", test_instance=False)



@app.route("/", methods=["GET"])
async def home(request):
    return json({"hello": "worldddd"})




@app.route("/all", methods=["GET"])
async def display_all_docs(request):
    results = app.es_client.search_all().results()
    return json(
        {"results": results}
    )



if __name__ == "__main__":
    app.register_listener(setup_es_client,
                          'before_server_start')
    app.run(host="0.0.0.0", port=8000, debug=True, workers=20)

When I run uvicorn myapp, it serves the homepage fine: I see the expected json.

But when I hit /all, it says

"app has not attribute es_client"

, which presumably indicates that the before_server_start function hasn't been run.

How do I fix this? I've looked into the sanic doc but I couldn't find any references to this issue

(It works fine when I run the app as is -- i.e, python3 myapp.py)

Upvotes: 0

Views: 818

Answers (1)

nz_21
nz_21

Reputation: 7343

Fixed.

Move app.register_listener(setup_es_client, 'before_server_start') above if __name__=="__main__"

Better yet, just use sanic's builtin decorator for nicer ergonomics: https://sanic.readthedocs.io/en/latest/sanic/middleware.html

Upvotes: 1

Related Questions