Flask-SocketIO-Celery 示例项目教程
flask-socketio-celery-example Example based on Miguel Grinberg's flask-celery-example but using Flask-SocketIO 项目地址:https://gitcode.com/gh_mirrors/fl/flask-socketio-celery-example
1. 项目的目录结构及介绍
flask-socketio-celery-example/
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── tasks.py
│ └── templates/
│ └── index.html
├── config.py
├── requirements.txt
├── run.py
└── worker.py
app/
: 包含应用程序的主要代码。
__init__.py
: 初始化 Flask 应用。main.py
: 定义路由和 SocketIO 事件处理。tasks.py
: 定义 Celery 任务。templates/
: 存放 HTML 模板文件。
config.py
: 配置文件,包含 Flask 和 Celery 的配置。requirements.txt
: 项目依赖文件。run.py
: 启动 Flask 应用的脚本。worker.py
: 启动 Celery 工作进程的脚本。
2. 项目的启动文件介绍
run.py
from app import app, socketio
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)
该文件用于启动 Flask 应用和 SocketIO 服务。 socketio.run(app, host='0.0.0.0', port=5000)
: 启动 SocketIO 服务,监听所有网络接口的 5000 端口。
worker.py
from app import celery
if __name__ == '__main__':
celery.start()
该文件用于启动 Celery 工作进程。 celery.start()
: 启动 Celery 工作进程。
3. 项目的配置文件介绍
config.py
import os
from celery.schedules import crontab
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
CELERYBEAT_SCHEDULE = {
'say-every-5-seconds': {
'task': 'app.tasks.say',
'schedule': 5.0,
'args': ('Hello',)
},
}
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
class TestingConfig(Config):
TESTING = True
class ProductionConfig(Config):
pass
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig
}
SECRET_KEY
: Flask 应用的密钥。SQLALCHEMY_COMMIT_ON_TEARDOWN
: 每次请求结束时自动提交数据库更改。SQLALCHEMY_TRACK_MODIFICATIONS
: 禁用 SQLAlchemy 的修改跟踪。CELERY_BROKER_URL
: Celery 的消息代理 URL。CELERY_RESULT_BACKEND
: Celery 的结果后端 URL。CELERYBEAT_SCHEDULE
: Celery 的定时任务配置。DevelopmentConfig
, TestingConfig
, ProductionConfig
: 不同环境的配置类。config
: 配置字典,根据环境选择不同的配置类。
flask-socketio-celery-example Example based on Miguel Grinberg's flask-celery-example but using Flask-SocketIO 项目地址:https://gitcode.com/gh_mirrors/fl/flask-socketio-celery-example