Пример #1
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
import pymysql
from flask_restful import Api
from flask_migrate import Migrate
from flask_wtf import CSRFProtect  ## 导入csrf保护

pymysql.install_as_MySQLdb()
app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))  ##当前文件  项目所在的根目录
app.config.from_pyfile("settings.py")  ## 使用python文件做配置文件
app.config.from_object("settings.TestConfig")
app.secret_key = "dsfdsfdsfdsfs"
db = SQLAlchemy(app)
api = Api(app)  ## 负责收集路由 收集类视图的注册信息
migrate = Migrate(app, db)  ###  安装数据库管理插件
csrf = CSRFProtect(app)  ## 使用csrf保护
Пример #2
0
from flask_mail import Mail
from flask_rq import RQ
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_migrate import Migrate


from app.assets import app_css, app_js, vendor_css, vendor_js
from config import config as Config

basedir = os.path.abspath(os.path.dirname(__file__))

mail = Mail()
db = SQLAlchemy()
migrate = Migrate()
csrf = CSRFProtect()

#compress = Compress()

# Set up Flask-Login
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'account.login'


def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')
Пример #3
0
def create_app(config_name):
    global user_datastore
    app = Flask(__name__)

    app.config.from_object(app_config[config_name])

    csrf = CSRFProtect()
    csrf.init_app(app)

    assets = Environment(app)
    create_assets(assets)

    via = Via()
    via.init_app(app)

    # Ipload in several models - - - -

    from app.user import user_photo
    from app.restaurant import restaurant_photo
    from app.food import food_photo

    configure_uploads(app, (restaurant_photo, food_photo, user_photo))

    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    if not database_exists(engine.url):
        create_database(engine.url)

    security = Security(app, user_datastore, register_form=SecurityRegisterForm)

    create_security_admin(app=app, path=os.path.join(os.path.dirname(__file__)))

    with app.app_context():
        db.init_app(app)
        #Conditionally create admin/end_user
        db.create_all()
        user_datastore.find_or_create_role(name='admin', description='Administrator')

        db.session.commit()
        user_datastore.find_or_create_role(name='end-user', description='End user')
        db.session.commit()

        # Create two Users for testing purposes -- unless they already exists.
        # In each case, use Flask-Security utility function to encrypt the password.
        encrypted_password = utils.encrypt_password('password')
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(email='*****@*****.**', password=encrypted_password)
        if not user_datastore.get_user('*****@*****.**'):
            user_datastore.create_user(email='*****@*****.**', password=encrypted_password)

        # Commit any database changes; the User and Roles must exist before we can add a Role to the User
        db.session.commit()

        # Give one User has the "end-user" role, while the other has the "admin" role. (This will have no effect if the
        # Users already have these Roles.) Again, commit any database changes.
        user_datastore.add_role_to_user('*****@*****.**', 'end-user')
        user_datastore.add_role_to_user('*****@*****.**', 'admin')
        db.session.commit()


    @app.route('/', methods=['GET'])
    @app.route('/home', methods=['GET'])    
    def index():
        return render_template('index.html')

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

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('error/404.html', title='Page Not Found'), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        db.session.rollback()
        return render_template('error/500.html', title='Server Error'), 500

    return app
Пример #4
0
# Import flask and template operators
from flask import Flask, render_template, url_for

from flask_bootstrap import Bootstrap
from flask_wtf import CSRFProtect, Form
from .config import config
from flask_admin.base import Admin, MenuLink
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin.contrib.sqla import ModelView

bootstrap = Bootstrap()
csrf_token = CSRFProtect()
admin = Admin(template_mode='bootstrap3', name='', url='/')


class MyFileAdmin(FileAdmin):
    form_base_class = Form
    can_upload = False
    can_mkdir = False
    can_rename = True


def create_app():
    app = Flask(__name__)

    app.config.from_object(config)
    bootstrap.init_app(app)
    csrf_token.init_app(app)
    admin.init_app(app)

    from .views import views as views_blueprint
Пример #5
0
 def configure_wtf(self):
     if self.config["WTF_CSRF_ENABLED"]:
         csrf = CSRFProtect(self.flask_app)
         csrf_exempt_list = self.config["WTF_CSRF_EXEMPT_LIST"]
         for ex in csrf_exempt_list:
             csrf.exempt(ex)
