问题是这样:我需要一个全局变量,但是在之后的 async function 里面才会对其进行赋值,这是我几个尝试,但是 pycharm 多少都会报 Warning
app = FastAPI()
conn_pool = None
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
这样底下的所有 conn_pool 的操作都会报Cannot find reference 'xxx' in 'None'
app = FastAPI()
conn_pool: asyncpg.pool.Pool = None
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
这样在conn_pool: asyncpg.pool.Pool = None
这一行会报Expected type 'Pool', got 'None' instead
app = FastAPI()
@app.on_event("startup")
async def startup():
global conn_pool
conn_pool = await asyncpg.create_pool()
@app.get('/')
async def index():
async with conn_pool.acquire() as conn:
pass # do something
可以用,但是在global conn_pool
会报Global variable 'conn_pool' is undefined at the module level
虽然所有代码都可以运行,但是都会错误提示,感觉很不舒服。求助有没有完美的解决方案。
我这里需要全局变量的原因是 conn_pool 需要在其他函数内使用
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.