def create_celery(app): from celery import Celery celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config['CELERY_RESULT_BACKEND']) celery.conf.update(app.config) Taskbase = celery.Task class ContextTask(Taskbase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): # task can user app return Taskbase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery
def generate_context(config): """Create the Flask app context and initializes any extensions such as Celery, Redis, SQLAlchemy, etc. :param dict config: Partial Flask config dict from generate_config(). :return: The Flask app instance. """ flask_app = Flask(__name__) flask_app.config.update(config) flask_app.config['TESTING'] = True flask_app.config['CELERY_ACCEPT_CONTENT'] = ['pickle'] if 'SQLALCHEMY_DATABASE_URI' in flask_app.config: db = SQLAlchemy(flask_app) db.engine.execute('DROP TABLE IF EXISTS celery_tasksetmeta;') elif 'REDIS_URL' in flask_app.config: redis = Redis(flask_app) redis.flushdb() Celery(flask_app) return flask_app
from flask_pagedown import PageDown from flask_ckeditor import CKEditor from flask_apscheduler import APScheduler from flask_elastic import Elastic from .jinjafilters import myfilter from flask_celery import Celery bootstrap = Bootstrap() moment = Moment() mail = Mail() db = SQLAlchemy() pagedown = PageDown() ckeditor = CKEditor() scheduler = APScheduler() elastic = Elastic() celery = Celery() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' login_manager.login_message = '请先登录。' def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) #jinja2过滤器注册 env = app.jinja_env env.filters['myfilter'] = myfilter
from flask_celery import Celery from flask_cache import Cache from flask_mail import Mail from flask_assets import Environment, Bundle from flask_admin.contrib.sqla import ModelView assets_env = Environment() main_css = Bundle('css/base.css', filters='cssmin', output='assets/css/common.css') # my_admin = Admin() bcrypt = Bcrypt() login_manager = LoginManager() rest_api = Api() flask_celery = Celery() mail = Mail() cache = Cache() # Setup the configuration for login manager. # 1. Set the login page. # 2. Set the more stronger auth-protection. # 3. Show the information when you are logging. # 4. Set the Login Messages type as `information`. # 下面设置内容会出现在重定向的页面上 login_manager.login_view = "form" login_manager.session_protection = "strong" login_manager.login_message = "Please login to access this page." login_manager.login_message_category = "info" # 设置cookie过期时间为一天,默认为一年 login_manager.remember_cookie_duration = timedelta(days=1)
from flask import Flask from flask_celery import Celery celery = Celery(__name__) def create_app(): app = Flask(__name__) app.config.from_pyfile('../config.py') celery.init_app(app) from .test import test as test_blueprint app.register_blueprint(test_blueprint) return app
#启动CELERY的WORKER专用的对象 from flask import Flask from flask_celery import Celery from config import config app = Flask('worker') app.config.from_object(config['default']) celery = Celery(app)
def test_one_dumb_line(): """For test coverage.""" flask_app = FakeApp() Celery(flask_app) assert 'celery' in flask_app.extensions
def test_multiple(flask_app): """Test attempted re-initialization of extension.""" assert 'celery' in flask_app.extensions with pytest.raises(ValueError): Celery(flask_app)
# -*- coding: utf-8 -*- # 装载静态文件 from flask_bootstrap import Bootstrap # 数据库连接 from flask_sqlalchemy import SQLAlchemy from flask_wtf.csrf import CSRFProtect from flask_cdn import CDN # 管理用户认证系统中的认证状态 from flask_login import LoginManager # 缓存 from flask_caching import Cache # 后台定时任务 from flask_celery import Celery db = SQLAlchemy() csrf = CSRFProtect() cache = Cache() # Create the Flask-Celery-Helper's instance fsk_celery = Celery() bootstrap = Bootstrap() # Flask-Login初始化 login_manager = LoginManager() # cdn cdn = CDN()
@twitter.tokengetter def get_twitter_token(token=None): return session.get('twitter_token') # Flask-login intialization login_manager = LoginManager() login_manager.login_view = 'main.login' login_manager.session_protection = 'strong' login_manager.login_message = 'Please login to access this page.' login_manager.login_message_category = 'info' @login_manager.user_loader def load_user(user_id): from tinyblog.models import User return User.query.filter_by(id=user_id).first() # Flask-Principal initialization principals = Principal() admin_permission = Permission(RoleNeed('admin')) poster_permission = Permission(RoleNeed('poster')) default_permission = Permission(RoleNeed('default')) # Flask-Celery-helper initialization flask_celery_helper = Celery() # Flask-Mail initialization mail = Mail()
from flask_logconfig import LogConfig from flask_socketio import SocketIO bcrypt = Bcrypt() csrf_protect = CSRFProtect() login_manager = LoginManager() db = SQLAlchemy() debug_toolbar = DebugToolbarExtension() marshmallow = Marshmallow( ) # http://marshmallow-sqlalchemy.readthedocs.io/en/latest/ 使用文档说明 api = Api(decorators=[csrf_protect.exempt]) # csrf json = FlaskJSON() # JSON logcfg = LogConfig() # LOG socket_io = SocketIO() # sockt_io mail = Mail() celery = Celery() # 异步任务系统 def api_route(self, *args, **kwargs): """ api_route """ def wrapper(cls): self.add_resource(cls, *args, **kwargs) return cls return wrapper api.route = types.MethodType(api_route, api)
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' @Author: Kin P. Lam @LastEditors: Kin P. Lam @Date: 2019-04-17 00:17:05 @LastEditTime: 2019-05-14 00:13:46 ''' from flask_celery import Celery from conf import config cly = Celery()
from flask_debugtoolbar import DebugToolbarExtension from flask_caching import Cache from flask_assets import Environment, Bundle from flask_admin import Admin from flask_mail import Mail from flask_youku import YouKu from flask import request from gzip import GzipFile from io import BytesIO bcrypt = Bcrypt() oid = OpenID() login_manager = LoginManager() # 初始化 principals = Principal() rest_api = Api() celery = Celery() # 对flask-celery-helper进行实例化 debug_toolbar = DebugToolbarExtension() cache = Cache() admin = Admin() mail = Mail() # login_manger配置修改 login_manager.login_view = 'main.login' login_manager.session_protection = 'strong' login_manager.login_message = '请穿上马甲再上场' login_manager.login_message_category = 'Info' # principal配置,定义三种角色 admin_permission = Permission(RoleNeed('admin')) poster_permission = Permission(RoleNeed('poster')) default_permission = Permission(RoleNeed('default'))
# coding: utf-8 from flask_celery import Celery celery = Celery() # celery 对象