Пример #6
0
def create_app(config_name):
    setup_log(config_name)
    # 创建flask对象
    app = Flask(__name__)

    # 添加参数到flask对象中
    app.config.from_object(config[config_name])

    # mysql数据库实例绑定
    db.init_app(app)

    # redis数据库实例的创建,Return a Redis client object
    global redis_store
    redis_store = redis.StrictRedis(host=Config.REDIS_HOST,
                                    port=Config.REDIS_PORT,
                                    decode_responses=True)

    # 对flask对象开启CSRFProtect保护
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 导入Session以便把flask对象中的session数据存入redis数据库
    Session(app)

    # 主页蓝图注册到app中
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    # 登录和注册蓝图注册到app中
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

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

    # 注册排行榜的根据索引进行匹配样式的过滤器
    from info.utils.common import click_list_class_filter
    app.add_template_filter(click_list_class_filter, "indexClass")

    # 注册用户个人中心蓝图
    from info.modules.user import profile_blue
    app.register_blueprint(profile_blue)
    from info.utils.common import user_login_data

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

    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    return app
Пример #7
0
def create_app(config_name):
    app = Flask(__name__)
    # 加载配置
    app.config.from_object(config[config_name])
    # 初始化mysql数据库对象
    db.init_app(app)
    # 初始化Redis数据库对象
    global redis_store
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,
                              port=config[config_name].REDIS_PORT,
                              db=0,
                              decode_responses=True)
    # 开启CSRF保护
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        """
        CSRFProtect只验证request中的csrf_token和cookie中的csrf_token是否一致,
        cookie中的csrf_token和表单/request中的csrf_token需要我们自己实现
        """
        # 生成一个csrf_token
        csrf_token = generate_csrf()
        # 将csrf_token存入cookie
        response.set_cookie('csrf_token', csrf_token)
        return response

    # 设置session保存指定的位置
    Session(app)

    # 配置项目日志
    setup_log(config_name)

    from info.utils.common import user_login_data

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

    # 将蓝图注册到app中
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

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

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

    from info.modules.center import center_blue
    app.register_blueprint(center_blue)

    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    # 注册自定义过滤器
    from info.utils.common import index_to_class
    app.add_template_filter(index_to_class, 'index_to_class')

    return app
Пример #8
0
# __init__.py

import logging
import os

from .settings import DevConfig

from flask import Flask, g
from flask_wtf import CSRFProtect

from app.extensions import db, migrate, ckeditor, Session
from app.models import GeneratorConfig, Article, Category
from app.routes.main import main
from app.site_builder.builder import set_builder_conf

crsf = CSRFProtect()


def create_app(fs: str = 'settings.py'):
    app = Flask(__name__)
    cnf = os.getenv('FLASK_ENV')
    if cnf.lower().startswith('dev'):
        app.config.from_object(DevConfig)
    else:
        app.config.from_object(DevConfig)

    crsf.init_app(app)

    # Server-side session config
    app.config["SESSION_TYPE"] = 'sqlalchemy'
    app.config["SESSION_PERMANENT"] = True
Пример #9
0
def create_app(config_name):
    # 1.创建app对象
    app = Flask(__name__)

    # 2.将配置信息添加到app上
    config_class = config_dict[config_name]  # DevelopmentConfig

    # 记录日志
    write_log(config_class)

    # DevelopmentConfig   --->赋予app属性为开发模式app
    #ProductionConfig---> 赋予app属性为:线上模式app
    app.config.from_object(config_class)

    # 3.数据对象(mysql和redis)
    # mysql 数据库对象
    # 延迟加载,懒加载,当app有值时才真正进行数据库初始化工作
    db.init_app(app)

    # redis 数据库对象
    global redis_store
    redis_store = StrictRedis(host=config_class.REDIS_HOST,
                              port=config_class.REDIS_PORT,
                              decode_responses=True)

    # 4.给项目添加csrf保护机制
    # 1.提取cookie中的csrf_tocken
    # 2.如果数据是通过表单发送:提取表单中csrf_token,如果数据是通过ajax请求发送的;提取请求头中的字段X-CSRFToken
    # 3.对比两个值是否一致
    CSRFProtect(app)

    # 利用钩子函数在每次请求之后设置csrf_token 值到cookie中
    @app.after_request
    def set_csrf_token(response):
        """补充csrf_token的逻辑"""

        # 1.生成csrf_token随机值
        csrf_token = generate_csrf()
        # 2.获取相应对象,统一设置csrf_token值到cookie中
        response.set_cookie("csrf_token", csrf_token)
        # 3.返回响应对象
        return response

    # 通过app对象将函数添加到系统过滤器中
    app.add_template_filter(do_ranklist_class, "ranklist_class")

    # 捕获404异常,返回404统一页面
    # 注意: 需要接受err信息
    @app.errorhandler(404)
    @get_user_info
    def handler_404notfound(err):

        # 1.查询用户信息
        user = g.user
        data = {"user_info": user.to_dict() if user else None}

        # 2.返回404页面
        return render_template("news/404.html", data=data)
        # return "123"

    # 5.创建Flask_session工具类对象:将flask.session的存储从 服务器内存 调整到redis 数据库
    Session(app)

    # 注意:真正使用蓝图对象时才导入,能够解决循环导入问题
    # 在app 上注册蓝图
    # 注册首页蓝图对象
    from info.modules.index import index_bp
    app.register_blueprint(index_bp)

    # 注册新闻的蓝图对象
    # from info.modules.news import news_bp
    # app.register_blueprint(news_bp)

    # 添加注册模块蓝图
    # from info.modules.passport import passport_bp
    # app.register_blueprint(passport_bp)

    return app
Пример #10
0
                            SECRET_KEY=pwgen(64),
                            BABEL_TRANSLATION_DIRECTORIES="../translations")
    print("\nWARNING: c3bottles is not configured properly and this\n"
          "instance fell back to the default configuration. This means\n"
          "that the secret key will change on every restart of the\n"
          "server and all users will be logged out forcibly!\n")

Compress(c3bottles)

db = SQLAlchemy(c3bottles, session_options={"autoflush": False})

lm = LoginManager(c3bottles)

bcrypt = Bcrypt(c3bottles)

csrf = CSRFProtect(c3bottles)

babel = Babel(c3bottles)

languages = ("en", "de")
locales = {l: Locale(l) for l in languages}
language_list = sorted([l for l in languages],
                       key=lambda k: locales[k].get_display_name())


def get_locale():
    """
    Get the locale from the session. If no locale is available, set it.
    """
    if "lang" not in session or session["lang"] not in language_list:
        set_locale()
Пример #11
0
from flask import Flask, request, jsonify, Response, redirect, render_template, flash, url_for, session
from flask_pymongo import PyMongo
from werkzeug.security import generate_password_hash, check_password_hash  # biblioteca para criptografar senhas
from bson import json_util
from bson.objectid import ObjectId
from forms import *
from flask_wtf import CSRFProtect
from functools import wraps

app = Flask(__name__)
app.config['MONGO_URI'] = 'mongodb://localhost/bdpmi'  # Base de dados
mongo = PyMongo(app)
app.secret_key = 'chavesecreta'
csrf = CSRFProtect(app)  # Função do Flask para proteger Form


# Controle de sessão do usuario
def login_required(run):
    @wraps(run)
    def wrap(*args, **kwargs):
        if 'usuario' in session:
            return run(*args, **kwargs)
        else:
            flash('Por favor! Efetue o login primeiro!')
            return redirect(url_for('login'))

    return wrap


##################################################################################
# ROTA HOME /
Пример #12
0
def create_app(config_name):
    app = Flask(__name__)
    #设置日志
    setup_log(config_name)

    app.config.from_object(config[config_name])
    #初始化db
    db.init_app(app)

    global redis_store
    #初始化redis,存储表单
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,port =config[config_name].REDIS_PORT,decode_responses=True)

    #开启当前项目CSRF保护,制作服务器验证功能,cookie中的csrf_token和表单csrf_token需要我们自己实现..
    #
    CSRFProtect(app)

    #设置session保存位置
    Session(app)

    from info.utils.common import do_index_class
    from info.utils.common import  user_login_data
    #添加过滤器
    app.add_template_filter(do_index_class,"indexclass")



    @app.after_request
    def after_request(response):
        #生成随机的csrftoken
        csrf_token=generate_csrf()
        #设置一个csrf
        response.set_cookie("csrf_token",csrf_token)
        return response
    @app.errorhandler(404)
    @user_login_data
    def page_not_fount(*args,**kwargs):
        user =g.user

        data = {'user':user.to_dict() if user else None}
        return render_template('news/404.html',data=data)

    #注册蓝图
    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)





    return app
Пример #13
0
def create_app(config_name):
    """返回app"""

    # 1.设置日志
    setup_log(config_name)
    # 2.创建app
    app = Flask(__name__)
    # 3.加载配置
    config_object = config[config_name]
    app.config.from_object(config_object)

    # 4.加载各种扩展
    # 4.1初始化数据库
    db.init_app(app)

    # 4.2开启CSRF项目保护,只做服务器的验证
    from flask_wtf import CSRFProtect
    CSRFProtect(app)

    @app.after_request
    def after_request(response):
        from flask_wtf.csrf import generate_csrf
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    # 4.3 统一对网站的404错误做处理
    from info.utils.common import user_login_data

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

    # 4.4设置session保存到指定位置
    from flask_session import Session
    Session(app)

    # 5初始化全局变量
    # 5.1初始化redis存储对象
    global redis_store
    from redis import StrictRedis
    redis_store = StrictRedis(host=config_object.REDIS_HOST,
                              port=config_object.REDIS_PORT,
                              decode_responses=True)

    # 注册过滤器
    # 主页排行过滤器
    from info.utils.common import do_index_class, do_index_active
    app.add_template_filter(do_index_class, 'index_class')
    app.add_template_filter(do_index_active, 'index_active')

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

    # 6.2 登录与注册蓝图
    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    # 6.3 新闻蓝图
    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    # 6.3 用户信息管理蓝图
    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    # 6.4 管理员信息管理蓝图
    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    # 7.返回app对象
    return app
Пример #14
0
def create_app():

    app = Flask(
        __name__
    )  # this is the name of the module/package that is calling this app
    app.debug = True
    app.secret_key = 'pineapples'
    #set the app configuration data
    #the folder to store images
    UPLOAD_FOLDER = '/static/img'
    app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

    #Disable security due to CSRF token bug
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['WTF_CSRF_SECRET_KEY'] = 'pineapples'
    csrf = CSRFProtect()
    csrf.init_app(app)

    #app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///marketplace.sqlite'
    app.config.from_mapping(
        #     #Flask SQLAlchemy settings
        SQLALCHEMY_DATABASE_URI=os.environ['DATABASE_URL'], )
    #initialize db with flask app
    db.init_app(app)

    ctx = app.app_context()
    ctx.push()
    db.create_all()

    bootstrap = Bootstrap(app)

    #initialize the login manager
    login_manager = LoginManager()

    #set the name of the login function that lets user login
    # in our case it is auth.login (blueprintname.viewfunction name)
    login_manager.login_view = 'auth.authenticate'
    login_manager.init_app(app)

    #create a user loader function takes userid and returns User
    #from .models import User  # importing here to avoid circular references
    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(int(user_id))

    @login_manager.unauthorized_handler
    def unauthorized():
        return redirect(url_for('auth.authenticate'))

    login_manager.session_protection = 'basic'

    #importing views module here to avoid circular references
    # a commonly used practice.
    from . import views
    app.register_blueprint(views.bp)

    from . import products
    app.register_blueprint(products.bp)

    from . import auth
    app.register_blueprint(auth.bp)

    #Define global variables for access inside jinja templates
    app.jinja_env.globals.update(ProductType=ProductType)
    app.jinja_env.globals.update(SubTypes=SubTypes)

    #Error handling returns set pages
    @app.errorhandler(404)
    def not_found_error(error):
        return render_template('404.html'), 404

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

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

    return app
Пример #15
0
import os

from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_wtf import CSRFProtect
from sqlalchemy_searchable import SearchQueryMixin
from flask_mail import Mail
from flask_session import Session
from flask_migrate import Migrate

db = SQLAlchemy()
bcrypt = Bcrypt()
csrf_protect = CSRFProtect()
login = LoginManager()
login.login_view = 'login.index'
login.login_message = ('Please log in to access this page.')
mail = Mail()
migrate = Migrate()
Пример #16
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)

    # 开启当前项目csrf保护

    # 帮我们做了:从cookie中取出随机值,从表单中取出随机值,然后进行校验,并且响应校验结果
    # 我们需要做:1.在界面加载的时候。往cookie中添加一个csrf_token ,并且在表单中添加一个隐藏的csrf_token

    # 而我们现在在登录或者注册不是使用表单,而是使用ajax请求,所以我们需要在 ajax请求的时候带上csrf_token这个随机值
    CSRFProtect(app)
    Session(app)

    # 添加自定义过滤器
    from info.utils.common import to_index_class
    app.add_template_filter(to_index_class, "index_class")

    from info.utils.common import user_login_data

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

    @app.after_request
    def after_response(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
Пример #17
0
def create_app(config_name):

    app = Flask(__name__)

    # 根据传入的配置名称,获取对应的配置类
    config = config_dict.get(config_name)

    # 记录日志信息的方法
    log_file(config.LEVEL)

    # 加载配置类信息
    app.config.from_object(config)

    # 创建SQLALCHEMY对象,管理app
    # db = SQLAlchemy(app)
    db.init_app(app)

    # 创建redis对象
    global redis_store
    redis_store = redis.StrictRedis(host=config.REDIS_HOST,
                                    port=config.REDIS_PORT,
                                    decode_responses=True)

    # 初始化Session,读取app身上session的配置信息
    Session(app)

    # 保护app,使用CSRFProtect
    CSRFProtect(app)

    #注册首页蓝图index_blue,到app中
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    # 注册认证蓝图passport_blue到app中
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    # 注册新闻蓝图new_blue到app中
    from info.modules.news import news_blue
    app.register_blueprint(news_blue)

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

    # 注册管理员蓝图admin_blue到app中
    from info.modules.admin import admin_blue
    app.register_blueprint(admin_blue)

    # 将过滤器添加到过滤器模板列表中
    app.add_template_filter(index_class, "index_class")

    # 捕捉404页面的异常
    @app.errorhandler(404)
    @user_login_data
    def item_notfound(e):
        data = {"user_info": g.user.to_dict() if g.user else ""}
        return render_template("news/404.html", data=data)

    # 使用请求钩子after_request,对所有的响应进行拦截,做统一的csrf_token的设置
    @app.after_request
    def after_request(resp):
        value = generate_csrf()
        resp.set_cookie("csrf_token", value)
        return resp

    print(app.url_map)
    return app
Пример #18
0
def create_app(config=None):
    """Create the Flask app instance that is used throughout the application.

    Args:
        config: Path to configuration file as a string or an object with config
        directives.

    Returns:
        Application object (instance of flask.Flask).
    """
    template_folder = 'frontend/dist'
    static_folder = 'frontend/dist'

    app = Flask(__name__,
                template_folder=template_folder,
                static_folder=static_folder)

    if not config:
        # Where to find the config file
        default_path = '/etc/timesketch/timesketch.conf'
        # Fall back to legacy location of the config file
        legacy_path = '/etc/timesketch.conf'
        if os.path.isfile(default_path):
            config = default_path
        else:
            config = legacy_path

    if isinstance(config, six.text_type):
        os.environ['TIMESKETCH_SETTINGS'] = config
        try:
            app.config.from_envvar('TIMESKETCH_SETTINGS')
        except IOError:
            sys.stderr.write(
                'Config file {0} does not exist.\n'.format(config))
            sys.exit()
    else:
        app.config.from_object(config)

    # Make sure that SECRET_KEY is configured.
    if not app.config['SECRET_KEY']:
        sys.stderr.write('ERROR: Secret key not present. '
                         'Please update your configuration.\n'
                         'To generate a key you can use openssl:\n\n'
                         '$ openssl rand -base64 32\n\n')
        sys.exit()

    # Plaso version that we support
    if app.config['UPLOAD_ENABLED']:
        try:
            # pylint: disable=import-outside-toplevel
            from plaso import __version__ as plaso_version
            app.config['PLASO_VERSION'] = plaso_version
        except ImportError:
            sys.stderr.write('Upload is enabled, but Plaso is not installed.')

    # Setup the database.
    configure_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    db = init_db()

    # Alembic migration support:
    # http://alembic.zzzcomputing.com/en/latest/
    migrate = Migrate()
    migrate.init_app(app, db)

    # Register blueprints. Blueprints are a way to organize your Flask
    # Flask application. See this for more information:
    # http://flask.pocoo.org/docs/latest/blueprints/
    app.register_blueprint(spa_views)
    app.register_blueprint(auth_views)

    # Setup URL routes for the API.
    api_v1 = Api(app, prefix='/api/v1')
    for route in V1_API_ROUTES:
        api_v1.add_resource(*route)

    # Register error handlers
    # pylint: disable=unused-variable
    @app.errorhandler(ApiHTTPError)
    def handle_api_http_error(error):
        """Error handler for API HTTP errors.

        Returns:
            HTTP response object (instance of flask.wrappers.Response)
        """
        return error.build_response()

    # Setup the login manager.
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'user_views.login'

    # This is used by the flask_login extension.
    # pylint: disable=unused-variable
    @login_manager.user_loader
    def load_user(user_id):
        """Based on a user_id (database primary key for a user) this function
        loads a user from the database. It is used by the Flask-Login extension
        to setup up the session for the user.

        Args:
            user_id: Integer primary key for the user.

        Returns:
            A user object (Instance of timesketch.models.user.User).
        """
        return User.query.get(user_id)

    # Setup CSRF protection for the whole application
    CSRFProtect(app)

    return app
Пример #19
0
#这个文件存放着app的创建与管理,蓝图的创建
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
import pymysql
pymysql.install_as_MySQLdb()
csrfya = CSRFProtect()
models = SQLAlchemy()
def Create_app():
    app = Flask(__name__)
    app.config.from_object('DB_settings.DebugConfig')
    csrfya.init_app(app)
    models.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app


Пример #20
0
def create_app(config=None):
    """Create the Flask app instance that is used throughout the application.

    Args:
        config: Path to configuration file as a string or an object with config
        directives.

    Returns:
        Application object (instance of flask.Flask).
    """
    # Setup the Flask app and load the config.
    app = Flask(__name__,
                template_folder=u'templates',
                static_folder=u'static')

    if not config:
        config = u'/etc/timesketch.conf'

    if isinstance(config, unicode):
        os.environ[u'TIMESKETCH_SETTINGS'] = config
        try:
            app.config.from_envvar(u'TIMESKETCH_SETTINGS')
        except IOError:
            sys.stderr.write(
                u'Config file {0} does not exist.\n'.format(config))
            sys.exit()
    else:
        app.config.from_object(config)

    # Make sure that SECRET_KEY is configured.
    if not app.config[u'SECRET_KEY']:
        sys.stderr.write(u'ERROR: Secret key not present. '
                         u'Please update your configuration.\n'
                         u'To generate a key you can use openssl:\n\n'
                         u'$ openssl rand -base64 32\n\n')
        sys.exit()

    # Plaso version that we support
    if app.config[u'UPLOAD_ENABLED']:
        try:
            from plaso import __version__ as plaso_version
        except ImportError:
            sys.stderr.write(u'Upload is enabled, but Plaso is not installed.')
            sys.exit()
        app.config[u'PLASO_VERSION'] = plaso_version

    # Setup the database.
    configure_engine(app.config[u'SQLALCHEMY_DATABASE_URI'])
    db = init_db()

    # Alembic migration support:
    # http://alembic.zzzcomputing.com/en/latest/
    migrate = Migrate()
    migrate.init_app(app, db)

    # Register blueprints. Blueprints are a way to organize your Flask
    # Flask application. See this for more information:
    # http://flask.pocoo.org/docs/latest/blueprints/
    app.register_blueprint(user_views)
    app.register_blueprint(home_views)
    app.register_blueprint(sketch_views)
    app.register_blueprint(story_views)

    # Setup URL routes for the API.
    api_v1 = Api(app, prefix=u'/api/v1')
    api_v1.add_resource(SketchListResource, u'/sketches/')
    api_v1.add_resource(SketchResource, u'/sketches/<int:sketch_id>/')
    api_v1.add_resource(AggregationResource,
                        u'/sketches/<int:sketch_id>/aggregation/')
    api_v1.add_resource(ExploreResource, u'/sketches/<int:sketch_id>/explore/')
    api_v1.add_resource(EventResource, u'/sketches/<int:sketch_id>/event/')
    api_v1.add_resource(EventAnnotationResource,
                        u'/sketches/<int:sketch_id>/event/annotate/')
    api_v1.add_resource(ViewListResource, u'/sketches/<int:sketch_id>/views/')
    api_v1.add_resource(ViewResource,
                        u'/sketches/<int:sketch_id>/views/<int:view_id>/')
    api_v1.add_resource(SearchTemplateListResource, u'/searchtemplate/')
    api_v1.add_resource(SearchTemplateResource,
                        u'/searchtemplate/<int:searchtemplate_id>/')
    api_v1.add_resource(UploadFileResource, u'/upload/')
    api_v1.add_resource(TaskResource, u'/tasks/')
    api_v1.add_resource(StoryListResource,
                        u'/sketches/<int:sketch_id>/stories/')
    api_v1.add_resource(StoryResource,
                        u'/sketches/<int:sketch_id>/stories/<int:story_id>/')
    api_v1.add_resource(QueryResource,
                        u'/sketches/<int:sketch_id>/explore/query/')
    api_v1.add_resource(CountEventsResource,
                        u'/sketches/<int:sketch_id>/count/')
    api_v1.add_resource(TimelineListResource,
                        u'/sketches/<int:sketch_id>/timelines/')
    api_v1.add_resource(
        TimelineResource,
        u'/sketches/<int:sketch_id>/timelines/<int:timeline_id>/')
    api_v1.add_resource(SearchIndexListResource, u'/searchindices/')
    api_v1.add_resource(SearchIndexResource,
                        u'/searchindices/<int:searchindex_id>/')
    api_v1.add_resource(GraphResource,
                        u'/sketches/<int:sketch_id>/explore/graph/')

    # Experimental API resources
    api_experimental = Api(app, prefix=u'/api/experimental')
    api_experimental.add_resource(WinLoginsResource,
                                  u'/sketches/<int:sketch_id>/win_logins/')
    api_experimental.add_resource(WinServicesResource,
                                  u'/sketches/<int:sketch_id>/win_services/')
    api_experimental.add_resource(CreateGraphResource,
                                  u'/sketches/<int:sketch_id>/create_graph/')
    api_experimental.add_resource(DeleteGraphResource,
                                  u'/sketches/<int:sketch_id>/delete_graph/')

    # Register error handlers
    # pylint: disable=unused-variable
    @app.errorhandler(ApiHTTPError)
    def handle_api_http_error(error):
        """Error handler for API HTTP errors.

        Returns:
            HTTP response object (instance of flask.wrappers.Response)
        """
        return error.build_response()

    # Setup the login manager.
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = u'user_views.login'

    # This is used by the flask_login extension.
    # pylint: disable=unused-variable
    @login_manager.user_loader
    def load_user(user_id):
        """Based on a user_id (database primary key for a user) this function
        loads a user from the database. It is used by the Flask-Login extension
        to setup up the session for the user.

        Args:
            user_id: Integer primary key for the user.

        Returns:
            A user object (Instance of timesketch.models.user.User).
        """
        return User.query.get(user_id)

    # Setup CSRF protection for the whole application
    CSRFProtect(app)

    return app
def csrfProtectCanBeImportedFromFlaskWtfDirectly():
  from flask import Flask
  from flask_wtf import CSRFProtect
  app = Flask(__name__) # Compliant
  CSRFProtect(app)
Пример #22
0
from flask_wtf import CSRFProtect

from config import config

configName = os.getenv('FLASK_CONFIG') or 'default'

# # 實例化一個全局logger對象
xlogger = logging.getLogger(config[configName].LOG_NAME)

# Flask_SQLALChemy组件初始化
db = SQLAlchemy()

# 實例化一個flask-session對象
session = Session()

# # 實例化一些插件的全局对象
loginmanager = LoginManager()
bootstrap = Bootstrap()
mail = Mail()
moment = Moment()

# # 實例化一个CSRF保护的全局对象
csrf = CSRFProtect()  # 安全KEY使用flask默认的SECRET_KEY

# Flask_uploads组件初始化,创建一个flask_uploads集合,供manage.py中的处理函数引用.
# 之所以放到这里初始化,是因为这些上传的文件被我视为数据库的一部分,当然也可以在别的地址初始化它
# 通过UploadSet函数创建一个Set,允许上传哪些类型的文件
#uploadSetPhotos = UploadSet('photos', IMAGES)

pass
Пример #23
0
import os
from flask import Flask, render_template, redirect, request, session
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, PasswordField, SubmitField

application = Flask(__name__, instance_relative_config=True)
application.config.from_pyfile("config.py")
csrf = CSRFProtect(application)

application.config["DEBUG"] = True


@application.before_request
def is_logged_in():
    if not session.get("logged_in") and request.endpoint not in ("login",
                                                                 "static"):
        session["url"] = request.url
        return redirect("/login")


class UserForm(FlaskForm):
    username = StringField(label="Username")
    password = PasswordField(label="Password")
    submit = SubmitField(label="Log in")


@application.route("/login", methods=["GET", "POST"])
def login():
    form = UserForm()
    status = 200
    if form.validate_on_submit():
Пример #24
0
                        message="Doit être compris entre 1000 et 98000")
        ])
    submit = SubmitField('Prédire')


# inference fonction, parameters have passed form filters before reaching this function
# still user can input inexistant code postal (verification could be implimented from flat file or db)
def make_inference(type_bien: str, surface: int, nb_pieces: int,
                   code_postal: int):
    with open(f"ml_models/tree_{type_bien}.pkl", "rb") as file:
        tree = pickle.load(file)
    prediction = tree.predict([[surface, nb_pieces, code_postal]])
    return prediction[0]


csrf = CSRFProtect()
app = Flask(__name__)
try:
    app.config.from_pyfile('config_dev.py')
except:
    app.config['SECRET_KEY'] = os.environ["FLASK_KEY"]
csrf.init_app(app)


@app.route('/', methods=['GET'])
@app.route('/home', methods=['GET'])
def home():
    return render_template('home.html')


@app.route('/about', methods=['GET'])
Пример #25
0
import appengine_config
import logging

from flask import Flask
from flask_restful import Api
from flask_wtf import CSRFProtect
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(__name__)
csrf_protect = CSRFProtect(app)
api = Api(app, decorators=[csrf_protect.exempt])
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

if appengine_config.GAE_DEV:
    logging.warning('Using a dummy secret key')
    app.secret_key = 'MyS3cr3tKey'
    app.debug = True
    DEBUG = True

else:
    import app_secrets

    app.secret_key = app_secrets.app_secret_key
Пример #26
0
import random
import json
import re
import sys
import qiniu
from io import BytesIO
import base64

app = Flask(__name__)
app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)

# 加载配置文件
app.config.from_object(config)

CSRFProtect(app=app)
db.init_app(app)
mail.init_app(app)
# app.config["WTF_CSRF_ENABLED"] = False

UEDITOR_UPLOAD_PATH = "images"  # 上传到本地服务器的路径
UEDITOR_UPLOAD_TO_QINIU = False  # 是否上传到七牛云
UEDITOR_QINIU_ACCESS_KEY = ""
UEDITOR_QINIU_SECRET_KEY = ""
UEDITOR_QINIU_BUCKET_NAME = ""
UEDITOR_QINIU_DOMAIN = "peouv6xac.bkt.clouddn.com"


@app.before_first_request
def before_first_request():
    global UEDITOR_UPLOAD_TO_QINIU
Пример #27
0
from flask import Flask, request, current_app
from flask_babel import Babel
from flask_redis import FlaskRedis
from flask_wtf import CSRFProtect
from pony.flask import Pony

from config import Config
from db import db as mysql

# flask
flask_app = Flask(__name__)
flask_app.config.from_object(Config)
flask_app.jinja_env.add_extension('jinja2.ext.i18n')

CSRFProtect(flask_app)

