Beispiel #1
0
def create_app():
    from flask import Flask
    app = Flask(__name__)

    from flask_cors import CORS
    CORS(app, support_credentials=True)

    from configs import Config
    app.config.from_object(Config)

    import utils, models, user, auth
    utils.init_app(app)
    models.init_app(app)
    user.init_app(app)
    auth.init_app(app)

    return app
Beispiel #2
0
def create_app(config):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    init_logger_from_object(config)

    global app
    app = Flask(__name__)

    api = Api(app=app,
              title=config.SERVICE_NAME,
              version=config.SERVICE_VERSION,
              doc=config.SWAGGER_PATH)

    app.config.from_object(config)

    # context init
    context.init_app(app)

    # v2.0.1 init
    from server.resource.v2 import init_api
    init_api(api)

    # exception handler
    from server.exception import init_api_error
    init_api_error(api)

    # init utils
    import utils
    utils.init_app(app)

    # init db
    from utils import db_session
    db_session.init_app(app)

    # init redis
    from utils import redis_cache
    redis_cache.init_app(app)

    from server.dao import init_app
    init_app(app)

    global jwt
    jwt = JWTManager(app)

    from utils.redis_cache import get_client

    # issues flask-jwt-extended 和 flask_restplaus 不能调用  jwt.expired_token_loader 等回调
    # 参考https://github.com/vimalloc/flask-jwt-extended/issues/86

    # @jwt.user_claims_loader
    # def add_claims_to_access_token(identity):
    #     # 再token中添加额外数据
    #     return {
    #         'email': identity['email']
    #     }

    # @jwt.user_identity_loader
    # def user_identity_lookup(user):
    #     return user

    # @jwt.user_loader_callback_loader
    # def user_loader_callback(identity):
    #
    #     current = {
    #         "test": "123",
    #         "user": identity
    #     }
    #     return current

    @jwt.token_in_blacklist_loader
    def check_if_token_is_revoked(decrypted_token):
        # 检查token是否被作废
        _redis = get_client()
        jti = decrypted_token['jti']
        entry = _redis.get(jti)
        if entry is None:
            return True
        return entry == 'true'

    return app
Beispiel #3
0
import os
import datetime
import time
import random

import flask
import werkzeug

import utils
import db
import images

app = flask.Flask("ureports")

utils.init_app(app)
db.init_app(app)
images.init_app(app)

with app.app_context():
    app.config.update(
        dict(DATA=os.path.join(app.root_path, "data", flask.current_app.name),
             DEBUG=False,
             SECRET="",
             IMG_TYPE="png",
             IMG_AGENT_XY=(500, 500),
             IMG_REPORT_XY=(2000, 2000),
             IMG_REPORT_THUMB_XY=(500, 500)))

    # For convenience:
    app.config["DATABASE"] = os.path.join(app.config["DATA"],
                                          flask.current_app.name + ".db")
Beispiel #4
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    app.config['MAX_CONTENT_LENGTH'] = app.config.get('MAX_CONTENT_LENGTH')

    # 开启调试模式
    app.debug = app.config.get('DEBUG')

    # jinja2 None to ''
    app.jinja_env.finalize = finalize

    # init utils
    import utils
    utils.init_app(app)

    # init logger
    log_handler = FinalLogger(app).get_logger()
    app.logger.addHandler(log_handler)

    # init redis
    # from utils import redis_cache
    # redis_cache.init_app(app)

    from app import template_filter
    template_filter.init_app(app)

    # 初始化路由
    import routing
    routing.init_routing(app)

    # 注册蓝图
    register_blueprints(app)

    # 添加当前时间戳 全局变量
    app.add_template_global(int(time.time()), 'current_time')

    @app.after_request
    def after_request(response):
        for query in get_debug_queries():
            if query.duration >= current_app.config[
                    'FLASKY_SLOW_DB_QUERY_TIME']:
                current_app.logger.warning(
                    'Slow query: %s\nParameters: %s\nDuration: %fs\nContext: %s\n'
                    % (query.statement, query.parameters, query.duration,
                       query.context))
        return response

    @app.errorhandler(Exception)
    def handle_exception(e):
        if current_app.config['CONFIG_NAME'] != 'local':
            if not isinstance(e, ServerBaseException):
                logger.exception(u'service has exception: {0}'.format(
                    e.message))
                import traceback
                from utils import email_util
                title = u'Server-%s-%s' % (current_app.config['CONFIG_NAME'],
                                           email_util.get_exception_message(e))
                body = u'Server异常: \n{message}'.format(
                    message=traceback.format_exc())
                email_util.send_warning_email(title, body,
                                              ['*****@*****.**'])
        return e.message

    return app
Beispiel #5
0
plt.setLabel("bottom", u"Amostra")
plt.setYRange(0, Y_MAX)
plt.setXRange(0, X_MAX-1)

rt_data = collections.deque(maxlen=X_MAX)
rms_data = collections.deque(maxlen=X_MAX)
count = 0

def update_rms_voltage():
	pass

def update_rt_voltage():
	try:
		value = int(arduino.readline())
		rt_data.append(value)
		rt_curve.setData(rt_data)

		global count
		count = (count + 1) % X_MAX
		if not count:
			update_rms_voltage()

	except ValueError:
		pass

tmr = utils.init_timer(update_rt_voltage)
tmr.start(0)

if __name__ == '__main__':
	utils.init_app()
Beispiel #6
0
import aiohttp_jinja2
import jinja2
from aiohttp import web

from background_tasks import start_background_tasks, cleanup_background_tasks
from routes import setup_routes
from utils import init_app

app = web.Application()
app = init_app(app)

app.router.add_static('/static/', path='static', name='static')
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))

app.on_startup.append(start_background_tasks)
app.on_cleanup.append(cleanup_background_tasks)

setup_routes(app)
web.run_app(app)