日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > vue >内容正文

vue

fastapi vue socket 从其他文件调用 socket 方法

發布時間:2023/12/10 vue 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 fastapi vue socket 从其他文件调用 socket 方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

需求:因為項目需要,邊做邊學python,這次需要使用socket功能,正常在main.py中寫個socket,還是OK的,但是我想要在其他文件中,直接使用socket的emit方法,需要在文件結構上進行一些調整。

使用到的第三方庫:python-socketio
官方地址:https://python-socketio.readthedocs.io/en/latest/

1、寫一下前端代碼:

<template><div><h1>Hello Socket</h1></div> </template> <script> import * as io from 'socket.io-client'; export default {mounted() {this.socket = io.connect("http://localhost:8000");this.socket.emit('Client', "Hello, Server!");this.socket.on("Server", args => {console.log(args)});} } </script>

2、下面是python代碼
新建文件socket.py

import socketiobackground_task_started = Falsesio = socketio.AsyncServer(async_mode='asgi',cors_allowed_origins='*') # logger=False)async def background_task():# Example of how to send server generated events to clients.count = 0while True:await sio.sleep(10)count += 1await sio.emit('Server', {'data': "Hello, Client"})@sio.event async def connect(sid, environ):print(f'{sid} connected!')global background_task_startedif not background_task_started:sio.start_background_task(background_task)background_task_started = Trueawait sio.emit("Server", {'data': "Connect",'count': 0})@sio.event async def disconnect(sid):print('disconnect', sid)

3、下面是main代碼
在controllers目錄下,新建文件main.py

from fastapi import Depends, FastAPI, Header, HTTPException from db.mongodb_utils import close_mongo_connection, connect_to_mongo from fastapi.middleware.cors import CORSMiddleware import socketio from controllers.socket import sio import uvicorn import zmqdef get_app() -> FastAPI(title="接口",description="api",version="0.0.1" ):app = FastAPI()app.add_event_handler("startup", connect_to_mongo)app.add_event_handler("shutdown", close_mongo_connection)sio_app = socketio.ASGIApp(sio, other_asgi_app=app)app.mount('/', sio_app)return appapp = get_app()if __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8000)

4、其他文件中使用
在其他文件中使用,需要如下代碼即可

from controllers.socket import sioawait sio.emit('Server',{'data': "大鐵牛"})

總結

以上是生活随笔為你收集整理的fastapi vue socket 从其他文件调用 socket 方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。