Exemple #1
0
def create():
    """Create application.
    """

    # Create application
    app = Flask('service', static_folder=None)
    app.config['DEBUG'] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['SECRET_KEY'] = 'openspending rocks'
    sess.init_app(app)

    # Register blueprints
    print("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix='/datastore')
    print("Creating API Loader Blueprint")
    app.register_blueprint(apiload.create(), url_prefix='/hooks/load/')
    print("Creating Authentication Blueprint")
    app.register_blueprint(authentication.create(), url_prefix='/oauth/')
    print("Creating Authorization Blueprint")
    app.register_blueprint(authorization.create(), url_prefix='/permit/')
    print("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix='/search/')

    # Return application
    return app
Exemple #2
0
def create():
    """Create application.
    """

    # Create application
    app = Flask("service", static_folder=None)
    app.config["DEBUG"] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "openspending rocks"
    sess.init_app(app)

    # Register blueprints
    logger.info("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix="/datastore/")
    logger.info("Creating Package Blueprint")
    app.register_blueprint(package.create(), url_prefix="/package/")
    logger.info("Creating Authentication Blueprint")
    app.register_blueprint(user.oauth_create(), url_prefix="/oauth/")
    logger.info("Creating Users Blueprint")
    app.register_blueprint(user.create(), url_prefix="/user/")
    logger.info("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix="/search/")

    # Return application
    return app
Exemple #3
0
def init_app(init=None,
             config=None,
             pyfile=None,
             template_folder='templates',
             index=False,
             error=True,
             is_web=False,
             is_api=False):
    """ 创建应用 """

    app = Flask(__name__, template_folder=template_folder)
    if config:
        app.config.from_object(config)
    if pyfile:
        app.config.from_pyfile(pyfile)

    ENVVAR = app.config.get('ENVVAR')
    if ENVVAR and os.environ.get(ENVVAR):
        app.config.from_envvar(app.config['ENVVAR'])

    if app.debug:
        app.config.setdefault('DEBUG_TB_ENABLED', True)
        app.config.setdefault('DEBUG_TB_PANELS', DEBUG_TB_PANELS)
        app.config.setdefault('DEBUG_TB_INTERCEPT_REDIRECTS', False)

    DebugToolbarExtension(app)

    app.config.setdefault('SESSION_REFRESH_EACH_REQUEST', False)
    app.is_web = is_web
    app.is_api = is_api
    app.is_back = os.environ.get('CHIKI_BACK') == 'true'
    app.static_folder = app.config.get('STATIC_FOLDER')
    app.mail = Mail(app)

    def get_data_path(name):
        return os.path.abspath(
            os.path.join(app.config.get('DATA_FOLDER'), name))

    if app.config.get('USER_AGENT_LIMIT'):

        @app.before_request
        def before_request():
            if request.path == current_app.config.get('WEROBOT_ROLE'):
                return
            if not app.debug and 'micromessenger' not in request.headers[
                    'User-Agent'].lower():
                return error_msg('请用微信客户端扫一扫')

    app.get_data_path = get_data_path

    init_babel(app)
    init_redis(app)

    if app.config.get('SESSION_TYPE'):
        Session(app)

    init_jinja(app)
    init_logger(app)
    init_oauth(app)
    init_page(app)
    db.init_app(app)
    media.init_app(app)

    with app.app_context():
        cm.init_app(app)
        Choices.init()

    if callable(init):
        init(app)

    @app.context_processor
    def context_processor():
        return dict(Item=Item, Menu=Menu)

    if error:
        init_error_handler(app)

    if index:

        @app.route('/')
        def index():
            return redirect(app.config.get('INDEX_REDIRECT'))

    blueprint = Blueprint('chiki',
                          __name__,
                          template_folder=os.path.join(TEMPLATE_ROOT, 'chiki'))
    app.register_blueprint(blueprint)

    if app.is_back:

        @app.route('/chiki_back')
        def chiki_back():
            return 'true'

    with app.app_context():
        if hasattr(app, 'user_manager'):
            user = um.models.User.objects(id=100000).first()
            if not user:
                user = um.models.User(id=100000,
                                      phone='13888888888',
                                      password='******',
                                      nickname=app.config.get('SITE_NAME'))
                user.save()
            if not user.avatar and os.path.exists(
                    app.get_data_path('imgs/logo.jpg')):
                with open(app.get_data_path('imgs/logo.jpg')) as fd:
                    user.avatar = dict(stream=StringIO(fd.read()),
                                       format='jpg')
                user.save()

    return app
Exemple #4
0
from flask import Flask, session as login_session
from flask.ext.login import LoginManager
from flask.ext.session import Session
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_wtf.csrf import CsrfProtect
import default_config

# Gives the imports local variable names
bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
csrf = CsrfProtect()
lm = LoginManager()
fs = Session()


# Creates the app
def create_app(config_name):
    app = Flask(__name__)
    # Gets the apps globals from config file
    app.config.from_object(default_config)

    # initiates the different modules
    bootstrap.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    csrf.init_app(app)
    lm.init_app(app)
    fs.init_app(app)
Exemple #5
0
from flask import Flask, flash, render_template, request, redirect, \
                  url_for, session, send_file
from flask.ext.session import Session
from werkzeug.utils import secure_filename
from score_code import ScoreSA
import tempfile
import os
import json

ALLOWED_EXTENSIONS = set(['xlsx', 'xlsm', 'xlt'])

app = Flask(__name__)
sess = Session()

with open('/home/ubuntu/SA_scorer_webapp/key.json') as f:
    key_file = json.load(f)

app.secret_key = key_file['secret_key']
app.config['SESSION_TYPE'] = 'filesystem'


def allowed_file(filename):
    '''
    input: filename
    output: True or False

    checks to make sure an uploaded file is included in allowed filenames
    '''
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
Exemple #6
0
"""

from flask import Flask
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
#from flask_login import LoginManager
from config import config
from flask.ext.session import Session
from flask.ext.security import Security

from flask.ext.security import SQLAlchemyUserDatastore
from flask.ext.cache import Cache

moment = Moment()
db = SQLAlchemy()
session = Session()
security = Security()
cache = Cache()
from .models import User, Role
user_datastore = SQLAlchemyUserDatastore(db, User, Role)

#login_manager = LoginManager()
#login_manager.session_protection = 'strong'
#login_manager.login_view = 'auth.login'
from flask.ext.security.utils import encrypt_password, verify_password
from flask_jwt import JWT


def authenticate(username, password):
    user = user_datastore.find_user(email=username)
    if user and user.confirmed_at and username == user.email and verify_password(
Exemple #7
0
def create_app(config_name):
    # 配置日志,并且传入配置名字,以便能获取到指定配置所对应的日志等级
    setup_log(config_name)
    # 创建Flask对象
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(config[config_name])
    # 通过app初始化
    db.init_app(app)
    # 初始化 redis 存储对象
    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,
                              port=config[config_name].REDIS_PORT,
                              decode_responses=True)
    # 开启当前项目 CSRF 保护,只做服务器验证功能
    # 帮我们做了:从cookie中取出随机值,从表单中取出随机,然后进行校验,并且响应校验结果
    # 我们需要做:1. 在返回响应的时候,往cookie中添加一个csrf_token,2. 并且在表单中添加一个隐藏的csrf_token
    # 而我们现在登录或者注册不是使用的表单,而是使用 ajax 请求,所以我们需要在 ajax 请求的时候带上 csrf_token 这个随机值就可以了
    CSRFProtect(app)
    # 设置session保存指定位置
    Session(app)

    # 初始化数据库
    #  在Flask很多扩展里面都可以先初始化扩展的对象,然后再去调用 init_app 方法去初始化
    from info.utils.common import do_index_class
    # 添加自定义过滤器
    app.add_template_filter(do_index_class, "index_class")

    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def page_not_fount(e):
        user = g.user
        data = {"user": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    @app.after_request
    def after_request(response):
        # 生成随机的csrf_token的值
        csrf_token = generate_csrf()
        # 设置一个cookie
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu, url_prefix="/admin")

    return app
Exemple #8
0
from flask import Flask
from flask.ext.session import Session

app = Flask(__name__)

app.config.from_object('config')
Session(app)

from app import views
Exemple #9
0
def init_app(init=None,
             config=None,
             pyfile=None,
             template_folder='templates',
             index=False,
             error=True,
             is_web=False,
             is_api=False,
             manager=False):
    """ 创建应用 """
    app = Flask(__name__, template_folder=template_folder)
    if os.environ.get('LOGGER_DEBUG'):
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        handler.setFormatter(logging.Formatter(DEBUG_LOG_FORMAT))
        app.logger.addHandler(handler)
        app.logger.setLevel(logging.DEBUG)

    init_db(db)

    if config:
        app.config.from_object(config)
    if pyfile:
        app.config.from_pyfile(pyfile)

    ENVVAR = app.config.get('ENVVAR')
    if ENVVAR and os.environ.get(ENVVAR):
        env = os.environ.get(ENVVAR)
        for pyfile in env.split('|'):
            if pyfile.startswith('./'):
                pyfile = os.path.join(os.getcwd(), pyfile)
            app.logger.info('load config pyfile: %s' % pyfile)
            app.config.from_pyfile(pyfile)

    if app.debug:
        app.config.setdefault('DEBUG_TB_ENABLED', True)
        app.config.setdefault('DEBUG_TB_PANELS', DEBUG_TB_PANELS)
        app.config.setdefault('DEBUG_TB_INTERCEPT_REDIRECTS', False)

    DebugToolbarExtension(app)

    app.config.setdefault('SESSION_REFRESH_EACH_REQUEST', False)
    app.is_web = is_web
    app.is_api = is_api
    app.is_admin = not is_web and not is_api
    app.is_back = os.environ.get('CHIKI_BACK') == 'true'
    app.static_folder = app.config.get('STATIC_FOLDER')
    app.mail = Mail(app)

    def get_data_path(name):
        return os.path.abspath(
            os.path.join(app.config.get('DATA_FOLDER'), name))

    if app.config.get('USER_AGENT_LIMIT', False):

        @app.before_request
        def before_request():
            if request.path == current_app.config.get('WEROBOT_ROLE'):
                return

            ua = request.headers['User-Agent'].lower()
            if not app.debug and 'micromessenger' not in ua:
                return error_msg('请用微信客户端扫一扫')

    app.get_data_path = get_data_path

    init_babel(app)
    init_redis(app)

    if not app.config.get('CACHE_TYPE'):
        app.config['CACHE_TYPE'] = 'simple'
    cache.init_app(app)

    if app.config.get('SESSION_TYPE'):
        Session(app)

    init_jinja(app)
    init_logger(app)
    init_oauth(app)
    init_third(app)
    init_page(app)

    db.init_app(app)
    media.init_app(app)

    if app.is_admin and not manager:
        with app.app_context():
            cm.init_app(app)
            Choices.init()

    global inits
    for i in inits:
        i(app)

    if callable(init):
        init(app)

    @app.context_processor
    def context_processor():
        return dict(Item=Item, Menu=Menu, url_for=url_for, ImageItem=ImageItem)

    if error:
        init_error_handler(app)

    if index:

        @app.route('/')
        def index():
            return redirect(app.config.get('INDEX_REDIRECT'))

    blueprint = Blueprint('chiki',
                          __name__,
                          template_folder=os.path.join(TEMPLATE_ROOT, 'chiki'))
    app.register_blueprint(blueprint)

    if app.is_back:

        @app.route('/chiki_back')
        def chiki_back():
            return 'true'

    if app.is_admin and not manager:
        with app.app_context():
            if hasattr(app, 'user_manager'):
                user = um.models.User.objects(id=100000).first()
                if not user:
                    user = um.models.User(id=100000,
                                          phone='13888888888',
                                          password='******',
                                          nickname=app.config.get('SITE_NAME'))
                    user.tid = user.create_tid()
                    user.save()
                if not user.avatar and os.path.exists(
                        app.get_data_path('imgs/logo.jpg')):
                    with open(app.get_data_path('imgs/logo.jpg')) as fd:
                        user.avatar = dict(stream=StringIO(fd.read()),
                                           format='jpg')
                    user.save()

    @app.route('/1.gif')
    def gif():
        return send_file(DATA_ROOT + '/1.gif',
                         cache_timeout=0,
                         add_etags=False,
                         mimetype='image/gif')

    @app.route('/test/error')
    def test_error():
        raise ValueError('testing!!!')

    @app.route('/trace/log', methods=['POST'])
    def trace_log():
        user = None
        if current_user.is_authenticated():
            user = current_user.id

        if current_app.config.get('FAST_MODE') is True:
            return json_success()

        TraceLog(
            user=user,
            key=request.form.get('key', ''),
            tid=request.form.get('tid', ''),
            label=request.form.get('label', ''),
            value=request.form.get('value', ''),
        ).save()
        return json_success()

    @app.route('/complaint/choose')
    @login_required
    def complaint_choose():
        complaint = sorted(Complaint.TYPE.DICT.iteritems(),
                           key=lambda x: x[1],
                           reverse=True)
        return render_template('complaint/choose.html', type=complaint)

    @app.route('/complaint/desc/')
    @login_required
    def complaint_desc():
        types = request.args.get('type', '')
        return render_template('complaint/desc.html', types=types)

    @app.route('/complaint/refer', methods=['POST'])
    @login_required
    def complaint_refer():
        types = request.form.get('type', '')
        content = request.form.get('content', '')
        complaints = Complaint(
            user=current_user.id,
            content=content,
            type=types,
            active=True,
        )
        complaints.create()
        complaints.save()
        return json_success(msg='success', num=complaints.id)

    @app.route('/complaint/save/')
    @login_required
    def complaint_save():
        num = request.args.get('num', '')
        return render_template('complaint/refer.html', num=num)

    @app.route('/complaint/active')
    @login_required
    def complaint_active():
        complaints = Complaint.objects(user=current_user.id,
                                       active=True).first()
        if complaints:
            complaints.user.complaint = True
            complaints.user.save()
        return ''

    init_db(db)

    return app
Exemple #10
0
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
import datetime
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.metrics import pairwise_distances_argmin_min
from flask.ext.session import Session

minnow = "static/minnow.csv"
trained_minnow = pd.read_csv(minnow)
trained_minnow.fillna(trained_minnow.mean(), inplace=True)
sess = Session()

labelEncoder = LabelEncoder()
labelEncoder.fit(trained_minnow['Survived'])
trained_minnow['Survived'] = labelEncoder.transform(trained_minnow['Survived'])
global_kmeans = ''
global_x = ''
global_mydict = ''

# print(trained_minnow.info())

# EB looks for an 'application' callable by default.
application = Flask(__name__)

@application.route('/', methods=['GET'])
def myapp():
Exemple #11
0
mail = Mail()

from flask.ext.migrate import Migrate
migrate = Migrate()

from flask_redis import Redis
redis_store = Redis()

from boto.s3.connection import S3Connection
s3 = S3Connection()

from flask.ext.security import Security
security = Security()

from flask.ext.session import Session
redis_session = Session()

from celery import Celery


def make_celery(app):
    celery = Celery(app.import_name)
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
Exemple #12
0
                   format_messages, Order, Scene)
from logger import ilogger as logger

memcache_hosts = os.getenv('ESPA_MEMCACHE_HOST', '127.0.0.1:11211').split(',')
cache = memcache.Client(memcache_hosts, debug=0)

espaweb = Flask(__name__)
espaweb.config.from_envvar('ESPAWEB_SETTINGS', silent=False)
espaweb.secret_key = espaweb.config['SECRET_KEY']
espaweb.config['SESSION_TYPE'] = 'memcached'
espaweb.config['SESSION_MEMCACHED'] = cache
espaweb.config['SESSION_PERMANENT'] = False
espaweb.config['PERMANENT_SESSION_LIFETIME'] = timedelta(minutes=120)
espaweb.config['SESSION_COOKIE_SECURE'] = True

Session(espaweb)
api_base_url = os.getenv('ESPA_API_HOST', 'http://localhost:4004/api/v1')


# Note: ERS SSO provides the governing decryption algorithm used in operations
class ErsSSO(object):
    def __init__(self, *args, **kwargs):
        pass

    def user(self, *args, **kwargs):
        return ('0', '1')


if os.path.exists(espaweb.config.get('ERS_SSO_PYPATH', '')):
    sys.path.insert(1, espaweb.config.get('ERS_SSO_PYPATH'))
    from ers import ErsSSO
Exemple #13
0
 def init_session(self):
     self.config['SESSION_MONGODB'] = db.init_mongodb()
     self.config['SESSION_MONGODB_DB'] = "app_sessions"
     self.config['SESSION_MONGODB_COLLECT'] = "sessions"
     Session(self)
Exemple #14
0
def create_app(config_name):
    app = Flask(__name__)

    app.config.from_object(config[config_name])
    try:
        load_dotenv('.env')
        app.config.update(parse_dotenv('.env'))
    except TypeError:
        print('Error parsing .env')
    app.config['SECRET_KEY']
    app.config['SESSION_TYPE'] = 'filesystem'
    app.config['MONGODB_SETTINGS'] = {
        'db': app.config['MONGO_DBNAME'],
        'host': app.config['MONGO_URI']
    }

    #MAIL
    app.config.update(
        DEBUG=True,
        #EMAIL SETTINGS
        MAIL_SERVER=app.config['MAIL_SERVER'],
        MAIL_PORT=app.config['MAIL_PORT'],
        MAIL_USE_TLS=False,
        MAIL_USE_SSL=True,
        MAIL_USERNAME=app.config['MAIL_USERNAME'],
        MAIL_PASSWORD=app.config['MAIL_PASSWORD'])

    mail = Mail(app)

    config[config_name].init_app(app)
    bootstrap.init_app(app)
    # mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    Session(app)

    # additional _init_.py file in each of these modules
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .browse import browse as browse_blueprint
    app.register_blueprint(browse_blueprint)

    from .literature import lit as lit_blueprint
    app.register_blueprint(lit_blueprint)

    from .preferences import pref as pref_blueprint
    app.register_blueprint(pref_blueprint)

    from .search import search as search_blueprint
    app.register_blueprint(search_blueprint)

    from .user import user as user_blueprint
    app.register_blueprint(user_blueprint)

    # attach routes and custom error pages here
    return app
Exemple #15
0
def init(conf=None, debug=0, logfile=None, gunicorn=True, unittest=False):
    """Initialize the whole application.

    :param conf: Configuration file to use
    :type conf: str

    :param debug: Enable verbose output
    :type debug: int

    :param logfile: Store the logs in the given file
    :type logfile: str

    :param gunicorn: Enable gunicorn engine instead of flask's default
    :type gunicorn: bool

    :returns: A :class:`burpui.server.BUIServer` object
    """
    from flask.ext.login import LoginManager
    from flask.ext.bower import Bower
    from .utils import basic_login_from_request
    from .server import BUIServer as BurpUI
    from .routes import view
    from .api import api, apibp

    if not unittest:
        from ._compat import patch_json
        patch_json()

    if gunicorn:
        from gevent import monkey
        monkey.patch_all()

    # We initialize the core
    app = BurpUI()
    app.gunicorn = gunicorn

    app.config['CFG'] = None

    app.secret_key = ('VpgOXNXAgcO81xFPyWj07ppN6kExNZeCDRShseNzFKV7ZCgmW2/eLn6x'
                      'Slt7pYAVBj12zx2Vv9Kw3Q3jd1266A==')
    app.jinja_env.globals.update(
        isinstance=isinstance,
        list=list,
        version_id='{}-{}'.format(__version__, __release__)
    )

    # The debug argument used to be a boolean so we keep supporting this format
    if isinstance(debug, bool):
        if debug:
            debug = logging.DEBUG
        else:
            debug = logging.NOTSET
    else:
        levels = [
            logging.NOTSET,
            logging.ERROR,
            logging.WARNING,
            logging.INFO,
            logging.DEBUG
        ]
        if debug >= len(levels):
            debug = len(levels) - 1
        if not debug:
            debug = 0
        debug = levels[debug]

    if debug != logging.NOTSET and not gunicorn:  # pragma: no cover
        app.config['DEBUG'] = True and not unittest
        app.config['TESTING'] = True and not unittest

    if logfile:
        from logging import Formatter
        from logging.handlers import RotatingFileHandler
        file_handler = RotatingFileHandler(
            logfile,
            maxBytes=1024 * 1024 * 100,
            backupCount=20
        )
        if debug < logging.INFO:
            LOG_FORMAT = (
                '-' * 80 + '\n' +
                '%(levelname)s in %(module)s.%(funcName)s ' +
                '[%(pathname)s:%(lineno)d]:\n' +
                '%(message)s\n' +
                '-' * 80
            )
        else:
            LOG_FORMAT = ('[%(asctime)s] %(levelname)s in '
                          '%(module)s.%(funcName)s: %(message)s')
        file_handler.setLevel(debug)
        file_handler.setFormatter(Formatter(LOG_FORMAT))
        app.logger.addHandler(file_handler)

    # Still need to test conf file here because the init function can be called
    # by gunicorn directly
    app.config['CFG'] = lookup_config(conf)

    app.setup(app.config['CFG'])

    if gunicorn:  # pragma: no cover
        from werkzeug.contrib.fixers import ProxyFix
        if app.storage and app.storage.lower() == 'redis':
            if app.redis:
                part = app.redis.split(':')
                host = part[0]
                try:
                    port = int(part[1])
                except:
                    port = 6379
            else:
                host = 'localhost'
                port = 6379
            try:
                from redis import Redis
                from flask.ext.session import Session
                red = Redis(host=host, port=port)
                app.config['SESSION_TYPE'] = 'redis'
                app.config['SESSION_REDIS'] = red
                ses = Session()
                ses.init_app(app)
            except:
                pass
            api.cache.init_app(
                app,
                config={
                    'CACHE_TYPE': 'redis',
                    'CACHE_REDIS_HOST': host,
                    'CACHE_REDIS_PORT': port,
                    'CACHE_REDIS_DB': 1
                }
            )
            # clear cache at startup in case we removed or added servers
            with app.app_context():
                api.cache.clear()
        else:
            api.cache.init_app(app)

        app.wsgi_app = ProxyFix(app.wsgi_app)
    else:
        api.cache.init_app(app)

    # Then we load our routes
    view.init_bui(app)
    view.__url__ = __url__
    view.__doc__ = __doc__
    app.register_blueprint(view)

    # We initialize the API
    api.init_bui(app)
    api.version = __version__
    api.release = __release__
    api.__url__ = __url__
    api.__doc__ = __doc__
    app.register_blueprint(apibp)

    # And the login_manager
    app.login_manager = LoginManager()
    app.login_manager.login_view = 'view.login'
    app.login_manager.login_message_category = 'info'
    app.login_manager.session_protection = 'strong'
    app.login_manager.init_app(app)

    app.config.setdefault(
        'BOWER_COMPONENTS_ROOT',
        os.path.join('static', 'vendor')
    )
    app.config.setdefault('BOWER_REPLACE_URL_FOR', True)
    bower = Bower()
    bower.init_app(app)

    @app.login_manager.user_loader
    def load_user(userid):
        """User loader callback"""
        if app.auth != 'none':
            return app.uhandler.user(userid)
        return None  # pragma: no cover

    @app.login_manager.request_loader
    def load_user_from_request(request):
        """User loader from request callback"""
        if app.auth != 'none':
            return basic_login_from_request(request, app)

    return app
Exemple #16
0
def create_app(config_name):
    app = Flask(__name__)

    # get().根据字典的key,获取到字典的value
    config_class = config_map.get(config_name)

    # 从对象添加配置
    app.config.from_object(config_class)

    db.init_app(app)  # 另一种方式创建db数据库对象
    # 等同于db = SQLAlchemy(app)

    # 创建redis(存储验证码,存储短信验证码和图片验证码)
    global redis_store
    redis_store = redis.StrictRedis(host=config_class.REDIS_HOST,
                                    port=config_class.REDIS_PORT,
                                    decode_responses=True)

    # 导入session:目的用来进行持久化操作,不需要每次都让用户进行登陆,我们需要把session存储到redis当中
    Session(app)
    # 开启CSRF保护
    CSRFProtect(app)

    # 使用请求钩子,在每次请求服务器的数据的时候,我们把返回值里面添加一个csrf_token
    @app.after_request
    def after_request(response):
        # 生成csrf_token
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def err_404_handler(error):
        """拦截网络所有的异常"""
        user = g.user
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/404.html", data=data)

    from info.utils.common import do_index_class
    # 添加到模板过滤器
    app.add_template_filter(do_index_class, "indexClass")

    # 注册首页的蓝图
    from info.index import index_blue
    app.register_blueprint(index_blue)

    # 注册验证码蓝图
    from info.passport import passport_blue
    app.register_blueprint(passport_blue)

    # 注册新闻详情蓝图
    from info.news import news_blue
    app.register_blueprint(news_blue)

    # 注册个人中心蓝图
    from info.user import user_blue
    app.register_blueprint(user_blue)

    # 注册后台管理系统蓝图
    from info.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
Exemple #17
0
from flask import Flask, session
from flask.ext.session import Session
from config import Config

app = Flask(__name__)
# app.config.from_object(Config)
sess = Session()
app.secret_key = 'You Will Never Guess'
# bootstrap = Bootstrap(app)

from app import routes
Exemple #18
0
def create_app(config_path):
    # setup flask
    app = Flask('jazzband')

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('error.html'), 404

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('forbidden.html'), 403

    @app.errorhandler(500)
    def error(error):
        return render_template('error.html'), 500

    @app.route('/favicon.ico')
    def favicon():
        filename = 'favicon.ico'
        cache_timeout = app.get_send_file_max_age(filename)
        return send_from_directory(os.path.join(app.static_folder, 'favicons'),
                                   filename,
                                   mimetype='image/vnd.microsoft.icon',
                                   cache_timeout=cache_timeout)

    # load decoupled config variables
    app.config.from_object(config_path)

    from .models import db, User, Project, EmailAddress
    db.init_app(app)

    from flask_migrate import Migrate
    Migrate(app, db)

    from .admin import admin, JazzbandModelView
    admin.init_app(app)
    admin.add_view(JazzbandModelView(User, db.session))
    admin.add_view(JazzbandModelView(Project, db.session))
    admin.add_view(JazzbandModelView(EmailAddress, db.session))

    if 'OPBEAT_SECRET_TOKEN' in os.environ:
        from opbeat.contrib.flask import Opbeat
        Opbeat(app, logging=True)

    if not app.debug:
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

    from whitenoise import WhiteNoise
    app.wsgi_app = WhiteNoise(
        app.wsgi_app,
        root=app.static_folder,
        prefix=app.static_url_path,
    )

    # setup github-flask
    from .github import github
    github.init_app(app)

    from .hooks import hooks
    hooks.init_app(app)

    # setup webassets
    from .assets import assets
    assets.init_app(app)

    # setup session store
    from flask.ext.session import Session
    Session(app)

    from flask.ext.compress import Compress
    Compress(app)

    from .content import about_pages, news_pages, content
    about_pages.init_app(app)
    news_pages.init_app(app)
    app.register_blueprint(content)

    from .account import account, login_manager
    app.register_blueprint(account)
    login_manager.init_app(app)

    from .members import members
    app.register_blueprint(members)

    from .projects import projects
    app.register_blueprint(projects)

    @app.context_processor
    def app_context_processor():
        return {
            'about': about_pages,
            'news': news_pages,
            'User': User,
            'Project': Project,
        }

    @app.after_request
    def add_vary_header(response):
        response.vary.add('Cookie')
        response.headers['Jazzband'] = "We're all part of the band"
        return response

    return app
Exemple #19
0
import os
from flask import Flask, redirect, url_for, render_template, request, session
from flask.ext.session import Session

from werkzeug import secure_filename
import indicoio

# hi
"What's up! Thanks for reaching out Dillon, made my day"

app = Flask(__name__)
# session allows you to share variables between pages
# by saving it to the server's storage, often in a lightweight
# database. You can see at the bottom it's just saving using
# the filesystem at the moment.
sess = Session()

ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg"])


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        session['name'] = request.form.get('name', default='anon')
        path = os.path.dirname(os.path.abspath(__file__)) + "/static/img/pictures/" + session['name']
Exemple #20
0
 def init_session(self):
     self.config['SESSION_MONGODB'] = db.init_mongodb()
     self.config['SESSION_MONGODB_DB'] = "app_sessions"
     self.config['SESSION_MONGODB_COLLECT'] = "sessions"
     self.config['SESSION_MONGODB']['app_sessions']['sessions'].create_index('id')
     Session(self)