cyr*_*slk 3 python fastapi uvicorn
我对 Python 很陌生。
我正在使用fastapi和制作一个简单的网络服务器uvicorn。
当我构建 Docker 并运行它时,我得到以下内容:
INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)
我的代码是:
# Setup FastAPI server
import uvicorn
from fastapi import FastAPI
from fastapi_utils.tasks import repeat_every
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
import os
from pymongo import MongoClient
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
load_dotenv('env')
# Database
CONNECTION_URL = os.environ['mongoConnectionURL']
DATABASE_NAME = os.environ['mongoDatabaseName']
NEWS_COLLECTION = os.environ['mongodbNewsCollection']
app = FastAPI()
# TODO JS has next function i'm currently unaware of
app.add_middleware(
    CORSMiddleware,
    allow_origins=['*'],
    allow_headers=["Origin, X-Requested-With, Content-Type, Accept"],
)
@app.get('/')
def index():
    return 'See /entries'
@app.get('/entries')
def getEntries():
    client = MongoClient(CONNECTION_URL)
    databaseMongo = client.get_database(DATABASE_NAME)
    collectionMongo = databaseMongo.get_collection(NEWS_COLLECTION)
    result = list(collectionMongo.find())
    for entry in result:
        return {
            'data': result
        }
if __name__ == "__main__":
    uvicorn.run(app, port=int(os.environ['PORT']))
我的 Dockerfile 是:
# Python container
FROM python:3.9.12
# Copy the source code to the container
COPY env /env
COPY main.py /main.py
COPY requirements.txt /requirements.txt
# If container is run in debug mode, we need to add the image folder
RUN mkdir /img
# Install requirements
RUN pip install --upgrade pip && pip install -r requirements.txt
CMD ["python", "main.py"]
我运行我的 docker 文件:
docker run memeified-docker-server
当我访问 时http://127.0.0.1:5000,浏览器会显示该ERR_CONNECTION_REFUSED 页面。
小智 5
尝试将 host="0.0.0.0" 赋予 uvicorn.run
uvicorn.run(app, host="0.0.0.0", port=int(os.environ['PORT']))
| 归档时间: | 
 | 
| 查看次数: | 4302 次 | 
| 最近记录: |