WebSocket fasaha ce mai ƙarfi don kafa hanyoyin sadarwa na lokaci-lokaci tsakanin sabar da abokan ciniki. Da ke ƙasa akwai jagora kan yadda ake haɗawa WebSocket cikin shahararrun tsare-tsare guda biyu, Flask da FastAPI.
Haɗuwa WebSocket cikin Flask
Mataki 1: Sanya Libraries
Da farko, kuna buƙatar shigar da flask
dakunan flask-socketio
karatu ta amfani da umarni mai zuwa:
pip install Flask flask-socketio
Mataki 2: Saita Aikace-aikacen
Ga misalin yadda ake haɗa WebSocket aikace Flask -aikacen:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
@socketio.on('message')
def handle_message(message):
emit('response', {'data': message})
if __name__ == '__main__':
socketio.run(app)
A cikin snippet na lambar da ke sama, muna amfani da flask-socketio
ɗakin karatu don ƙirƙirar WebSocket sabar. Ana kiran aikin handle_message
lokacin da abokin ciniki ya aika sako, kuma uwar garken yana amsawa ta hanyar fitar da wani response
taron.
Haɗuwa WebSocket cikin FastAPI
Mataki 1: Sanya Libraries
Shigar fastapi
da uvicorn
ɗakunan karatu ta amfani da umarni mai zuwa:
pip install fastapi uvicorn
Mataki 2: Saita Aikace-aikacen
Ga misalin yadda ake haɗa WebSocket aikace FastAPI -aikacen:
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get('/')
def get():
return HTMLResponse(content=open("index.html").read())
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Server received: {data}")
A cikin snippet lambar da ke sama, muna amfani da shi FastAPI don ƙirƙirar WebSocket sabar. Aikin websocket_endpoint
yana karɓar WebSocket haɗin kai, yana sauraron bayanan da abokan ciniki suka aiko, kuma yana amsawa ta hanyar aika bayanai zuwa ga abokin ciniki.
Kammalawa
Haɗuwa WebSocket cikin shahararrun ginshiƙai kamar Flask da FastAPI buɗe dama don ƙirƙirar aikace-aikace na lokaci-lokaci da sadarwa tsakanin sabar da abokan ciniki.