FastAPI завис в ожидании запуска приложения [дубликат] ⇐ Python
-
Anonymous
FastAPI завис в ожидании запуска приложения [дубликат]
I'm trying to create a web app using FastAPI, to show weather and time and Bitcoin price and etc. This is the Python code (I obviously replace the OPENWEATHERMAP_API_KEY and other stuff):
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect, BackgroundTasks from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import requests import asyncio app = FastAPI() # Templates templates = Jinja2Templates(directory="templates") # Static files (like CSS and JS) app.mount("/static", StaticFiles(directory="static"), name="static") # API key for OpenWeatherMap (replace with your own) OPENWEATHERMAP_API_KEY = "YOUR_OPENWEATHERMAP_API_KEY" # Background task to update Bitcoin price every minute async def update_bitcoin_price(background_tasks: BackgroundTasks): while True: await asyncio.sleep(60) bitcoin_price = get_bitcoin_price() background_tasks.add_task(update_data, "bitcoinPrice", f"Bitcoin Price: €{bitcoin_price}") # Background task to update weather information every 5 minutes async def update_weather_info(background_tasks: BackgroundTasks): while True: await asyncio.sleep(300) weather_info = get_weather_info() background_tasks.add_task(update_data, "weatherInfo", weather_info) # Background task to update text file contents every 4 hours async def update_file_contents(background_tasks: BackgroundTasks): while True: await asyncio.sleep(14400) file_contents = get_file_contents() background_tasks.add_task(update_data, "fileContents", f"Text File Contents: {file_contents}") # Function to fetch Bitcoin price from CoinGecko API def get_bitcoin_price(): response = requests.get('https://api.coingecko.com/api/v3/simple ... encies=eur') response.raise_for_status() data = response.json() return data["bitcoin"]["eur"] # Function to fetch weather information from OpenWeatherMap API def get_weather_info(): city = "YOUR_CITY" # Replace with the city of your choice weather_endpoint = f"http://api.openweathermap.org/data/2.5/ ... its=metric" response = requests.get(weather_endpoint) response.raise_for_status() data = response.json() temperature = data["main"]["temp"] weather_description = data["weather"][0]["description"] return f"Weather: {weather_description}, Temperature: {temperature}°C" # Function to fetch text file contents def get_file_contents(): try: with open("your_text_file.txt", "r", encoding="utf-8") as file: return file.read() except FileNotFoundError: return "Text file not found" # Function to update data on the web page def update_data(data_id: str, new_data: str): sockets_to_update = list(app.state.websockets) for socket in sockets_to_update: socket["background_tasks"].add_task(emit_data, socket["websocket"], data_id, new_data) # Function to emit data to connected clients async def emit_data(websocket, data_id: str, new_data: str): await websocket.send_text(f'{{"id": "{data_id}", "data": "{new_data}"}}') # Route to handle the WebSocket connection @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() app.state.websockets.add({"websocket": websocket, "background_tasks": BackgroundTasks()}) try: while True: data = await websocket.receive_text() except WebSocketDisconnect: app.state.websockets.remove({"websocket": websocket, "background_tasks": BackgroundTasks()}) # Route to render the HTML page @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("index.html", {"request": request}) # Start background tasks @app.on_event("startup") async def startup_event(): app.websockets = set() background_tasks = BackgroundTasks() background_tasks.add_task(update_bitcoin_price) background_tasks.add_task(update_weather_info) background_tasks.add_task(update_file_contents) app.add_event_handler("startup", startup_event) # Serve the app using Uvicorn if __name__ == "__main__": import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000) And this is the HTML file:
FastAPI Web App body { background-color: black; color: green; font-family: Arial, sans-serif; margin: 0; padding: 0; text-align: center; } #time { font-size: 24px; margin-top: 20px; } #bitcoinPrice { font-size: 18px; margin-top: 10px; } #additionalText { font-size: 20px; font-family: 'Times New Roman', Times, serif; margin-top: 15px; } #weatherInfo { font-size: 16px; margin-top: 10px; } #fileContents { font-size: 16px; margin-top: 10px; } Hello, this is a FastAPI web app with live time, Bitcoin price, weather information, and text file contents! This is a simple web app with styling, live time, live Bitcoin price in euros, weather information, and text file contents using FastAPI.
// WebSocket connection const socket = new WebSocket("ws://127.0.0.1:8000/ws"); // Function to update data on the web page function updateData(data) { const element = document.getElementById(data.id); if (element) { element.innerHTML = data.data; } } // Event listener for WebSocket messages socket.addEventListener("message", (event) => { const data = JSON.parse(event.data); updateData(data); });
When I run the app (using uvicorn main:app --reload) I get this in the console:
INFO: Will watch for changes in these directories: ['C:\\Users...'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [14632] using WatchFiles INFO: Started server process [9072] INFO: Waiting for application startup. And that's it. Nothing happens. And if Visit http://127.0.0.1:8000, I get this error:
This site can’t be reached 127.0.0.1 refused to connect. What am I doing wrong?
Источник: https://stackoverflow.com/questions/779 ... on-startup
I'm trying to create a web app using FastAPI, to show weather and time and Bitcoin price and etc. This is the Python code (I obviously replace the OPENWEATHERMAP_API_KEY and other stuff):
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect, BackgroundTasks from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles import requests import asyncio app = FastAPI() # Templates templates = Jinja2Templates(directory="templates") # Static files (like CSS and JS) app.mount("/static", StaticFiles(directory="static"), name="static") # API key for OpenWeatherMap (replace with your own) OPENWEATHERMAP_API_KEY = "YOUR_OPENWEATHERMAP_API_KEY" # Background task to update Bitcoin price every minute async def update_bitcoin_price(background_tasks: BackgroundTasks): while True: await asyncio.sleep(60) bitcoin_price = get_bitcoin_price() background_tasks.add_task(update_data, "bitcoinPrice", f"Bitcoin Price: €{bitcoin_price}") # Background task to update weather information every 5 minutes async def update_weather_info(background_tasks: BackgroundTasks): while True: await asyncio.sleep(300) weather_info = get_weather_info() background_tasks.add_task(update_data, "weatherInfo", weather_info) # Background task to update text file contents every 4 hours async def update_file_contents(background_tasks: BackgroundTasks): while True: await asyncio.sleep(14400) file_contents = get_file_contents() background_tasks.add_task(update_data, "fileContents", f"Text File Contents: {file_contents}") # Function to fetch Bitcoin price from CoinGecko API def get_bitcoin_price(): response = requests.get('https://api.coingecko.com/api/v3/simple ... encies=eur') response.raise_for_status() data = response.json() return data["bitcoin"]["eur"] # Function to fetch weather information from OpenWeatherMap API def get_weather_info(): city = "YOUR_CITY" # Replace with the city of your choice weather_endpoint = f"http://api.openweathermap.org/data/2.5/ ... its=metric" response = requests.get(weather_endpoint) response.raise_for_status() data = response.json() temperature = data["main"]["temp"] weather_description = data["weather"][0]["description"] return f"Weather: {weather_description}, Temperature: {temperature}°C" # Function to fetch text file contents def get_file_contents(): try: with open("your_text_file.txt", "r", encoding="utf-8") as file: return file.read() except FileNotFoundError: return "Text file not found" # Function to update data on the web page def update_data(data_id: str, new_data: str): sockets_to_update = list(app.state.websockets) for socket in sockets_to_update: socket["background_tasks"].add_task(emit_data, socket["websocket"], data_id, new_data) # Function to emit data to connected clients async def emit_data(websocket, data_id: str, new_data: str): await websocket.send_text(f'{{"id": "{data_id}", "data": "{new_data}"}}') # Route to handle the WebSocket connection @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() app.state.websockets.add({"websocket": websocket, "background_tasks": BackgroundTasks()}) try: while True: data = await websocket.receive_text() except WebSocketDisconnect: app.state.websockets.remove({"websocket": websocket, "background_tasks": BackgroundTasks()}) # Route to render the HTML page @app.get("/", response_class=HTMLResponse) async def read_item(request: Request): return templates.TemplateResponse("index.html", {"request": request}) # Start background tasks @app.on_event("startup") async def startup_event(): app.websockets = set() background_tasks = BackgroundTasks() background_tasks.add_task(update_bitcoin_price) background_tasks.add_task(update_weather_info) background_tasks.add_task(update_file_contents) app.add_event_handler("startup", startup_event) # Serve the app using Uvicorn if __name__ == "__main__": import uvicorn uvicorn.run(app, host="127.0.0.1", port=8000) And this is the HTML file:
FastAPI Web App body { background-color: black; color: green; font-family: Arial, sans-serif; margin: 0; padding: 0; text-align: center; } #time { font-size: 24px; margin-top: 20px; } #bitcoinPrice { font-size: 18px; margin-top: 10px; } #additionalText { font-size: 20px; font-family: 'Times New Roman', Times, serif; margin-top: 15px; } #weatherInfo { font-size: 16px; margin-top: 10px; } #fileContents { font-size: 16px; margin-top: 10px; } Hello, this is a FastAPI web app with live time, Bitcoin price, weather information, and text file contents! This is a simple web app with styling, live time, live Bitcoin price in euros, weather information, and text file contents using FastAPI.
// WebSocket connection const socket = new WebSocket("ws://127.0.0.1:8000/ws"); // Function to update data on the web page function updateData(data) { const element = document.getElementById(data.id); if (element) { element.innerHTML = data.data; } } // Event listener for WebSocket messages socket.addEventListener("message", (event) => { const data = JSON.parse(event.data); updateData(data); });
When I run the app (using uvicorn main:app --reload) I get this in the console:
INFO: Will watch for changes in these directories: ['C:\\Users...'] INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [14632] using WatchFiles INFO: Started server process [9072] INFO: Waiting for application startup. And that's it. Nothing happens. And if Visit http://127.0.0.1:8000, I get this error:
This site can’t be reached 127.0.0.1 refused to connect. What am I doing wrong?
Источник: https://stackoverflow.com/questions/779 ... on-startup