예제 #1
0
def before_request():
    """
    Setup before request
    """
    if not getattr(g, 'redis', None):
        redis_store = FlaskRedis(app)
        try:
            redis_store.client_list()
        except ConnectionError:
            redis_store = None
        g.redis = redis_store
예제 #2
0
def before_request():
    """
    Setup before request
    """
    if not getattr(g, 'redis', None):
        redis_store = FlaskRedis(app)
        try:
            redis_store.client_list()
        except ConnectionError:
            redis_store = None
        g.redis = redis_store
예제 #3
0
파일: app.py 프로젝트: dotzero/Pad
def get_redis():
    """Opens a new database connection if there is none yet."""
    if not hasattr(g, 'redis'):
        if app.testing:
            rs = FlaskRedis.from_custom_provider(app.config['REDIS_PROVIDER'])
        else:
            rs = FlaskRedis()

        rs.init_app(app)
        g.redis = rs

    return g.redis
예제 #4
0
def get_redis():
    """Opens a new database connection if there is none yet."""
    if not hasattr(g, 'redis'):
        if app.testing:
            rs = FlaskRedis.from_custom_provider(app.config['REDIS_PROVIDER'])
        else:
            rs = FlaskRedis()

        rs.init_app(app)
        g.redis = rs

    return g.redis
예제 #5
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)
    app.dbStore = sqlite3.connect(app.config['STORE_DB'])

    app.dbStore.row_factory = sqlite3.Row

    app.iwn = IndieWebNews(app.config['KEY_BASE'])

    # register our blueprints
    app.register_blueprint(main)
    app.register_blueprint(api)

    return app
예제 #6
0
파일: __init__.py 프로젝트: bear/tenki
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)
    app.weather = Weather(app.config['OWM_API'], app.config['KEY_BASE'], app.dbRedis)

    # register our blueprints
    app.register_blueprint(main)

    return app
예제 #7
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)
    app.weather = Weather(app.config['OWM_API'], app.config['KEY_BASE'], app.dbRedis)

    # register our blueprints
    app.register_blueprint(main)

    return app
예제 #8
0
def app():
    mock_redis = FlaskRedis.from_custom_provider(FakeStrictRedis)
    flask_app = capp.create_app(True, mock_redis)
    database.config_engine('sqlite://', echo=True)
    database.init_db()
    connection = database.engine.connect()

    yield flask_app

    connection.close()
    database.Base.metadata.drop_all(bind=database.engine)
예제 #9
0
def create_app(config=None):

    app = flask.Flask(
            'threatresponse',
            static_folder='../static',
            template_folder='../templates',
            )

    app.config.from_object('config')  # Load from config.py
    app.config.from_object(settings)
    FlaskRedis(app, 'REDIS')
    return app
예제 #10
0
def create_app(testing=False):
    app = Flask(__name__)

    if testing:
        app.config['TESTING'] = True

    # Redis config
    redis_url = environ.get('REDIS_URL')
    if redis_url:
        app.config.setdefault('REDIS_URL', redis_url)

    # Mock redis
    if app.testing:
        redis = FlaskRedis.from_custom_provider(MockRedisWrapper)
    else:
        redis = FlaskRedis.from_custom_provider(OptionalRedis)
        opbeat.init_app(app)

    redis.init_app(app)

    app.register_blueprint(views)
    views.redis = redis

    return app, redis
