def get_jwt_user():
    """
    解密token,得到payload
    :return:
    """
    secret = config_obj.get("user", "secret")
    algorithms = config_obj.get("user", "algorithms")
    try:
        token = request.headers['Authorization']
        payload =  jwt.decode(token, secret, algorithms=algorithms)
        if payload and 'user_id' in payload:
            return payload
    except:
        abort(401, "Invalid JWT header")
def encode_auth_token(user_id, account_id):
    """
    生成认证Token
    :return: string
    """
    try:
        # token七天过期,需要重新登录 测试1天过期
        expire_at = datetime.now() + timedelta(1)
        payload = {
            "user_id": user_id,
            "account_id": account_id,
            "login_time": (datetime.now()).strftime('%Y-%m-%d %H:%M:%S'),
            "exp": expire_at
        }
        jwt_en = jwt.encode(
            payload,
            config_obj.get('user', 'secret'),
            algorithm="HS256"
        ).decode('utf-8')
        return jwt_en
    except Exception as e:
        logging.info("create authentication error %s %s", user_id, e)
        return e
Exemple #3
0
# coding:utf-8

from configuration import config_obj

bind = config_obj.get("gunicorn", "bind")
# 64-2048
backlog = config_obj.getint("gunicorn", "backlog")
# workers = multiprocessing.cpu_count() * 3
workers = config_obj.get("gunicorn", "workers")
worker_class = config_obj.get("gunicorn", "worker_class")
# 同步响应最长处理时间
timeout = config_obj.getint("gunicorn", "timeout")
pidfile = config_obj.get("gunicorn", "pidfile")
debug = config_obj.getboolean("gunicorn", "debug")
# gunicorn -c flask_config.py server:application
# 设置日志记录水平
loglevel = 'debug'
# 设置错误信息日志路径
errorlog = '/var/logs/error.logs'
# 设置访问日志路径
accesslog = '/var/logs/access.logs'

# 跑的时候设置log level, 最终就可以将flask的日志输出在gunicorn上了
# $ gunicorn --workers=4 --bind=0.0.0.0:8000 --logs-level=warning apps:apps
from utils.flask_json_encode import JSONEncoder
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin
from configuration import config_obj
from flask_config import config


class RetryMySQLDatabase(ReconnectMixin, PooledMySQLDatabase):
    pass
    # def begin(self):
    #     # db api 并没有自动加 begin 语句,所以在此要手动加上
    #     self.get_conn().begin()


db = RetryMySQLDatabase(
    config_obj.get('db', 'database'),
    max_connections=config_obj.getint('db', 'max_connections'),
    stale_timeout=config_obj.getint('db', 'stale_timeout'),
    host=config_obj.get('db', 'host'),
    user=config_obj.get('db', 'user'),
    password=config_obj.get('db', 'password'),
    port=config_obj.getint('db', "port")
)

from playhouse.flask_utils import FlaskDB


def create_app(config_name):
    _app = Flask(__name__)
    _app.config.from_object(config[config_name])
    _app.json_encoder = JSONEncoder
 def get_base_url(self):
     return config_obj.get("gateway", "base_url")
Exemple #6
0
# -*- coding:utf-8 -*-
import logging
import os
from logging import Logger, StreamHandler
from logging.handlers import TimedRotatingFileHandler
from configuration import config_obj

log_level = config_obj.get("logging", "level") if config_obj.get("logging", "level") else "info"


def init_logger(logger_name):
    if not os.path.exists("logs"):
        os.mkdir("logs")
    if logger_name not in Logger.manager.loggerDict:
        logger = logging.getLogger(logger_name)
        logger.setLevel(logging.DEBUG)
        # handler all
        screen_handler = StreamHandler()
        handler = TimedRotatingFileHandler('./logs/{}_all.logs'.format(logger_name), when='midnight', backupCount=7)
        datefmt = "%Y-%m-%d %H:%M:%S"
        format_str = "[%(asctime)s]: %(name)s %(levelname)s %(lineno)s %(message)s"
        formatter = logging.Formatter(format_str, datefmt)
        screen_handler.setFormatter(formatter)
        screen_handler.setLevel(logging.DEBUG)
        handler.setFormatter(formatter)
        handler.setLevel(eval("logging.{}".format(log_level.upper())))
        logger.addHandler(handler)
        logger.addHandler(screen_handler)
        # handler error
        handler = TimedRotatingFileHandler('./logs/{}_error.logs'.format(logger_name), when='midnight', backupCount=7)
        datefmt = "%Y-%m-%d %H:%M:%S"
Exemple #7
0
from flask_cors import CORS
from utils.flask_json_encode import JSONEncoder
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin
from configuration import config_obj
from flask_config import config


class RetryMySQLDatabase(ReconnectMixin, PooledMySQLDatabase):
    pass
    # def begin(self):
    #     # db api 并没有自动加 begin 语句,所以在此要手动加上
    #     self.get_conn().begin()


db = RetryMySQLDatabase(config_obj.get('db', 'database'),
                        max_connections=config_obj.getint(
                            'db', 'max_connections'),
                        stale_timeout=config_obj.getint('db', 'stale_timeout'),
                        host=config_obj.get('db', 'host'),
                        user=config_obj.get('db', 'user'),
                        password=config_obj.get('db', 'password'),
                        port=config_obj.getint('db', "port"))

from playhouse.flask_utils import FlaskDB


def create_app(config_name):
    _app = Flask(__name__)
    _app.config.from_object(config[config_name])
    _app.json_encoder = JSONEncoder