[英]Can not configure a Starlette .env file
I'm trying to set up the.env file for my project.我正在尝试为我的项目设置 .env 文件。 But it seems incorrect.
但这似乎不正确。
I store the.env file in the same folder as the config.py file as below.我将 .env 文件存储在与 config.py 文件相同的文件夹中,如下所示。
|__run.py
|___|myproject
|__config.py
|__.env
Code in my config.py file:我的 config.py 文件中的代码:
from starlette.config import Config
from starlette.datastructures import Secret, CommaSeparatedStrings
config = Config(".env")
BACKHUG_JWT_AES_KEY = config('BACKHUG_JWT_AES_KEY', default=None)
print(type(BACKHUG_JWT_AES_KEY))
print(BACKHUG_JWT_AES_KEY)
Data in the.env file: .env 文件中的数据:
BACKHUG_JWT_AES_KEY="SAMPLE_AES_KEY"
But the result I got was:但我得到的结果是:
<class 'NoneType'>
None
I don't know why it got the None object.我不知道为什么它没有object。 How can I fix it?
我该如何解决?
I run my project from a run.py file.我从run.py文件运行我的项目。
Code in the run.py file: run.py文件中的代码:
import uvicorn
if __name__ == "__main__":
uvicorn.run("myproject.main:app", host="0.0.0.0", port=8888, reload=True)
Remove the double quotes in the value and try again:删除值中的双引号,然后重试:
env file: .env 文件:
BACKHUG_JWT_AES_KEY=SAMPLE_AES_KEY
I'm pretty sure this is an issue with the current working directory .我很确定这是当前工作目录的问题。 I can suggest two ways.
我可以建议两种方法。
.env
file to one directory with the run.py
file.env
文件移动到带有run.py
文件的目录Or或者
config = Config("myproject/.env")
config = Config("myproject/.env")
There is a better way!有一个更好的方法!
Use FastAPI and Pydantic for this.为此使用FastAPI和Pydantic 。 Pydantic provides a great
BaseSettings
class. Pydantic 提供了一个很棒的
BaseSettings
class。 Also, we have great documentation for settings and environment variables .此外,我们有很好的设置和环境变量文档。
Create a Settings
class by inheriting from Pydantic 's BaseSettings
:通过从Pydantic的 BaseSettings 继承来创建
Settings
BaseSettings
:
from pydantic import BaseSettings
class Settings(BaseSettings):
backhug_jwt_access_key: str
class Config:
env_file = "myproject/.env"
This Settings class automatically reads the variables from the .env
file.此设置class 自动从
.env
文件中读取变量。 Then from your main file you can use it like this:然后从您的主文件中,您可以像这样使用它:
from . import config
from functools import lru_cache
from fastapi import Depends, FastAPI
app = FastAPI()
@lru_cache()
def get_settings():
return config.Settings()
@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
return {"jwt_key": settings.backhug_jwt_access_key}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.