예제 #11
0
파일: __init__.py 프로젝트: jjdelc/kaku
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """
    app = Flask(__name__)

    app.config.from_object(object_name)
    if os.environ.get('KAKU_SETTINGS', None) is not None:
        app.config.from_envvar('KAKU_SETTINGS')

    if not app.debug:
        handler   = logging.handlers.RotatingFileHandler(app.config['LOG_FILE'], maxBytes=100000000, backupCount=9)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(pathname)s:%(lineno)d -- %(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(logging.DEBUG)

        app.logger.addHandler(handler)
        app.logger.setLevel(logging.DEBUG)

        wzlog = logging.getLogger('werkzeug')
        wzlog.setLevel(logging.DEBUG)
        wzlog.addHandler(handler)

    if app.config['SITE_TEMPLATES'] is not None:
        app.jinja_loader = jinja2.FileSystemLoader(app.config['SITE_TEMPLATES'])

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    app.dbRedis = FlaskRedis.from_custom_provider(StrictRedis, app)

    # register our blueprints
    app.register_blueprint(main)
    app.register_blueprint(auth)

    app.logger.info('Flask app [%s] created' % __name__)

    return app
예제 #12
0
파일: ext.py 프로젝트: tonicbupt/ainur
# coding: utf-8

from redis import StrictRedis
from flask.ext.redis import FlaskRedis
from flask.ext.sqlalchemy import SQLAlchemy


class DecodedRedis(StrictRedis):

    @classmethod
    def from_url(cls, url, db=None, **kwargs):
        kwargs['decode_responses'] = True
        return StrictRedis.from_url(url, db, **kwargs)


rds = FlaskRedis.from_custom_provider(DecodedRedis)
db = SQLAlchemy()
예제 #13
0
from flask import Flask
from flask.ext.redis import FlaskRedis
import os

__version__ = '0.9.0'
redis_store = FlaskRedis()

template_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                            'templates')


def create_app(name=__name__,
               config={},
               static_folder='transporter/static',
               template_folder=template_dir):
    """NOTE: `db_uri` is only a temporary solution. It shall be replaced by
    something more robust."""
    app = Flask(name,
                static_folder=static_folder,
                template_folder=template_folder)
    app.secret_key = 'secret'
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URI')
    app.config['REDIS_URL'] = os.environ.get('REDIS_URL')
    app.config['DEBUG'] = True

    app.config.update(config)

    redis_store.init_app(app)

    from transporter.models import db
    db.init_app(app)
예제 #14
0
파일: app.py 프로젝트: qiu0130/MsgBoard
app = Flask(__name__)
app.config.from_object(ProductionConfig)
mako = MakoTemplates(app)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)


# redis编码设置
class DecodedRedis(StrictRedis):
    @classmethod
    def from_url(cls, url, db=None, **kwargs):
        kwargs['decode_responses'] = True
        return StrictRedis.from_url(url, db, **kwargs)

redis_store = FlaskRedis.from_custom_provider(DecodedRedis, app)


class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key = True, autoincrement = True)
    username = db.Column(db.String(128), unique = True)
    password_hashed = db.Column(db.String(256))

    def __init__(self, username, password):
        self.username = username
        self.password_hashed = bcrypt.generate_password_hash(password)

    def __repr__(self):
        return "<User %r>" % (self.username)
예제 #15
0
from flask.ext.redis import FlaskRedis
from flask.ext.assets import Environment, Bundle
from flask.ext.cache import Cache
from flask.ext.mustache import FlaskMustache

import logging
import os
import re
import settings


from werkzeug import exceptions
from werkzeug.utils import ImportStringError
from celery import Celery

redis_store = FlaskRedis()

def create_app(config=None):

    app = flask.Flask(
            'threatresponse',
            static_folder='../static',
            template_folder='../templates',
            )

    app.config.from_object('config')  # Load from config.py
    app.config.from_object(settings)
    FlaskRedis(app, 'REDIS')
    return app

예제 #16
0
    utils.setup_logging()
    app.config.update(utils.handle_env())


def get_docker_client():
    try:
        # We will attempt to get the cluster info from environment variables
        kwargs = kwargs_from_env()
        logging.debug("getting kwargs")
        kwargs['tls'].assert_hostname = False
        client = Client(**kwargs)
        logging.debug(client.version())
        return client
    except Exception:
        # If for some reason we can not connect, kill the server.
        traceback.print_exc()
        traceback.print_stack()
        logging.critical("Unable to connect to cluster. Exiting")
        exit(errno.ECONNABORTED)


app = Flask(__name__)
config()
api = Api(app)
# Pointing to our docker machine right now.
docker_client = get_docker_client()
# Using Cloudant to store our game-server data
# cloudant_client = cloudant_connect()
redis_client = FlaskRedis.from_custom_provider(DecodedRedis, app)
logging.debug("Initialized objects...")
예제 #17
0
# _*_ coding:utf-8 _*_

from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.redis import FlaskRedis
from flask.ext.bootstrap import Bootstrap
from flask.ext.login import LoginManager

__all__ = ['db', 'redis']

db = SQLAlchemy()
redis = FlaskRedis()
bootstrap = Bootstrap()
loging_manager = LoginManager()
loging_manager.session_protection = 'strong'
loging_manager.login_view = 'admin.login'
loging_manager.login_message = u'请登入帐号再进行下一步操作!'
예제 #18
0
파일: ctest.py 프로젝트: Wendy-Wu/LM
'''
Created on Mar 28, 2016

@author: wuw7
'''
#!/usr/bin/env python
import datetime
import flask
from flask.ext.redis import FlaskRedis
import redis

app = flask.Flask(__name__)
app.secret_key = 'asdf'
app.config.from_object('config')
red = FlaskRedis.from_custom_provider(redis.StrictRedis, app)
#red = redis.StrictRedis()


def event_stream():
    pubsub = red.pubsub()
    pubsub.subscribe('chat')
    # TODO: handle client disconnection.
    for message in pubsub.listen():
        print message
        yield 'data: %s\n\n' % message['data']


@app.route('/login', methods=['GET', 'POST'])
def login():
    if flask.request.method == 'POST':
        flask.session['user'] = flask.request.form['user']
예제 #19
0
import uuid
import json
from flask.ext.redis import FlaskRedis

db = FlaskRedis()


class BadFieldException(BaseException):
    pass


class NotFoundException(BaseException):
    pass


class TTLDBaseModel(object):

    __key_pattern__ = 'nothing'
    __fields__ = []
    __blacklist__ = ['_meta']

    _doc = {}

    def __init__(self, *args, **kwargs):
        pass

    def _hasfield(self, key):
        return key in self.__fields__ and key not in self.__blacklist__

    def __setitem__(self, key, val):
        if self._hasfield(key):
예제 #20
0
__author__ = 'ufarooqi'
from flask.ext.redis import FlaskRedis
from redis_collections import Dict
from .constants import REDIS2

redis_store = FlaskRedis()
redis_store2 = FlaskRedis(config_prefix=REDIS2)


def redis_dict(redis_instance, redis_list_key=None):
    if redis_list_key and redis_instance.exists(redis_list_key):
        return Dict(redis=redis_instance,
                    key=redis_instance.get(redis_list_key))
    else:
        redis_list_instance = Dict(redis=redis_instance)
        if redis_list_key:
            redis_instance.set(redis_list_key, redis_list_instance.key)
        return redis_list_instance
예제 #21
0
# -*- coding: utf-8 -*-
"""
    app
    ~~~

    TTLD app
