*๏ธโฃ¶
๐ ๐ช โ๏ธ ๏ธโฃ โฎ๏ธ FastAPI*.
โ WebSockets
¶
๐ฅ ๐ ๐ช โ WebSockets
:
$ pip install websockets
---> 100%
*๏ธโฃ ๐ฉโ๐ป¶
๐ญ¶
๐ ๐ญ โ๏ธ, ๐ ๐ฒ โ๏ธ ๐ธ โ โฎ๏ธ ๐ ๐ ๏ธ ๐ ๐ฅ, Vue.js โ๏ธ ๐.
& ๐ โ๏ธ *๏ธโฃ โฎ๏ธ ๐ ๐ฉโ๐ป ๐ ๐ ๐ฒ โ๏ธ ๐ ๐ธ ๐.
โ๏ธ ๐ ๐ช โ๏ธ ๐ฆ๐ธ ๐ฑ ๐ธ ๐ ๐ โฎ๏ธ ๐ *๏ธโฃ ๐ฉโ๐ป ๐, ๐ฆ๐ธ ๐.
โ๏ธ ๐ 5๏ธโฃ๐ โ๏ธ ๐ ๐ ๐ ๐ โฎ๏ธ *๏ธโฃ ๐.
โ๏ธ ๐ ๐ผ, ๐ฅ ๐ โ๏ธ ๐ถ ๐ ๐ธ ๐ โฎ๏ธ ๐ธ, ๐ ๐ ๐ ๐ป.
๐, โ๏ธ, ๐ซ โ & ๐ ๐ซ๐ โ๏ธ โซ๏ธ ๐ญ.
๐ญ ๐ ๐ โ๏ธ 1๏ธโฃ ๐ ๐.
โ๏ธ โซ๏ธ ๐ ๐ ๐ฏ ๐ ๐ฝ-๐ *๏ธโฃ & โ๏ธ ๐ท ๐ผ:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
โ websocket
¶
๐ FastAPI ๐ธ, โ websocket
:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
๐ก โน
๐ ๐ช โ๏ธ from starlette.websockets import WebSocket
.
FastAPI ๐ ๐ WebSocket
๐ ๐ช ๐, ๐ฉโ๐ป. โ๏ธ โซ๏ธ ๐ ๐ โช๏ธโก๏ธ ๐.
โ ๐ง & ๐จ ๐ง¶
๐ *๏ธโฃ ๐ฃ ๐ ๐ช await
๐ง & ๐จ ๐ง.
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
๐ ๐ช ๐จ & ๐จ ๐ฑ, โ, & ๐ป ๐ฝ.
๐ โซ๏ธ¶
๐ฅ ๐ ๐ ๐ main.py
, ๐ ๐ ๐ธ โฎ๏ธ:
$ uvicorn main:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
๐ ๐ ๐ฅ http://127.0.0.1:8000.
๐ ๐ ๐ ๐ ๐ ๐:
๐ ๐ช ๐ ๐ง ๐ข ๐ฆ, & ๐จ ๐ซ:
& ๐ FastAPI ๐ธ โฎ๏ธ *๏ธโฃ ๐ ๐จ ๐:
๐ ๐ช ๐จ (& ๐จ) ๐ ๐ง:
& ๐ ๐ซ ๐ โ๏ธ ๐ *๏ธโฃ ๐.
โ๏ธ Depends
& ๐¶
*๏ธโฃ ๐ ๐ ๐ช ๐ โช๏ธโก๏ธ fastapi
& โ๏ธ:
Depends
Security
Cookie
Header
Path
Query
๐ซ ๐ท ๐ ๐ ๐ FastAPI ๐/โก ๐ ๏ธ:
from typing import Union
from fastapi import (
Cookie,
Depends,
FastAPI,
Query,
WebSocket,
WebSocketException,
status,
)
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<label>Item ID: <input type="text" id="itemId" autocomplete="off" value="foo"/></label>
<label>Token: <input type="text" id="token" autocomplete="off" value="some-key-token"/></label>
<button onclick="connect(event)">Connect</button>
<hr>
<label>Message: <input type="text" id="messageText" autocomplete="off"/></label>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var ws = null;
function connect(event) {
var itemId = document.getElementById("itemId")
var token = document.getElementById("token")
ws = new WebSocket("ws://localhost:8000/items/" + itemId.value + "/ws?token=" + token.value);
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
event.preventDefault()
}
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
@app.get("/")
async def get():
return HTMLResponse(html)
async def get_cookie_or_token(
websocket: WebSocket,
session: Union[str, None] = Cookie(default=None),
token: Union[str, None] = Query(default=None),
):
if session is None and token is None:
raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
return session or token
@app.websocket("/items/{item_id}/ws")
async def websocket_endpoint(
websocket: WebSocket,
item_id: str,
q: Union[int, None] = None,
cookie_or_token: str = Depends(get_cookie_or_token),
):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(
f"Session cookie or query token value is: {cookie_or_token}"
)
if q is not None:
await websocket.send_text(f"Query parameter q is: {q}")
await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}")
Info
๐ *๏ธโฃ โซ๏ธ ๐ซ ๐ค โ ๐ ๐ค HTTPException
, โฉ๏ธ ๐ฅ ๐ค WebSocketException
.
๐ ๐ช โ๏ธ ๐ช ๐ โช๏ธโก๏ธ โ ๐ ๐ฌ ๐ง.
๐ *๏ธโฃ โฎ๏ธ ๐¶
๐ฅ ๐ ๐ ๐ main.py
, ๐ ๐ ๐ธ โฎ๏ธ:
$ uvicorn main:app --reload
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
๐ ๐ ๐ฅ http://127.0.0.1:8000.
๐ค ๐ ๐ช โ:
- "๐ฌ ๐", โ๏ธ โก.
- "๐ค" โ๏ธ ๐ข ๐ข.
Tip
๐ ๐ ๐ข token
๐ ๐ต ๐.
โฎ๏ธ ๐ ๐ ๐ช ๐ *๏ธโฃ & โคด๏ธ ๐จ & ๐จ ๐ง:
๐ ๐ & ๐ ๐ฉโ๐ป¶
๐โ *๏ธโฃ ๐ ๐ช, await websocket.receive_text()
๐ ๐ค WebSocketDisconnect
โ , โ ๐ ๐ช โคด๏ธ โ & ๐ต ๐ ๐ ๐ผ.
from typing import List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
app = FastAPI()
html = """
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<h2>Your ID: <span id="ws-id"></span></h2>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var client_id = Date.now()
document.querySelector("#ws-id").textContent = client_id;
var ws = new WebSocket(`ws://localhost:8000/ws/${client_id}`);
ws.onmessage = function(event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
ws.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
"""
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
self.active_connections.remove(websocket)
async def send_personal_message(self, message: str, websocket: WebSocket):
await websocket.send_text(message)
async def broadcast(self, message: str):
for connection in self.active_connections:
await connection.send_text(message)
manager = ConnectionManager()
@app.get("/")
async def get():
return HTMLResponse(html)
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
await manager.connect(websocket)
try:
while True:
data = await websocket.receive_text()
await manager.send_personal_message(f"You wrote: {data}", websocket)
await manager.broadcast(f"Client #{client_id} says: {data}")
except WebSocketDisconnect:
manager.disconnect(websocket)
await manager.broadcast(f"Client #{client_id} left the chat")
๐ โซ๏ธ ๐ :
- ๐ ๐ฑ โฎ๏ธ ๐ ๐ฅ ๐.
- โ ๐ง โช๏ธโก๏ธ ๐ซ.
- โคด๏ธ ๐ 1๏ธโฃ ๐.
๐ ๐ ๐ค WebSocketDisconnect
โ , & ๐ ๐ ๐ฉโ๐ป ๐ ๐จ ๐ง ๐:
Client #1596980209979 left the chat
Tip
๐ฑ ๐ โญ & ๐ ๐ผ ๐ฆ โ ๐ต & ๐ป ๐ง ๐ *๏ธโฃ ๐.
โ๏ธ โ๏ธ ๐คฏ ๐, ๐ ๐ต ๐พ, ๐ ๐, โซ๏ธ ๐ ๐ด ๐ท โช ๐ ๏ธ ๐, & ๐ ๐ด ๐ท โฎ๏ธ ๐ ๐ ๏ธ.
๐ฅ ๐ ๐ช ๐ณ โฉ ๐ ๏ธ โฎ๏ธ FastAPI โ๏ธ ๐ ๐ ๐๏ธ, ๐โ๐ฆบ โณ, โณ โ๏ธ ๐, โ ๐/๐ป.
๐ โน¶
๐ก ๐ ๐ ๐, โ ๐ ๐งพ: