Ejemplo n.º 1
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    configure_uploads(app, photos)
    patch_request_class(app) # 限制文件上传大小

    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)
    # oauth.init_app(app)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        sslify = SSLify(app)


    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 .api_1_0 import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')

    return app
Ejemplo n.º 2
0
def create_app(config_name):
    app= Flask(__name__)
    app.config.from_object(config_by_name[config_name] )
    
    UPLOAD_FOLDER = r'D:\aqua\apps\static\downloads'
    ALLOWED_EXTENSIONS= set(['txt','json','csv','xlsx'])
    app.config['UPLOADS_DEFAULT_DEST'] = UPLOAD_FOLDER
    app.config['UPLOAD_FOLDER'] ='downloads'
    docs = UploadSet('docs',DOCUMENTS)
    configure_uploads(app,docs)
    patch_request_class(app)
    celery.conf.update(CeleryConfig)
    mail.init_app(app)
    '''
    db.init_app(app)
    
    
    toolbar.init_app(app)
    pagedown.init_app(app)
    '''
    login_manager.init_app(app)
    moment.init_app(app)
    bootstrap.init_app(app)
    from .main import  main as main_blueprint
    app.register_blueprint(main_blueprint)
    return app
Ejemplo n.º 3
0
def configure_uploads(app):
    """
    文件上传支持.
    我们将图片直接保存在static目录之下, 因此在生产环境中可以直接由nginx提供服务.
    注意我们没有调用flask_uploads的configure_uploads(), 这个方法负责为每个uploadset生成UploadConfiguration, 并且注册一个blueprint用来生成上传后的url.
    所以我们直接初始化UploadConfiguration, 注意在上传完文件后要使用url_for('static', filename=[])来生成url.
    """
    # 设置上传目标路径, 无需通过配置文件设置一个绝对路径
    uploads._config = UploadConfiguration(os.path.join(app.root_path, 'static', 'uploads'))
    # 限制上传文件大小
    patch_request_class(app, 10 * 1024 * 1024)
Ejemplo n.º 4
0
def configure_app(app, config):
    if not config:
        config = assets.AppModes.DEVELOPMENT
    config = config_factory.get(config)
    app.config.from_object(config)
    # override config with env file cfg
    prod_config = os.environ.get('OPINEW_CONFIG_FILE')
    if prod_config and os.path.exists(prod_config):
        app.config.from_envvar('OPINEW_CONFIG_FILE')  # pragma: no cover
    # limit the file size that can be uploaded
    patch_request_class(app, assets.Constants.MAX_FILE_SIZE)
    # infinite jinja template cache
    app.jinja_env.cache = {}
Ejemplo n.º 5
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    db.init_app(app)
    from .main import main
    from .auth import auth
    from .manager import manager
    app.register_blueprint(main)
    app.register_blueprint(auth)
    app.register_blueprint(manager)
    configure_uploads(app, photos)
    patch_request_class(app)
    from .models import Message, User, Post, Praise, Comment, Collection
    app.add_template_global(Message, 'Message')
    app.add_template_global(User, 'User')
    app.add_template_global(Post, 'Post')
    app.add_template_global(Comment, 'Comment')
    return app
Ejemplo n.º 6
0
from utils.my_bcrypt import bcrypt
from user.routes import bp as user_bp
from vessel.routes import bp as vessel_bp
from container_image.routes import bp as container_image_bp
from container_info.routes import bp as container_info_bp
from container_check.routes import bp as container_check_bp
from container_approval.routes import bp as container_approval_bp
from container_report.routes import bp as container_report_bp
from utils.image_helper import IMAGE_SET

app = Flask(__name__)
app.config.from_object('config.Config')
# app.config["MONGO_URI"] = Config.MONGO_URI
# app.config["UPLOADED_IMAGES_DEST"] = Config.UPLOADED_IMAGES_DEST
# app.config["JWT_SECRET_KEY "] = Config.JWT_SECRET_KEY
patch_request_class(app, 6 * 1024 * 1024)  # 6MB max upload.
configure_uploads(app, IMAGE_SET)

mongo.init_app(app)
bcrypt.init_app(app)
jwt = JWTManager(app)

# ENCODER jsonify untuk menghandle objectID dan Datetime dari mongodb
app.json_encoder = JSONEncoder


@jwt.user_claims_loader
def add_claims_to_jwt(identity):
    user = mongo.db.users.find_one({"username": identity})
    return {"name": user["name"],
            "isAdmin": user["isAdmin"],
Ejemplo n.º 7
0
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, Length, Email, EqualTo

import mysql.connector
from config import db_config

import tempfile
import os
import boto3

from app import webapp
#from wand.image import Image

photos = UploadSet('photos', IMAGES)
configure_uploads(webapp, photos)
patch_request_class(webapp)

'''

Class Definitions

'''

class RegisterForm(FlaskForm):
    username = StringField(u'Username', validators=[
                DataRequired(message= u'Username can not be empty.'), Length(4, 16)])
    password = PasswordField('New Password', validators=[
        DataRequired(message= u'Password can not be empty.'),
        EqualTo('confirm', message='Passwords must match')
    ])
    confirm = PasswordField('Repeat Password')
Ejemplo n.º 8
0
def configure_forms(app):
    configure_uploads(app, photos)
    configure_uploads(app, avatars)

    # set maximum file size, default is 3MB
    patch_request_class(app, app.config["MAX_FILE_SIZE"])
Ejemplo n.º 9
0
# -*- coding: utf-8 -*-
import os
from flask import Flask, request
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class

app = Flask(__name__)
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # set maximum file size, default is 16MB

html = '''
    <!DOCTYPE html>
    <title>Upload File</title>
    <h1>Photo Upload</h1>
    <form method=post enctype=multipart/form-data>
         <input type=file name=photo>
         <input type=submit value=Upload>
    </form>
    '''


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        file_url = photos.url(filename)
        return html + '<br><img src=' + file_url + '>'
    return html
Ejemplo n.º 10
0
from flask import render_template, flash, redirect,url_for, session, jsonify
from flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class
from flask import request
from config import Config
from form import LoginForm, DataForm, UploadForm
from Leach import result
import cv2
from amiya import perd


app = Flask(__name__)
app.config.from_object(Config)
basedir = os.path.abspath(os.path.dirname(__file__))
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)

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


@app.route('/user/<name>')
def user(name):
    return '<h1>hello!,{}!</h1>'.format(name)


@app.route('/')
@app.route('/login', methods=['GET', 'POST'])
def login():
Ejemplo n.º 11
0
from resources.users import users_api
from resources.auth import auth_api
from resources.comments import comments_api
from resources.images import images_api

API_PREFIX = '/api/v1'
daily_rate = os.environ.get('GLOBAL_DAILY_RATE')
hourly_rate = os.environ.get('GLOBAL_HOURLY_RATE')

app = Flask(__name__)
load_dotenv('.env', verbose=True)
app.config.from_object('default_config')
# any default config settings that need to be over-written can be changed the
# file referred to by APPLICATION_SETTINS in .env
app.config.from_envvar('APPLICATION_SETTINGS')
patch_request_class(app, 10 * 1024 * 1024)  # 10 MB max
configure_uploads(app, IMAGE_SET)

jwt = JWTManager(app)

limiter = Limiter(app,
                  default_limits=[daily_rate, hourly_rate],
                  key_func=get_ipaddr)


@app.before_first_request
def create_tables():
    db.create_all()


@jwt.unauthorized_loader
Ejemplo n.º 12
0
from Algorithm.Classification.src.DTree import *
from Algorithm.Classification.src.KNN import *
from Algorithm.Classification.src.XGB import *
from Algorithm.Classification.src.NB import *


app = Flask(__name__, static_url_path="")
# app = Flask(__name__)
app.config['SECRET_KEY'] = 'adsfhgasfkjhkj'
app.config['UPLOADED_FILES_DEST'] = os.getcwd() + '\\userfiles'

# CSRFProtect(app)
Bootstrap(app)
files = UploadSet('files', DOCUMENTS)
configure_uploads(app, files)
patch_request_class(app) # 文件大小限制默认为16M


@app.before_request
def before_request():
    g.user = None
    s = Session()
    if 'email' in session:
    	g.user = s.query(User).filter(User.email == session['email']).first()
    	print(g.user.name)


@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
	"""
Ejemplo n.º 13
0
from blacklist import BLACKLIST
from resources.user import User, UserRegister, UserLogin, UserLogout, TokenRefresh, UserList
from resources.github_login import GithubLogin, GithubAuthorize
from resources.item import Item, ItemList
from resources.store import Store, StoreList
from resources.confirmation import Confirmation, ConfirmationByUser
from resources.image import ImageUpload, Image, AvatarUpload, Avatar
from resources.order import Order, OrderList
from libs.image_helper import IMAGE_SET
from oauth import oauth

app = Flask(__name__)

app.config.from_object("default_config")
app.config.from_envvar("APPLICATION_SETTINGS")
patch_request_class(app, 10 * 1024 * 1024)  # 10MB Max Upload Size
configure_uploads(app, IMAGE_SET)

api = Api(app)

jwt = JWTManager(app)


@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
    return jsonify(err.messages), 400


@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist_loader(decrypted_token):
    return decrypted_token['jti'] in BLACKLIST
Ejemplo n.º 14
0
"""The initialization for the app folder."""
from config import Config
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import (configure_uploads, patch_request_class, IMAGES,
                           UploadSet)
"""Creates an instance of Flask app and
	initializes all dependencies that I am using
"""
app = Flask(__name__)  # Creates an instance of a flask app
app.config.from_object(Config)  # Generatess config from config.py
bootstrap = Bootstrap(app)  # activates flask bootstrap
db = SQLAlchemy(app)  # initializes database
migrate = Migrate(app, db)  # initializes flask migrate
login = LoginManager(app)  # links login manager to app
login.login_view = 'login'  # setup for Login Manager
photos = UploadSet('photos', IMAGES)  # upload settings
configure_uploads(app, photos)  # more upload settings
patch_request_class(app)  # the rest of the upload settings
""" runs routes.py and generates models.py """
from app import routes, models
Ejemplo n.º 15
0
def register_configuration(app):
    configure_uploads(app, filez)
    patch_request_class(app, size=25000000)
    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.debug = True
    app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
Ejemplo n.º 16
0
#!/usr/bin/env python
import os
from app import create_app, db
from flask_script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
from flask_uploads import UploadSet, DOCUMENTS
from flask_uploads import configure_uploads, patch_request_class
from app.main.forms import files


app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
configure_uploads(app, (files,))
patch_request_class(app, size=100*1024*1024)


def make_shell_context():
    return dict(app=app, db=db)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('runserver', Server(host='0.0.0.0', port=5000))


if __name__ == '__main__':
    manager.run()
Ejemplo n.º 17
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class
from config import UPLOADS_DEFAULT_DEST, MAX_FILE_SIZE

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

app.config['UPLOADS_DEFAULT_DEST'] = UPLOADS_DEFAULT_DEST
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
patch_request_class(app, MAX_FILE_SIZE)

db = SQLAlchemy(app)

migrate = Migrate(app, db)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

if not app.debug:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('tmp/blog.log', 'a', 1 * 1024 * 1024,
                                       10)
    file_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
Ejemplo n.º 18
0
    TokenRefresh,
    UserLogout,
)
from resources.item import Item, ItemList, ItemPriorityFind
from resources.shopping_list import ShoppingList, ListOfShoppingLists
from resources.confirmation import Confirmation, ConfirmationByUser
from resources.image import Image, ImageUpload, Profile, ProfileUpload
from libs.image_handler import IMAGE_SET

# Creates and configures the flask application

app = Flask(__name__)
load_dotenv(".env", verbose=True)
app.config.from_object("default_config")
app.config.from_envvar("APPLICATION_SETTINGS")
patch_request_class(app,
                    10 * 1024 * 1024)  # 10 MB max image upload size for API
configure_uploads(app, IMAGE_SET)

api = Api(app)
jwt = JWTManager(app)


# Creates database before first request to API can be sent
@app.before_first_request
def create_tables():
    db.create_all()


# App-Wide error handling for Validation type errors
@app.errorhandler(ValidationError)
def handle_marshmallow_validation(error):
Ejemplo n.º 19
0
import logging
import os
from flask import Flask
from config import Config
from flask_bootstrap import Bootstrap
from flask_uploads import patch_request_class
from logging.handlers import SMTPHandler, RotatingFileHandler

app = Flask(__name__)
app.config.from_object(Config)
bootstrap = Bootstrap(app)
patch_request_class(app, size=16777216)

from app import routes, errors

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'],
            subject='VXRD Error Traceback',
            credentials=auth,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
Ejemplo n.º 20
0
from flask_moment import Moment
from flask_uploads import configure_uploads, patch_request_class, UploadSet, IMAGES

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
mail = Mail(app)
bootstrap = Bootstrap(app)
pagedown = PageDown(app)
moment = Moment(app)
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app, size=629145)

if not app.debug:
    if app.config['MAIL_SERVER']:
        auth = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        secure = None
        if app.config['MAIL_USE_TLS']:
            secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr='no-reply@' + app.config['MAIL_SERVER'],
            toaddrs=app.config['ADMINS'],
            subject='Writerrific Failure',
            credentials=auth,
Ejemplo n.º 21
0
from flask_login import LoginManager

from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import UploadSet, IMAGES
from flask_uploads import configure_uploads, patch_request_class
import json
from server_utils import full_path

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)

login = LoginManager(app)
login.login_view = 'login'

CLIENT_SECRET_PATH = full_path(__file__, '..', 'client_secret.json')

with open(CLIENT_SECRET_PATH) as f:
    client_secret_json = json.load(f)
    CLIENT_ID = client_secret_json['web']['client_id']

# image upload setup
images = UploadSet('images', IMAGES)
configure_uploads(app, images)
patch_request_class(app, 4 * 1024 * 1024)  # limits image's size

# here app is the package
# not the above app var
from app import models, login_routes, routes, api
Ejemplo n.º 22
0
def create_app(test_config=None):
    # Create Flask app with a default config
    app = Flask(__name__, instance_relative_config=True)

    # Load test config if we are in testing mode
    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    from lidarts.models import User, Role
    from lidarts.auth.forms import ExtendedLoginForm, ExtendedRegisterForm, \
        ExtendedChangePasswordForm, ExtendedResetPasswordForm

    # Initialize Flask extensions
    db.init_app(app)
    cdn.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app,
                      user_datastore,
                      login_form=ExtendedLoginForm,
                      register_form=ExtendedRegisterForm,
                      change_password_form=ExtendedChangePasswordForm,
                      reset_password_form=ExtendedResetPasswordForm)

    origins = app.config[
        'CORS_ALLOWED_ORIGINS'] if 'CORS_ALLOWED_ORIGINS' in app.config else '*'

    if 'ENGINEIO_MAX_DECODE_PACKETS' in app.config:
        Payload.max_decode_packets = app.config['ENGINEIO_MAX_DECODE_PACKETS']

    message_queue = app.config[
        'SOCKETIO_MESSAGE_QUEUE'] if 'SOCKETIO_MESSAGE_QUEUE' in app.config else 'redis://'
    socketio.init_app(
        app,
        message_queue=message_queue,
        async_mode='gevent',
        cors_allowed_origins=origins,
        # logger=True, engineio_logger=True,
    )
    babelobject.init_app(app)
    moment.init_app(app)
    configure_uploads(app, avatars)
    patch_request_class(app, 2 * 1024 * 1024)

    app.json_encoder = JSONEncoder
    # Fixes bug: url_for generates http endpoints instead of https which causes mixed-content-errors
    app.wsgi_app = ReverseProxied(app.wsgi_app)

    # filter for jinja
    app.jinja_env.filters['datetime'] = format_datetime
    app.jinja_env.globals['get_locale'] = get_locale

    if 'REDIS_URL' in app.config:
        # app.redis = Redis.from_url('redis://')
        # app.redis_client = StrictRedis()
        app.redis = StrictRedis(
            host=app.config['REDIS_URL'],
            password=app.config['REDIS_PASSWORD'],
        )
    else:
        app.redis = StrictRedis.from_url('redis://')
    app.task_queue = rq.Queue('lidarts-tasks', connection=app.redis)

    # Flask-Security mails need to be sent in background
    @security.send_mail_task
    def delay_flask_security_mail(msg):
        app.task_queue.enqueue('lidarts.tasks.send_mail', msg)

    if 'DASHBOARD_ENABLED' in app.config and app.config['DASHBOARD_ENABLED']:
        dashboard.config.init_from(
            file=os.path.join(app.instance_path, 'dashboard.cfg'))

        def get_user_id():
            return current_user.id

        dashboard.config.group_by = get_user_id
        dashboard.bind(app)

    # Load all blueprints
    from lidarts.admin import bp as admin_bp
    app.register_blueprint(admin_bp)

    from lidarts.api import bp as api_bp
    app.register_blueprint(api_bp)

    from lidarts.generic import bp as generic_bp
    app.register_blueprint(generic_bp)

    from lidarts.game import bp as game_bp
    app.register_blueprint(game_bp)

    from lidarts.profile import bp as profile_bp
    app.register_blueprint(profile_bp)

    from lidarts.legal import bp as legal_bp
    app.register_blueprint(legal_bp)

    from lidarts.auth import bp as auth_bp
    app.register_blueprint(auth_bp)

    from lidarts.tools import bp as tools_bp
    app.register_blueprint(tools_bp)

    from lidarts.statistics import bp as statistics_bp
    app.register_blueprint(statistics_bp)

    from lidarts.tournament import bp as tournament_bp
    app.register_blueprint(tournament_bp)

    from lidarts.generic.errors import not_found_error, internal_error
    app.register_error_handler(404, not_found_error)
    app.register_error_handler(500, internal_error)

    import lidarts.models
    import lidarts.socket.base_handler
    import lidarts.socket.chat_handler
    import lidarts.socket.X01_game_handler
    import lidarts.socket.game.cricket.cricket_game_handler
    import lidarts.socket.public_challenge_handler
    import lidarts.socket.tournament_handler
    import lidarts.socket.webcam_follow_handler

    return app
Ejemplo n.º 23
0
        "SECRET_KEY": "askdfjasd"
    }
finally:
    # set file destination
    application.config['UPLOADED_DATAFILES_DEST'] = configurations[
        "SAVE_FILE_DESTINATION"]
    # set secret
    application.secret_key = configurations['SECRET_KEY']

# declare files for upload set
# DATA allows for only data extensions (".csv" etc)
datafiles = UploadSet('datafiles', DATA)
configure_uploads(application, datafiles)

# set max upload size to 500MB
patch_request_class(application, 500 * 1024 * 1024)

#### FUNCTIONS ####

# hashing function to be applied to pandas dataframe
# salt is prepended to string


def hashthis(string, salt):
    hash_string = salt + string
    sha = hashlib.sha256(hash_string.encode()).hexdigest()
    return sha


# pandas processing function to anonymise ids column
Ejemplo n.º 24
0
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('POSTGRES_DATABASE_URI')
app.config[
    'SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # do not track changes until saved
app.config[
    'PROPAGATE_EXCEPTIONS'] = True  # flask extensions can raise their own errors
app.config['JWT_BLACKLIST_ENABLED'] = True  # enable blacklisting user id's
app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = [
    'access', 'refresh'
]  # enable blacklist for those functions
app.config['JWT_SECRET_KEY'] = os.environ["JWT_SECRET_KEY"]
app.config['UPLOADED_IMAGES_DEST'] = os.path.join("static", "images")
app.config['DEBUG'] = True
patch_request_class(app, 10 * 1024 * 1024)  # 10MB image size limit
configure_uploads(app, IMAGE_SET)  # img extensions
api = Api(app)


@app.errorhandler(ValidationError)
def handle_marshmallow_validation(error):
    return jsonify(error.messages), 400


# Enable jwt authentication (check resources.user.UserLogin)
jwt = JWTManager(app)


@jwt.token_in_blacklist_loader
def chcek_if_token_in_blacklist(decrypted_token):
Ejemplo n.º 25
0
import os
from flask import Flask, request
from flask_uploads import UploadSet, configure_uploads, IMAGES,\
 patch_request_class

app = Flask(__name__)
app.config['UPLOADED_PHOTOS_DEST'] = os.getcwd()  # 文件储存地址

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app)  # 文件大小限制,默认为16MB

html = '''
    <!DOCTYPE html>
    <title>Upload File</title>
    <h1>图片上传</h1>
    <form method=post enctype=multipart/form-data>
         <input type=file name=photo>
         <input type=submit value=上传>
    </form>
    '''


@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        file_url = photos.url(filename)
        return html + '<br><img src=' + file_url + '>'
    return html
Ejemplo n.º 26
0
    UserLogin,
    User,
    TokenRefresh,
    UserLogout,
)
from resources.item import Item, ItemList
from resources.store import Store, StoreList
from resources.confirmation import Confirmation, ConfirmationByUser
from resources.image import ImageUpload, Image, AvatarUpload, Avatar
from libs.image_helper import IMAGE_SET

app = Flask(__name__)
load_dotenv(".env", verbose=True)
app.config.from_object("default_config")
app.config.from_envvar("APPLICATION_SETTINGS")
patch_request_class(app,
                    10 * 1024 * 1024)  # restrict max upload image size to 10MB
configure_uploads(app, IMAGE_SET)
api = Api(app)


@app.before_first_request
def create_tables():
    db.create_all()


@app.errorhandler(ValidationError)
def handle_marshmallow_validation(err):
    return jsonify(err.message), 400


jwt = JWTManager(app)
Ejemplo n.º 27
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)

    configure_uploads(app, images)
    patch_request_class(app, size=33554432)

    app.r = Redis.from_url(app.config['REDIS_URL'])
    app.q = Queue('climb_dest-tasks', connection=app.r)  # start worker: rq worker climb_dest-tasks

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

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

    from app.user import bp as user_bp
    app.register_blueprint(user_bp)

    from app.destinations import bp as destinations_bp
    app.register_blueprint(destinations_bp)

    from app.currency import bp as currency_bp
    app.register_blueprint(currency_bp)

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                toaddrs=app.config['ADMINS'], subject='climb_dest Failure',
                credentials=auth, secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/climb_dest.log', maxBytes=10240,
                                        backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('Climbit startup')

    return app
Ejemplo n.º 28
0
def CreateWallApp():
    app = WallApp(static_folder='assets', static_url_path='/assets')
    app.config.from_object(__name__ + '.ConfigClass')

    try:
        app.config.from_object('local_settings')
    except:
        pass

    # Use for Frontend debug
    CORS(app, resources={r"/api/*": {"origins": "*"}})

    Compress(app)
    Cache(app)
    babel = Babel(app)
    login = LoginManager(app)

    @login.unauthorized_handler
    def handle_needs_login():
        flash("You have to be logged in to access this page.")
        return redirect(url_for('login', next=request.endpoint))

    @app.route("/login", methods=["GET", "POST"])
    def login():
        if request.method == 'POST':
            username = request.form['username']
            password = request.form['password']

            user = User.query.filter(
                or_(User.username == username,
                    User.email == username)).first()
            if user is None or not user.check_password(password):
                flash("Sorry, but you could not log in.")
                redirect(url_for('home_page'))
            else:
                next = request.form['next']
                login_user(user, remember=True)
                return redirect(next)
        else:
            next = request.args.get('next')
            return render_template("login.html", next=next)

    login.login_view = 'login'

    @babel.localeselector
    def get_locale():
        return 'ru'

    app.dropzone = Dropzone(app)
    app.photos = UploadSet('photos', IMAGES)
    configure_uploads(app, app.photos)
    patch_request_class(app)

    @app.route('/')
    def home_page():
        users = db.session.query(func.count(User.id)).scalar()
        images = db.session.query(func.count(Image.id)).scalar()
        is_logedin = current_user.is_authenticated
        return render_template("index.html",
                               files=str(images),
                               users=str(users),
                               is_logedin=is_logedin)

    @app.route('/images_page')
    @login_required
    def images_page():
        return render_template('images_page.html')

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return redirect(url_for('home_page'))

    api = Api(app)

    class Images(Resource):
        def get(self, page):
            pglen = 10
            record_query = Image.query \
                .filter(Image.updated_at <= datetime.now()) \
                .paginate(int(page), pglen, False)

            files = record_query.items
            contents = []
            total = {'files': len(files), 'pglen': pglen}
            for file in files:
                filepath = app.photos.url(file.image)
                info = {}
                info['name'] = file.image
                info['width'] = file.width
                info['height'] = file.height
                info['url'] = filepath
                info['type'] = 'file'

                contents.append(info)
            return {'contents': contents, 'total': total}

    api.add_resource(Images, '/api/v1/FilesREST/<page>')

    return app
Ejemplo n.º 29
0
import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from flask_uploads import patch_request_class

# import atexit
# from apscheduler.schedulers.background import BackgroundScheduler

from flask_script import Manager, Server
from application import create_app
# from utilities.journal import print_date_time

app = create_app()
#file's size limit
patch_request_class(app, size=41943040)
manager = Manager(app)

# scheduler = BackgroundScheduler()
# scheduler.add_job(func=print_date_time,trigger='cron', hour='0')
# scheduler.start()

host = os.environ.get('IP', '127.0.0.1')
port = int(os.environ.get('PORT', 5000))

manager.add_command(
    "runserver",
    Server(use_debugger=True, use_reloader=True, host=host, port=port))

if __name__ == "__main__":
    manager.run()
Ejemplo n.º 30
0
app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024
manager = Manager(app)

#设置保存的位置
app.config['UPLOADED_PHOTOS_DEST'] = os.path.join(os.path.dirname(__file__),
                                                  'uploads')

#创建文件上传对象 主要用来设置 允许的上传类型
photos = UploadSet('photos', IMAGES)

#将上传对象 跟 app实例完成绑定
configure_uploads(app, photos)

#配置上传文件大小 size默认64M 如果size为None
#那么就会按照我们自己设置的 app.config['MAX_CONTENT_LENGTH'] 大小
patch_request_class(app, size=None)


@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/uploads/', methods=['GET', 'POST'])
def uploads():
    img_url = None
    if request.method == "POST":
        #保存文件
        filename = photos.save(request.files['photos'])
        #获取保存的url
        img_url = photos.url(filename)
Ejemplo n.º 31
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    load_dotenv()
    app.config.update(os.environ)

    @app.before_request
    def start_session():
        try:
            session["sid"]
        except KeyError:
            session["sid"] = urllib.parse.quote_plus(b64encode(os.urandom(10)))
            print("Starting with sid {}".format(session["sid"]))

    cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
    images = UploadSet("images", IMAGES)
    patch_request_class(app, 2 * 1024 * 1024)
    configure_uploads(app, images)

    from . import db
    from . import auth
    from . import views

    app.register_blueprint(auth.bp)
    app.register_blueprint(views.bp)
    from .blueprints.admin import admin_theme

    app.register_blueprint(admin_theme, url_prefix="/admin")
    app.add_url_rule("/", "index", views.__getattribute__("choose"))

    # the signals
    from .signals import journey_complete

    # Set custom modules path
    sys.path.append(app.config["MODULES_PATH"])

    with app.app_context():

        # Migrate database
        database.init_app(app)
        migrate = Migrate(app, database)
        upgrade('./migrations')

        if test_config is not None:
            seed_db()
            app.config.update(test_config)

        load_theme(app)

        # Register yml pages as routes
        pages = Page.query.all()
        for page in pages:
            page_path = page.path
            template_file = page.template_file
            view_func_name = page.page_name
            # Generate view function
            generate_view_func = """def %s_view_func():
            return render_template('%s')""" % (
                view_func_name,
                template_file,
            )
            exec(generate_view_func) in globals(), locals()
            method_name = view_func_name + "_view_func"
            possibles = globals().copy()
            possibles.update(locals())
            view_func = possibles.get(method_name)
            app.add_url_rule("/" + page_path, view_func_name + "_view_func",
                             view_func)

        # Import any custom modules
        modules = Module.query.all()
        print("sys.path contains: {}".format(sys.path))
        for module in modules:
            # Assume standard python module
            try:
                print("Attempting to importing module: {}".format(module.name))
                importlib.import_module(module.name)
            except ModuleNotFoundError:
                # Attempt to load module from src
                dest = Path(app.config["MODULES_PATH"], module.name)
                print("Cloning module into: {}".format(dest))
                os.makedirs(str(dest), exist_ok=True)
                try:
                    git.Repo.clone_from(module.src, dest)
                except git.exc.GitCommandError:
                    pass
                # Now re-try import
                try:
                    import site

                    reload(site)
                    importlib.import_module(module.name)
                except ModuleNotFoundError:
                    print("Error: Could not import module: {}".format(
                        module.name))
            # Register modules as blueprint (if it is one)
            try:
                importedModule = importlib.import_module(module.name)
                if isinstance(getattr(importedModule, module.name), Blueprint):
                    # Load any config the Blueprint declares
                    blueprint = getattr(importedModule, module.name)
                    blueprintConfig = "".join(
                        [blueprint.root_path, "/", "config.py"])
                    app.config.from_pyfile(blueprintConfig, silent=True)
                    # Register the Blueprint
                    app.register_blueprint(getattr(importedModule,
                                                   module.name))
                    print("Imported as flask Blueprint")
                    # Run Blueprint migrations if any
                    modulePath = Path(importedModule.__file__).parents[0]
                    moduleMigrationsPath = Path(modulePath, 'migrations')
                    if moduleMigrationsPath.is_dir():
                        # Run migrations
                        for migration in moduleMigrationsPath.iterdir():
                            print("Running module migration {}".format(
                                migration))
                            # Run subscribie_cli database migrations
                            db_full_path = app.config['DB_FULL_PATH']
                            subprocess.call("python " + str(migration) +
                                            ' -up -db ' + db_full_path,
                                            shell=True)

            except (ModuleNotFoundError, AttributeError):
                print("Error: Could not import module as blueprint: {}".format(
                    module["name"]))

    # Handling Errors Gracefully
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("errors/404.html"), 404

    @app.errorhandler(500)
    def page_not_found(e):
        return render_template("errors/500.html"), 500

    @app.cli.command()
    def initdb():
        """Initialize the database."""
        click.echo('Init the db')
        with open("seed.sql") as fp:
            con = sqlite3.connect(app.config["DB_FULL_PATH"])
            cur = con.cursor()
            cur.executescript(fp.read())
            con.close()

    return app
Ejemplo n.º 32
0
from app import app
from flask_uploads import UploadSet, configure_uploads, patch_request_class

IMAGES = tuple('jpg jpe jpeg png gif'.split())

profilepictures = UploadSet('profilepictures', IMAGES)
entityphotos = UploadSet('entityphotos', IMAGES)
pdftopos = UploadSet('pdftopos', ('pdf',))

configure_uploads(app, (
    profilepictures,
    entityphotos,
    pdftopos
))

patch_request_class(app, app.config['UPLOADS_MAX_FILESIZE'])
Ejemplo n.º 33
0
import os

from flask import Flask, request, redirect, url_for, render_template
from flask_restful import abort, reqparse, Resource, Api
from flask_restful.representations import json
from flask_uploads import UploadSet, IMAGES, configure_uploads, patch_request_class
from peewee import *
from playhouse.shortcuts import model_to_dict

app = Flask(__name__)
api = Api(app)

app.config['UPLOADED_PHOTOS_DEST'] = os.path.dirname(os.path.abspath(__file__))
photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)
patch_request_class(app, 12 * 1024 * 1024)


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST' and 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        return redirect(url_for('show', name=filename))
    return render_template('upload.html')


@app.route('/photo/<name>')
def show(name):
    if name is None:
        abort(404)
    url = photos.url(name)
Ejemplo n.º 34
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    HoneyMiddleware(
        app, db_events=True
    )  # db_events defaults to True, set to False if not using our db middleware with Flask-SQLAlchemy
    load_dotenv(verbose=True)
    app.config.update(os.environ)

    if test_config is not None:
        app.config.update(test_config)

    @app.before_request
    def start_session():
        try:
            session["sid"]
        except KeyError:
            session["sid"] = urllib.parse.quote_plus(b64encode(os.urandom(10)))
            print("Starting with sid {}".format(session["sid"]))

    @app.before_first_request
    def register_modules():
        """Import any custom modules"""
        # Set custom modules path
        sys.path.append(app.config["MODULES_PATH"])
        modules = Module.query.all()
        print("sys.path contains: {}".format(sys.path))
        for module in modules:
            # Assume standard python module
            try:
                print("Attempting to importing module: {}".format(module.name))
                importlib.import_module(module.name)
            except ModuleNotFoundError:
                # Attempt to load module from src
                dest = Path(app.config["MODULES_PATH"], module.name)
                print("Cloning module into: {}".format(dest))
                os.makedirs(str(dest), exist_ok=True)
                try:
                    git.Repo.clone_from(module.src, dest)
                except git.exc.GitCommandError:
                    pass
                # Now re-try import
                try:
                    import site

                    reload(site)
                    importlib.import_module(module.name)
                except ModuleNotFoundError:
                    print("Error: Could not import module: {}".format(
                        module.name))
            # Register modules as blueprint (if it is one)
            try:
                importedModule = importlib.import_module(module.name)
                if isinstance(getattr(importedModule, module.name), Blueprint):
                    # Load any config the Blueprint declares
                    blueprint = getattr(importedModule, module.name)
                    blueprintConfig = "".join(
                        [blueprint.root_path, "/", "config.py"])
                    app.config.from_pyfile(blueprintConfig, silent=True)
                    # Register the Blueprint
                    app.register_blueprint(getattr(importedModule,
                                                   module.name))
                    print(f"Imported {module.name} as flask Blueprint")

            except (ModuleNotFoundError, AttributeError):
                print("Error: Could not import module as blueprint: {}".format(
                    module.name))

    CORS(app, resources={r"/api/*": {"origins": "*"}})
    CORS(app, resources={r"/auth/jwt-login/*": {"origins": "*"}})
    images = UploadSet("images", IMAGES)
    patch_request_class(
        app, int(app.config.get("MAX_CONTENT_LENGTH", 2 * 1024 * 1024)))
    configure_uploads(app, images)

    from . import auth
    from . import views
    from . import api

    app.register_blueprint(auth.bp)
    app.register_blueprint(views.bp)
    app.register_blueprint(api.api)
    from .blueprints.admin import admin
    from .blueprints.subscriber import subscriber
    from .blueprints.pages import module_pages
    from .blueprints.iframe import module_iframe_embed
    from .blueprints.style import module_style_shop
    from .blueprints.seo import module_seo_page_title

    app.register_blueprint(module_pages, url_prefix="/pages")
    app.register_blueprint(module_iframe_embed, url_prefix="/iframe")
    app.register_blueprint(module_style_shop, url_prefix="/style")
    app.register_blueprint(module_seo_page_title, url_prefix="/seo")
    app.register_blueprint(admin, url_prefix="/admin")
    app.register_blueprint(subscriber)

    app.add_url_rule("/", "index", views.__getattribute__("choose"))

    with app.app_context():

        database.init_app(app)
        Migrate(app, database)

        try:
            payment_provider = PaymentProvider.query.first()
            if payment_provider is None:
                # If payment provider table not seeded, seed with blank values.
                payment_provider = PaymentProvider()
                database.session.add(payment_provider)
                database.session.commit()
        except sqlalchemy.exc.OperationalError as e:
            # Allow to fail until migrations run (flask upgrade requires app reboot)
            print(e)

        load_theme(app)

    # Handling Errors Gracefully
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("errors/404.html"), 404

    @app.errorhandler(413)
    def request_entity_too_large(error):
        return "File Too Large", 413

    @app.errorhandler(500)
    def page_error_500(e):
        return render_template("errors/500.html"), 500

    @app.cli.command()
    def initdb():
        """Initialize the database."""
        click.echo("Init the db")
        with open("seed.sql") as fp:
            con = sqlite3.connect(app.config["DB_FULL_PATH"])
            cur = con.cursor()
            # Check not already seeded
            cur.execute("SELECT id from user")
            if cur.fetchone() is None:
                cur.executescript(fp.read())
            else:
                print("Database already seeded.")
            con.close()

    @app.cli.command()
    def alert_subscribers_make_choice():
        """Alert qualifying subscribers to set their choices

        For all people (aka Subscribers)

        - Loop over their *active* subscriptions
        - Check if x days before their subscription.next_date
        - If yes, sent them an email alert
        """
        def alert_subscriber_update_choices(subscriber: Person):
            email_template = str(
                Path(current_app.root_path +
                     "/emails/update-choices.jinja2.html"))
            # App context needed for request.host (app.config["SERVER_NAME"] not set)
            with app.test_request_context("/"):
                update_options_url = ("https://" + flask.request.host +
                                      url_for("subscriber.login"))
                company = Company.query.first()
                with open(email_template) as file_:
                    template = Template(file_.read())
                    html = template.render(
                        update_options_url=update_options_url, company=company)
                    try:
                        mail = Mail(current_app)
                        msg = Message()
                        msg.subject = company.name + " " + "Update Options"
                        msg.sender = current_app.config["EMAIL_LOGIN_FROM"]
                        msg.recipients = [person.email]
                        msg.html = html
                        mail.send(msg)
                    except Exception as e:
                        print(e)
                        print("Failed to send update choices email")

        people = Person.query.all()

        for person in people:
            for subscription in person.subscriptions:
                if (get_subscription_status(
                        subscription.gocardless_subscription_id) == "active"):
                    # Check if x days until next subscription due, make configurable
                    today = datetime.date.today()
                    days_until = subscription.next_date().date() - today
                    if days_until.days == 8:
                        print(f"Sending alert for subscriber '{person.id}' on \
                              plan: {subscription.plan.title}")
                        alert_subscriber_update_choices(person)

    return app
Ejemplo n.º 35
0
def create_app(config_filename="config.py",
               app_name=None,
               register_blueprints=True):
    # App configuration
    app = Flask(app_name or __name__)

    env_cfg = os.getenv("CUSTOM_CONFIG", config_filename)
    app.config.from_pyfile(env_cfg)

    Bootstrap(app)

    app.jinja_env.add_extension("jinja2.ext.with_")
    app.jinja_env.add_extension("jinja2.ext.do")
    app.jinja_env.globals.update(is_admin=is_admin)
    app.jinja_env.filters["state_to_str"] = state_str

    if HAS_SENTRY:
        app.config["SENTRY_RELEASE"] = raven.fetch_git_sha(
            os.path.dirname(__file__))
        sentry = Sentry(app, dsn=app.config["SENTRY_DSN"])  # noqa: F841
        print(" * Sentry support activated")
        print(" * Sentry DSN: %s" % app.config["SENTRY_DSN"])

    if app.config["DEBUG"] is True:
        app.jinja_env.auto_reload = True
        app.logger.setLevel(logging.DEBUG)

    # Logging
    if not app.debug:
        formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s "
                                      "[in %(pathname)s:%(lineno)d]")
        file_handler = RotatingFileHandler("%s/errors_app.log" % os.getcwd(),
                                           "a", 1000000, 1)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        app.logger.addHandler(file_handler)

    mail.init_app(app)
    migrate = Migrate(app, db)  # noqa: F841
    babel = Babel(app)  # noqa: F841
    toolbar = DebugToolbarExtension(app)  # noqa: F841

    db.init_app(app)

    # Setup Flask-Security
    security = Security(  # noqa: F841
        app,
        user_datastore,
        register_form=ExtendedRegisterForm,
        confirm_register_form=ExtendedRegisterForm)

    @FlaskSecuritySignals.password_reset.connect_via(app)
    @FlaskSecuritySignals.password_changed.connect_via(app)
    def log_password_reset(sender, user):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info",
                     "Your password has been changed !")

    @FlaskSecuritySignals.reset_password_instructions_sent.connect_via(app)
    def log_reset_password_instr(sender, user, token):
        if not user:
            return
        add_user_log(user.id, user.id, "user", "info",
                     "Password reset instructions sent.")

    git_version = ""
    gitpath = os.path.join(os.getcwd(), ".git")
    if os.path.isdir(gitpath):
        git_version = subprocess.check_output(
            ["git", "rev-parse", "--short", "HEAD"])
        if git_version:
            git_version = git_version.strip().decode("UTF-8")

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.locale
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(["fr", "en"])

    @babel.timezoneselector
    def get_timezone():
        identity = getattr(g, "identity", None)
        if identity is not None and identity.id:
            return identity.user.timezone

    @app.before_request
    def before_request():
        cfg = {
            "CAMGEAR_VERSION_VER": VERSION,
            "CAMGEAR_VERSION_GIT": git_version,
            "CAMGEAR_VERSION": "{0} ({1})".format(VERSION, git_version),
        }
        g.cfg = cfg

    @app.errorhandler(InvalidUsage)
    def handle_invalid_usage(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    pictures = UploadSet("pictures", IMAGES)
    configure_uploads(app, pictures)
    patch_request_class(app, 10 * 1024 * 1024)  # 10m limit

    thumb = Thumbnail(app)  # noqa: F841

    if register_blueprints:
        from controllers.main import bp_main

        app.register_blueprint(bp_main)

        from controllers.users import bp_users

        app.register_blueprint(bp_users)

        from controllers.admin import bp_admin

        app.register_blueprint(bp_admin)

        from controllers.accessories import bp_accessories

        app.register_blueprint(bp_accessories)

        from controllers.cameras import bp_cameras

        app.register_blueprint(bp_cameras)

        from controllers.lenses import bp_lenses

        app.register_blueprint(bp_lenses)

        from controllers.autocompletion import bp_autocomplete

        app.register_blueprint(bp_autocomplete)

    @app.route("/uploads/<string:thing>/<path:stuff>", methods=["GET"])
    def get_uploads_stuff(thing, stuff):
        if app.debug:
            directory = safe_join(app.config["UPLOADS_DEFAULT_DEST"], thing)
            app.logger.debug(f"serving {stuff} from {directory}")
            return send_from_directory(directory, stuff, as_attachment=True)
        else:
            app.logger.debug(f"X-Accel-Redirect serving {stuff}")
            resp = Response("")
            resp.headers[
                "Content-Disposition"] = f"attachment; filename={stuff}"
            resp.headers[
                "X-Accel-Redirect"] = f"/_protected/media/tracks/{thing}/{stuff}"
            return resp

    @app.errorhandler(404)
    def page_not_found(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 404,
            "message": gettext("Page not found"),
            "e": msg,
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 404

    @app.errorhandler(403)
    def err_forbidden(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 403,
            "message": gettext("Access forbidden"),
            "e": msg,
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 403

    @app.errorhandler(410)
    def err_gone(msg):
        pcfg = {
            "title": gettext("Whoops, something failed."),
            "error": 410,
            "message": gettext("Gone"),
            "e": msg
        }
        return render_template("error_page.jinja2", pcfg=pcfg), 410

    if not app.debug:

        @app.errorhandler(500)
        def err_failed(msg):
            pcfg = {
                "title": gettext("Whoops, something failed."),
                "error": 500,
                "message": gettext("Something is broken"),
                "e": msg,
            }
            return render_template("error_page.jinja2", pcfg=pcfg), 500

    @app.after_request
    def set_x_powered_by(response):
        response.headers["X-Powered-By"] = "camgear"
        return response

    # Other commands
    @app.cli.command()
    def routes():
        """Dump all routes of defined app"""
        table = texttable.Texttable()
        table.set_deco(texttable.Texttable().HEADER)
        table.set_cols_dtype(["t", "t", "t"])
        table.set_cols_align(["l", "l", "l"])
        table.set_cols_width([50, 30, 80])

        table.add_rows([["Prefix", "Verb", "URI Pattern"]])

        for rule in sorted(app.url_map.iter_rules(), key=lambda x: str(x)):
            methods = ",".join(rule.methods)
            table.add_row([rule.endpoint, methods, rule])

        print(table.draw())

    @app.cli.command()
    def config():
        """Dump config"""
        pp(app.config)

    @app.cli.command()
    def seed():
        """Seed database with default content"""
        make_db_seed(db)

    @app.cli.command()
    def createuser():
        """Create an user"""
        username = click.prompt("Username", type=str)
        email = click.prompt("Email", type=str)
        password = click.prompt("Password",
                                type=str,
                                hide_input=True,
                                confirmation_prompt=True)
        while True:
            role = click.prompt("Role [admin/user]", type=str)
            if role == "admin" or role == "user":
                break

        if click.confirm("Do you want to continue ?"):
            role = Role.query.filter(Role.name == role).first()
            if not role:
                raise click.UsageError("Roles not present in database")
            u = user_datastore.create_user(name=username,
                                           email=email,
                                           password=hash_password(password),
                                           roles=[role])

            db.session.commit()

            if FSConfirmable.requires_confirmation(u):
                FSConfirmable.send_confirmation_instructions(u)
                print("Look at your emails for validation instructions.")

    return app
Ejemplo n.º 36
0
def create_app(config_name=None):
    """Returns the Flask app."""
    app = Flask(__name__, template_folder='templates')
    if not config_name:
        config_name = os.getenv('FLASK_ENV')

    if config_name == 'production':
        setup_logger_handlers(app)

    app.config.from_object(app_config[config_name])

    app.jinja_env.line_statement_prefix = '%'
    app.jinja_env.filters['datetimeformat'] = datetimeformat

    assets.init_app(app)
    oauth.init_app(app)
    # Compare the init_app of cache to oauth later
    cache.init_app(app,
                   config={
                       'CACHE_TYPE': 'redis',
                       'CACHE_DEFAULT_TIMEOUT': 5,
                       'CACHE_REDIS_HOST': os.getenv('REDIS_HOST'),
                       'CACHE_REDIS_PORT': os.getenv('REDIS_PORT'),
                       'CACHE_KEY_PREFIX': 'benwaonline:'
                   })
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        if user_id:
            key = 'user_{}'.format(user_id)
            r = cache.get(key)
            if not r:
                r = UserGateway().get_by_user_id(user_id)
                cache.set(key, r, timeout=3600)
            return r
        return None

    @login_manager.unauthorized_handler
    def handle_unauthorized():
        return redirect(url_for('authbp.authorize'))

    @app.errorhandler(BenwaOnlineError)
    def handle_error(error):
        args = error.args[0]
        msg = '{} - {}'.format(args['title'], args['source'])
        current_app.logger.debug(msg)
        return render_template('error.html', error=msg)

    @app.errorhandler(BenwaOnlineRequestError)
    def handle_request_error(error):
        msg = 'BenwaOnlineRequestError @ main: {}'.format(error)
        current_app.logger.debug(msg)

        return render_template('request_error.html', error=error)

    register_blueprints(app)

    configure_uploads(app, (images, ))
    patch_request_class(app, FILE_SIZE_LIMIT)

    return app
Ejemplo n.º 37
0
from flask import (Flask, request, flash, redirect, send_from_directory,
                   render_template, url_for)
from flask_uploads import UploadSet, configure_uploads, patch_request_class, ALL
from werkzeug import SharedDataMiddleware

basedir = os.getcwd()
app = Flask(__name__)
app.config['UPLOADED_FILES_DEST'] = os.path.join(basedir, 'uploads')
app.config['FILE_PATH'] = os.path.join(basedir, 'uploads')
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'ouahflnl'

upload_file = UploadSet('files', ALL)
configure_uploads(app, upload_file)
patch_request_class(app, 5*1024*1024*1024*1024)


@app.route("/file/<filename>", build_only=True)
def prev_file(filename):
    return send_from_directory(app.config.get('UPLOADED_FILES_DEST'), filename)


app.wsgi_app = SharedDataMiddleware(
    app.wsgi_app,
    {
        "/file": app.config.get("UPLOADED_FILES_DEST")
    },
    cache=False
)