"""

import os
from flask import Flask, render_template
from flask.ext.redis import FlaskRedis

redis_store = FlaskRedis()

app = Flask(__name__)
app.config.from_object('app_config')
if os.getenv('ENV_STAGE', 'dev') == 'test':
    app.config.from_object('tests.settings')

redis_store.init_app(app)


@app.route('/')
def index():
    return render_template('index.html', body_class="index")

@app.route('/entry')
def entry():
    return render_template('entry.html', body_class="entry")

if __name__ == '__main__':
예제 #22
0
파일: __init__.py 프로젝트: faltad/worldcup
from flask import Flask
from flask.ext.redis import FlaskRedis
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__, static_folder='static/public')

app.config.from_pyfile('../config/config.cfg')

db = SQLAlchemy(app)
redis = FlaskRedis(app)

import website.routes.index
import website.routes.matches
import website.routes.clubs
import website.routes.teams
import website.routes.error_handlers
import website.routes.webhook

import website.custom_filters

import website.models.country
import website.models.club
import website.models.position
import website.models.player
예제 #23
0
#coding:utf-8
from flask import Flask,render_template
import pymysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from flask.ext.redis import FlaskRedis
app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/movie'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY']="57a9c928-06cf-4550-8d4c-0d7adf8a8250"
# app.config['REDIS_URL'] = "redis://localhost:6379/0"
app.config['REDIS_URL'] = "redis://192.168.3.23:6379/0"
app.config['UP_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)),"static/uploads/")
app.config['FACE_DIR'] = os.path.join(os.path.abspath(os.path.dirname(__file__)),"static/uploads/users/")
app.debug = True
db = SQLAlchemy(app)
rd = FlaskRedis(app)

from app.home import home as home_blueprint
from app.admin import admin as admin_blueprint

app.register_blueprint(home_blueprint)
app.register_blueprint(admin_blueprint,url_prefix='/admin')

@app.errorhandler(404)
def page_not_found(error):
    return render_template('home/404.html'),404
예제 #24
0
from flask import Flask, g
from flask.ext.redis import FlaskRedis
from flask.ext.login import LoginManager
from flask.sessions import SecureCookieSessionInterface
from ldappool import ConnectionManager

from cosign import CoSign
from ldaptools import LDAPTools

app = Flask(__name__)
app.config.from_object('config')

flask_redis = FlaskRedis(app, 'REDIS')
ldap = LDAPTools(
    ConnectionManager(app.config["LDAP_SERVER"])
)

cosign = CoSign(app)

lm = LoginManager(app)
lm.login_view = "login"


class CustomSessionInterface(SecureCookieSessionInterface):
    """Prevent creating session from API requests."""
    def save_session(self, *args, **kwargs):
        return

app.session_interface = CustomSessionInterface()

@lm.request_loader
예제 #25
0
#coding: utf-8
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.pool import QueuePool as BaseQueuePool

db = SQLAlchemy(session_options={"autoflush":False})
from .utils.redis_geo import GeoRedis
from flask.ext.redis import FlaskRedis
redis_store = FlaskRedis.from_custom_provider(GeoRedis)

from flask.ext.celery import Celery
celery = Celery()

from dogpile.cache import make_region
regions = {
    'taxis': make_region('taxis'),
    'hails': make_region('hails'),
    'zupc': make_region('zupc').configure('dogpile.cache.memory'),
    'users': make_region('users')
}

from flask.ext.uploads import (UploadSet, configure_uploads,
            DOCUMENTS, DATA, ARCHIVES, IMAGES)
documents = UploadSet('documents', DOCUMENTS + DATA + ARCHIVES)
images = UploadSet('images', IMAGES)


from .index_zupc import IndexZUPC
index_zupc = IndexZUPC()

from .utils.cache_user_datastore import CacheUserDatastore
from .models import security
예제 #26
0
"""Initializer for Resume Parsing App"""

__author__ = 'erikfarmer'

from flask.ext.redis import FlaskRedis

from resume_parsing_service.common.utils.models_utils import init_talent_app
from resume_parsing_service.common.routes import ResumeApi, GTApis
from resume_parsing_service.common.talent_config_manager import load_gettalent_config, TalentConfigKeys
from resume_parsing_service.common.utils.talent_ec2 import get_ec2_instance_id
from resume_parsing_service.common.talent_flask import TalentFlask
from resume_parsing_service.common.models.db import db

app, logger = init_talent_app(__name__)

try:
    redis_store = FlaskRedis(app)

    from views import api, contact_api
    app.register_blueprint(api.PARSE_MOD, url_prefix=ResumeApi.URL_PREFIX)
    app.register_blueprint(contact_api.CONTACT_MOD, url_prefix='/v1')

    logger.info("Starting resume_parsing_service in %s environment",
                app.config[TalentConfigKeys.ENV_KEY])

except Exception as error:
    logger.exception(
        "Couldn't start resume_service in %s environment because: %s" %
        (app.config[TalentConfigKeys.ENV_KEY], error.message))
예제 #27
0
import logging
from flask import Flask, request
from logging.handlers import RotatingFileHandler

from flask.ext.redis import FlaskRedis

#import datetime

#Create the App
app = Flask(__name__)

#Redis Connection URL
app.config['REDIS_URL'] = "redis://*****:*****@app.route("/")
def hello():
    app.logger.error(('The referrer was {}'.format(request.referrer)))
    return "Hello World!"

예제 #28
0
    configuration = {'debug': False}

    configuration_file = pkg_resources.resource_filename(
        pkg_resources.Requirement.parse('commandment'), 'config/config.json')

    if os.path.exists(configuration_file):
        with open(configuration_file, 'r') as configuration_fh:
            loaded_configuration = json.load(configuration_fh)
        configuration.update(loaded_configuration)

    for key in ('host', 'port', 'pass', 'database'):
        keyu = key.upper()
        if os.environ.get('REDIS_%s' % keyu):
            configuration['redis'][key] = os.environ.get('REDIS_%s' % keyu)

    app = create_app(configuration['debug'], FlaskRedis(), configuration)

    if 'database' not in configuration:
        configuration['database'] = {
            'uri': app.config['DATABASE_URI'],
            'echo': app.config['DATABASE_ECHO']
        }

    if os.environ.get('COMMANDMENT_PORT'):
        configuration['port'] = int(os.environ.get('COMMANDMENT_PORT'))

    if 'port' not in configuration:
        configuration['port'] = app.config.get('PORT')

    app.logger.info(configuration)
예제 #29
0
# coding=utf-8
from flask import Flask
from flask.ext.redis import FlaskRedis
from redis import StrictRedis
from wechat_sdk import WechatConf

app = Flask(__name__)
app.config.from_envvar('MY_WECHAT_APP_SETTINGS')
redis_store = FlaskRedis.from_custom_provider(StrictRedis, app)

wechat_conf = WechatConf(
    token=app.config['WX_TOKEN'],
    appid=app.config['WX_APP_ID'],
    appsecret=app.config['WX_APP_SECRET'],
    encrypt_mode=app.config['WX_ENCRYPT_MODE'],
    encoding_aes_key=app.config['WX_ENCODING_AES_KEY']
)
예제 #30
0
app = Flask(__name__)
app.config.from_object(ProductionConfig)
mako = MakoTemplates(app)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)


# redis编码设置
class DecodedRedis(StrictRedis):
    @classmethod
    def from_url(cls, url, db=None, **kwargs):
        kwargs['decode_responses'] = True
        return StrictRedis.from_url(url, db, **kwargs)


redis_store = FlaskRedis.from_custom_provider(DecodedRedis, app)


class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), unique=True)
    password_hashed = db.Column(db.String(256))

    def __init__(self, username, password):
        self.username = username
        self.password_hashed = bcrypt.generate_password_hash(password)

    def __repr__(self):
        return "<User %r>" % (self.username)