# mysql
mysql.bind(**flask_app.config['PONY'])
mysql.generate_mapping()
pony = Pony(flask_app)

# redis
redis = FlaskRedis(flask_app)

babel = Babel(flask_app)


@babel.localeselector
def get_locale():
    locale = request.cookies.get('locale', '')
    if locale:
Пример #28
0
from flask import Flask, render_template, request, flash
from flask_wtf import CSRFProtect
import os
import checkfuelprice as fp
import settings as settings
import search_view as sv

# print("Current path: ", os.getcwd())
app = Flask(__name__)
app.config.from_object(settings.Config)
csrf = CSRFProtect(app)


@app.route('/', methods=('GET', 'POST'))
def search():
    form = sv.SearchForm(request.form)

    if form.validate_on_submit():
        if form.suburbs.data == '-1':
            flash('Please select suburb.', 'error')
            return render_template('search.html', form=form)

        if form.brand.data == '0':
            brand = 'All brands'
        else:
            brand = dict(form.brand.choices).get(int(form.brand.data))

        if form.surrounding.data == 'yes':
            surrounding = 'Yes'
        else:
            surrounding = 'No'
Пример #29
0
from flask_wtf import CSRFProtect

# 初始化app
app = Flask(__name__)

#注册蓝图
app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)
app.register_blueprint(common_bp)

#导入配置文件
app.config.from_object(config)
db.init_app(app)

#注册csrf模块
csrf = CSRFProtect()
csrf.exempt(front_bp)
csrf.exempt(cms_bp)
csrf.exempt(common_bp)
csrf.init_app(app)


# 处理404错误
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


#处理500错误
@app.errorhandler(500)
def page_not_found(e):
Пример #30
0
# Make environment specific choice of configuration
if os.environ["PPT_ENVIRONMENT"] == "prod":
    app.config.from_pyfile('../config/settings_prod.py')
elif os.environ["PPT_ENVIRONMENT"] == "test":
    app.config.from_pyfile('../config/settings_test.py')
else:
    app.config.from_pyfile('../config/settings_dev.py')
    
app.secret_key = app.config["SECRET_KEY"]

# Load/initialize extensions

# CSRFProtect is for csrf protecting POST requests that do not contain a form.
# By initializing it, all POST requests must send an X-CSRFToken header
# to be allowed to connect. 
csrf = CSRFProtect()
csrf.init_app(app)

cors = CORS(app)
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
principals = Principal(app)
wtforms_json.init()

# authentication/login form methods. We use flask_jwt for authentication, and
# send out a JSON web token that is stored in the client and sent back with
# every request. The authentication back end is LDAP. We send out LDAP groups
# the user is in for use in role-based authorization on the front end (what to
# show the user). We do check the directory again when handling each request.
Пример #31
0
def create_app(config_str):
    app = Flask(__name__)
    # 从字典中获取类
    app.config.from_object(config_dict[config_str])
    # 日志初始化
    setup_log(config_str)
    # mysql初始化
    db.init_app(app)
    # 初始化redis数据库
    global redis_store
    # redis_store = StrictRedis(
    #     host="REDIS_HOST",
    #     port="REDIS_PORT",
    #     db="REDIS_DB",
    #     )
    redis_store = StrictRedis(
        host=app.config.get('REDIS_HOST'),
        port=app.config.get('REDIS_PORT'),
        db=app.config.get('REDIS_DB')
    )
    # 导入蓝图
    # 蓝图注入app 中
    from info.modules.index import index_blueprint
    app.register_blueprint(index_blueprint)

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

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

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

    from info.modules.admin import admin_blueprint
    app.register_blueprint(admin_blueprint)
    # csrf保护
    CSRFProtect(app)
    # session 保存在redis中
    Session(app)

    @app.after_request
    def after(response):
        # 完善CSRF验证
        from flask_wtf.csrf import generate_csrf
        # 生成csrf口令
        token = generate_csrf()
        # 输出到浏览器cookie中
        response.set_cookie('csrf_token', token)
        return response
    from info.utils.common import longin_wrappes
    @app.errorhandler(404)
    @longin_wrappes
    def header_404(e):
        data = {
            "user": g.user
        }

        return render_template("news/404.html",data = data)

    return app