Beispiel #1
0
service_opts = [
    {
        "name": 'report_interval',
        "default": 30,
        "help": 'seconds between nodes reporting state to datastore',
        "type": int,
    },
    {
        "name": 'periodic_interval',
        "default": 60,
        "help": 'seconds between running periodic tasks',
        "type": int,
    },
]

options = get_options(service_opts, 'services')


class Launcher(object):
    """Launch one or more services and wait for them to complete."""
    def __init__(self):
        """Initialize the service launcher.

        :returns: None

        """
        self._services = []

    @staticmethod
    def run_server(server):
        """Start and wait for a server to finish.
Beispiel #2
0
from ops_charging import cache
from ops_charging import utils
from ops_charging import log as logging

from ops_charging.service import db as service_db

auth_opts = [
    {
        "name": "policy",
        "default": "ops_charging.api.auth.policy",
        "help": "",
        "type": str,
    },
]

options = get_options(auth_opts, 'auth')

LOG = logging.getLogger()


def load_policy():
    option_split = options.policy.split(".")
    mod = option_split[0]
    fun = options.policy[options.policy.rfind('.') + 1:]
    fn_, modpath, desc = imp.find_module(mod)
    fn_, path, desc = imp.find_module(
        fun, [os.path.join(modpath, "/".join(option_split[1:-1]))])
    return imp.load_module(fun, fn_, path, desc)


class BaseAuth(tornado.web.RequestHandler):
Beispiel #3
0
import uuid
import json
import requests
import time

import datetime
import socket

from eventlet import event
from eventlet import greenthread

from ops_charging.options import get_options
from ops_charging import log as logging
from ops_charging import exception

options = get_options()

LOG = logging.getLogger(__name__)


def import_class(import_str):
    """Returns a class from a string including module and class."""
    mod_str, _sep, class_str = import_str.rpartition('.')
    try:
        __import__(mod_str)
        return getattr(sys.modules[mod_str], class_str)
    except (ImportError, ValueError, AttributeError), exc:
        LOG.debug('Inner Exception: %s', exc)
        raise exception.ClassNotFound(class_name=class_str, exception=exc)

Beispiel #4
0
# """Session Handling for SQLAlchemy backend."""

import mysql.connector
# import time
# import json
# import datetime
#
# import sqlalchemy.interfaces
# import sqlalchemy.orm
# from sqlalchemy.exc import DisconnectionError, OperationalError
# from sqlalchemy.pool import NullPool, StaticPool
# from ops_charging.db.models import db_session, engine
#
# from ops_charging import exception

from ops_charging.options import get_options

db_options = [
    {
        "name": 'db_user',
        "default": "charging",
        "help": '',
        "type": str,
    },
]
options = get_options(db_options)
Beispiel #5
0
from ops_charging.utils import get_http, post_http, get_token, ConvertTime2Int
import ops_charging.log as logging
import uuid
import time
import json
import random

from ops_charging.plugins.users_plugins import UserOperate
from ops_charging.plugins.expr_money_plugins import ExprOrders
from ops_charging import cache
from ops_charging.service import manager
from ops_charging.options import get_options

LOG = logging.getLogger(__name__)
discount_opts = []
options = get_options(discount_opts)


class DiscountOperate(object):
    def __init__(self, *args, **kwargs):
        print "i am init"

    @staticmethod
    def add_discount(id, money, valid_date, user_context, description=None):
        try:
            if not id or not money or not valid_date or not user_context:
                em = "invalid argement with add discount"
                LOG.exception(em)
                return False, 400
            # must be admin role
            if not user_context.get("user").get("admin"):
Beispiel #6
0
import ops_charging.plugins.orderinfo_plugins as orderinfo_plugins
import ops_charging.log as logging
from ops_charging.options import get_options

LOG = logging.getLogger(__name__)

# not used
order_opts = [
    {
        "name": "testaaaaaaa1aaaa",
        "default": "111111111",
        "type": str
    },
]

options = get_options(order_opts)


class PriceOperation(object):
    def __init__(self):
        pass

    @staticmethod
    def get_price():
        try:
            prices = Price.query.filter().all()
            if not prices:
                em = "not any more prices....."
                LOG.exception(em)
                return False, 500
            return True, prices
import shutil
import uuid
import os
import time

from ops_charging.db.models import db_session, UploadLog, Invoice
from sqlalchemy import and_
from ops_charging.utils import get_http, post_http, get_token, ConvertTime2Int
import ops_charging.log as logging
from ops_charging import cache
from ops_charging.service import manager
from ops_charging.options import get_options

LOG = logging.getLogger(__name__)
file_upload_opts = []
options = get_options(file_upload_opts)


class FileUploadOperate(object):
    """tornado upload/download file operate"""
    @staticmethod
    def save_file(files, file_path, user_info):
        isExists = os.path.exists(file_path)
        if not isExists:
            os.makedirs(file_path)
        if not files:
            return None
        # 添加到数据库
        db_obj = UploadLog(
            str(uuid.uuid1()),
            user_info.get("user_id"),
Beispiel #8
0
from ops_charging.service import manager
from ops_charging.options import get_options

LOG = logging.getLogger(__name__)
invoice_opts = [
    # 不能开取发票的充值类型
    {"name": "reject_recharge_type",
     "default": ["deveops",
                 "discount_id",
                 ],
    #  "default": [],
     "type": list
     },

]
options = get_options(invoice_opts)


class InvoiceOperate(object):

    @staticmethod
    def add_invoice(data, upfile_uuid):
        # 计算所有充值记录之和
        if not data.orders:
            em = "no any more orders id"
            LOG.exception(em)
            raise HTTPError(400, em)
        money = 0
        for order in data.orders:
            # 查找所有充值记录
            recharge = RechargeLog.query.filter(RechargeLog.uid == order).first()
Beispiel #9
0
import uuid
import time
from ops_charging.db.models import db_session, Orders, Price, User, ConsumeLog
from sqlalchemy import and_

import ops_charging.plugins.orderinfo_plugins as orderinfo_plugins
import ops_charging.log as logging
from ops_charging.options import get_options
from ops_charging.plugins.expr_money_plugins import ExprOrders

LOG = logging.getLogger(__name__)

# not used
order_tencent_opts = [
]
options = get_options(order_tencent_opts)


class TencentOrders(object):
    @staticmethod
    def add_order(data):
        """添加订单"""
        data = orderinfo_plugins.GetOrderAbout(data)
        for r_name, used in data.resources.iteritems():
            if not used:
                continue
            order_object = Orders(str(uuid.uuid1()),
                                  start_time=data.time_stamp,
                                  end_time=data.end_time,
                                  resource_from=data.resource_from,
                                  resource_from_provider=data.resource_from_provider,
Beispiel #10
0
from ops_charging.utils import get_http, post_http, get_token
import ops_charging.log as logging

from ops_charging import cache
from ops_charging.options import get_options

LOG = logging.getLogger(__name__)
sms_opts = [
    {
        "name": "",
        "default": "",
        "help": "",
        "type": str
    },
]
options = get_options(sms_opts)

#encoding=utf-8

from yunpian_python_sdk.model import constant as YC
from yunpian_python_sdk.ypclient import YunpianClient
import cPickle

from ops_sia.cache import Backend
import random
from tomorrow import threads
from ops_sia.options import get_options
from ops_sia.utils import get_http, post_http, get_token
import ops_sia.log as logging

LOG = logging.getLogger(__name__)
Beispiel #11
0
from ops_charging.options import get_options

auth_opts = [{
    "name": "cached_backend",
    "default": 'redis://127.0.0.1:6379/0',
    "help": 'cached backend uri',
    "type": str,
}, {
    "name": 'cache_timeout',
    "default": '3600',
    "help": 'cache timeout seconds',
    "type": str,
}]

options = get_options(auth_opts, 'cache')


class Backend(object):
    def __init__(self):
        cached_backend = options.cached_backend
        _conn = cached_backend.split("//")[1]
        if '@' in _conn:
            passwd, host_port = _conn.split('@')
        else:
            passwd = None
            host_port = _conn
        if passwd:
            passwd = passwd[1:]
        host, db_p = host_port.split(':')
        port, db = db_p.split('/')
Beispiel #12
0
from ops_charging.options import get_options
import ops_charging.log as logging
from ops_charging.utils import post_http, get_http

LOG = logging.getLogger(__name__)

wechatpay_options = [
    {
        "name": "",
        "default": '',
        "help": "",
        "type": str
    },
]

options = get_options(wechatpay_options)


class GneQRCode(object):
    def __init__(self, url, version=5, box_size=10, border=4):
        self.url = url.strip()
        self.version = version
        self.box_size = box_size
        self.border = border

    @property
    def qr_code(self):
        qr = qrcode.QRCode(
            version=self.version,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=self.box_size,
Beispiel #13
0
    "default": "https://mapi.alipay.com/gateway.do?",
    "type": str
}, {
    "name": "OPEN_API_GW",
    "default": "https://openapi.alipay.com/gateway.do?",
    "type": str
}, {
    "name": "PayStatus",
    "default": {
        "TRADE_FINISHED": "success",
        "TRADE_SUCCESS": "success"
    },
    "type": dict
}]

options = get_options(alipay_options)


class AliPayPlugins(object):
    @staticmethod
    def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
        """
        Returns a bytestring version of 's', encoded as specified in 'encoding'.
    
        If strings_only is True, don't convert (some) non-string-like objects.
        """
        if strings_only and isinstance(s, (types.NoneType, int)):
            return s
        if not isinstance(s, basestring):
            try:
                return str(s)
        "type": int
    },
    {
        "name":
        "check_time",
        "default": [
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23
        ],
        "help":
        "send msg to user at work time",
        "type":
        list
    },
]
options = get_options(users_opts)


class UserOperate(manager.Manager):
    def __init__(self, *args, **kwargs):
        super(UserOperate, self).__init__()
        print "i am init"

    @staticmethod
    def add_user(data):
        project_id = data.get("tenant_id")
        project_name = data.get("_context_project_name")
        user_id = data.get("user_id")
        user_name = data.get('_context_user_name')
        id = str(uuid.uuid1())
        exist_user = User.query.filter(User.user_id == user_id).first()