当前位置: 首页>>代码示例>>Python>>正文


Python models.DBSession类代码示例

本文整理汇总了Python中ccvpn.models.DBSession的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: forgot

def forgot(request):
    if request.method != 'POST' or 'username' not in request.POST:
        return {}

    u = DBSession.query(User) \
        .filter_by(username=request.POST['username']) \
        .first()
    if not u:
        request.messages.error('Unknown username.')
        request.response.status_code = HTTPBadRequest.code
        return {}
    if not u.email:
        request.messages.error('No e-mail address associated with username.')
        request.response.status_code = HTTPBadRequest.code
        return {}

    token = PasswordResetToken(u)
    with transaction.manager:
        DBSession.add(token)

    mailer = get_mailer(request)
    body = render('mail/password_reset.mako', {
        'user': u,
        'requested_by': request.remote_addr,
        'url': request.route_url('account_reset', token=token.token)
    })
    message = Message(subject='CCVPN: Password reset request',
                      recipients=[u.email],
                      body=body)
    mailer.send(message)
    request.messages.info('We sent a reset link. Check your emails.')
    return {}
开发者ID:Logolo,项目名称:ccvpn,代码行数:32,代码来源:account.py

示例2: api_gateway_connect

def api_gateway_connect(request):
    try:
        fullname = request.POST['username']
        client_addr = request.POST['remote_addr']
    except KeyError:
        return HTTPBadRequest('Require username/remote_addr')

    if '/' in fullname:
        username, profilename = fullname.split('/', 1)
    else:
        username = fullname
        profilename = None

    user = DBSession.query(User).filter_by(username=username).first()
    if not user or not user.is_active or not user.is_paid:
        return HTTPForbidden('Invalid account')

    sess = VPNSession()
    sess.gateway_id = request.gw.id
    sess.gateway_version = request.gw_version
    sess.user_id = user.id
    sess.remote_addr = client_addr

    if profilename:
        profile = DBSession.query(Profile) \
                           .filter_by(name=profilename, uid=user.id).first()
        if not profile:
            return HTTPForbidden('Unknown profile')
        sess.profile_id = profile.id

    DBSession.add(sess)

    params = {}

    return HTTPOk(body=json.dumps(params))
开发者ID:theotix,项目名称:ccvpn,代码行数:35,代码来源:api.py

示例3: setup_database

def setup_database():
    """ Create an empty database and structure """
    DBSession.remove()
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    DBSession.configure(bind=engine)
    return DBSession
开发者ID:Graoumpf,项目名称:ccvpn,代码行数:7,代码来源:__init__.py

示例4: api_gateway_auth

def api_gateway_auth(request):
    try:
        fullname = request.POST['username']
        password = request.POST['password']
    except KeyError:
        return HTTPBadRequest('Require username/password')

    if '/' in fullname:
        username, profilename = fullname.split('/', 1)
    else:
        username = fullname
        profilename = None

    user = DBSession.query(User).filter_by(username=username).first()
    if not user or not user.check_password(password) or not user.is_active:
        return HTTPForbidden('Invalid username or password.')
    if not user.is_paid:
        return HTTPForbidden('Free account')

    if profilename:
        profile = DBSession.query(Profile) \
                           .filter_by(name=profilename, uid=user.id).first()
        if not profile:
            return HTTPForbidden('Unknown profile')
    return HTTPOk(empty_body=True)
开发者ID:theotix,项目名称:ccvpn,代码行数:25,代码来源:api.py

示例5: status

def status(request):
    settings = request.registry.settings
    domain = settings.get('net_domain', '')
    gateways = DBSession.query(Gateway) \
                        .filter_by(enabled=True) \
                        .order_by(Gateway.country, Gateway.name) \
                        .all()
    l = list(gateways)

    get_uptime = get_uptime_factory(settings)

    for host in l:
        host.host_name = '%s-%s.%s'%(host.country, host.name, domain)
        host.uptime = get_uptime(host.host_name)
        host.bps_formatted = format_bps(host.bps)

    bw_graph_url = settings.get('munin.bw_graph_url', None)
    bw_graph_img = settings.get('munin.bw_graph_img', None)
    bw_graph = (bw_graph_url, bw_graph_img)
    return {
        'gateways': l,
        'bw_graph': bw_graph if all(bw_graph) else None,
        'n_users': DBSession.query(func.count(User.id))
                            .filter_by(is_paid=True).scalar(),
        'n_countries': len(set(i.country for i in l)),
        'total_bw': format_bps(sum(i.bps for i in l)),
    }
开发者ID:Graoumpf,项目名称:ccvpn,代码行数:27,代码来源:__init__.py

示例6: initialize_db

def initialize_db():
    Base.metadata.create_all(DBSession.bind.engine)
    if not DBSession.query(User).filter_by(username='admin').count():
        with transaction.manager:
            admin = User(username='admin', is_admin=True)
            admin.set_password('admin')
            DBSession.add(admin)
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:7,代码来源:initializedb.py

示例7: orders

def orders(request):
    items_count = DBSession.query(func.count(Order.id)) \
                           .filter_by(uid=request.user.id) \
                           .filter(Order.close_date != None) \
                           .scalar()
    page_items = 100
    pages = int((items_count / page_items) + 0.5)
    try:
        page = int(request.GET['page'])
    except (KeyError, ValueError):
        page = 0
    offset = page * page_items
    orders = DBSession.query(Order).filter_by(uid=request.user.id) \

    now = datetime.datetime.now()

    orders = orders.filter(
        (Order.paid == True) |  # Order is paid
        ((Order.paid == False) & (Order.close_date > now)) |  # Or not expired
        ((Order.paid == False) & (Order.paid_amount > 0))  # Or not fully paid
    )

    orders = orders.order_by(Order.start_date.desc())
    orders = orders.limit(page_items).offset(offset).all()
    return {'orders': orders, 'page': page, 'pages': pages}
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:25,代码来源:account.py

示例8: order_post

def order_post(request):
    _ = request.translate
    code = request.POST.get('code')
    if code:
        return order_post_gc(request, code)

    times = (1, 3, 6, 12)
    try:
        method_name = request.POST.get('method')
        time_months = int(request.POST.get('time'))
    except (ValueError, TypeError):
        return HTTPSeeOther(location=request.route_url('account'))

    if method_name == 'admin' and request.user.is_admin:
        time = datetime.timedelta(days=30 * time_months)
        request.user.add_paid_time(time)
        return HTTPSeeOther(location=request.route_url('account'))

    method = request.payment_methods.get(method_name)
    if not method or time_months not in times:
        return HTTPBadRequest('Invalid method/time')

    time = datetime.timedelta(days=30 * time_months)

    o = method.init(request.user, time)
    DBSession.add(o)
    DBSession.flush()
    return method.start(request, o)
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:28,代码来源:order.py

示例9: main

def main(argv=sys.argv):
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawTextHelpFormatter)
    parser.add_argument('-v', '--verbose', action='count')
    parser.add_argument('-S', '--send', action='store_true', default=False)
    parser.add_argument('--active', action='store_true', default=True)
    parser.add_argument('-s', '--subject', action='store')
    parser.add_argument('config')
    parser.add_argument('textfile')

    args = parser.parse_args()

    log_level = logging.WARNING
    if args.verbose is not None:
        verbose = int(args.verbose)
        if verbose == 1:
            log_level = logging.INFO
        elif verbose >= 2:
            log_level = logging.DEBUG
    logging.basicConfig(level=log_level)

    config_uri = args.config
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    mailer = mailer_factory_from_settings(settings)

    if not args.subject:
        print('Require a subject.')
        exit(1)

    message_in = open(args.textfile, 'r').read()
    if not message_in:
        print('Require a message.')
        exit(1)

    q = DBSession.query(User)
    q = q.filter(User.email != '')
    q = q.filter(User.email is not None)
    if args.active:
        q = q.filter_by(is_paid=True)
    users = list(q.all())

    print('Sending to: %d users.' % (len(users)))
    if args.verbose:
        for u in users:
            print('- %s [%s]' % (u.email, u.username))

    for u in users:
        if not args.send:
            print('Not sending message to %s.' % u.email)
            continue
        message = Message(subject=args.subject,
                          recipients=[u.email],
                          body=message_in)
        mailer.send_immediately(message)
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:58,代码来源:mail.py

示例10: main

def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    checkbtcorders(settings)
开发者ID:Logolo,项目名称:ccvpn,代码行数:9,代码来源:checkbtcorders.py

示例11: order_callback

def order_callback(request):
    id = int(request.matchdict['hexid'], 16)
    o = DBSession.query(Order).filter_by(id=id).first()
    if not o:
        return HTTPNotFound()
    method = methods.METHOD_IDS[o.method]
    ret = method().callback(request, o)
    DBSession.flush()
    return ret
开发者ID:Logolo,项目名称:ccvpn,代码行数:9,代码来源:account.py

示例12: profiles_edit_post

def profiles_edit_post(request):
    _ = request.translate
    try:
        profile_id = int(request.matchdict['id'])
        profile = DBSession.query(Profile).filter_by(id=profile_id) \
                           .filter_by(uid=request.user.id).one()
    except (KeyError, ValueError, NoResultFound):
        return HTTPSeeOther(location=request.route_url('account'))

    redirect = HTTPSeeOther(location=request.route_url('account_profiles_edit',
                                                       id=profile.id))

    try:
        name = request.POST.get('name', '')
        client_os = request.POST['client_os']
        gateway = request.POST['gateway']
        protocol = request.POST['protocol']
        disable_ipv6 = 'enable_ipv6' not in request.POST
        http_proxy = request.POST.get('use_http_proxy', '')
    except (KeyError, ValueError):
        return redirect

    if protocol not in Profile.PROTOCOLS:
        return redirect

    if profile.name and name and name != profile.name:
        if not profile.validate_name(name):
            request.messages.error(_('Invalid name.'))
            return redirect

        # Check if the name is already used
        used = DBSession.query(Profile).filter_by(uid=request.user.id) \
                        .filter_by(name=name).first()
        if used:
            request.messages.error(_('Name already used.'))
            return redirect

        profile.name = name

    profile.client_os = client_os
    profile.protocol = protocol
    profile.disable_ipv6 = disable_ipv6
    profile.use_http_proxy = http_proxy

    if gateway.startswith('rr_') and len(gateway) == 5:
        # rr_<cc>  # random in country
        cc = gateway[3:]
        profile.gateway_country = cc
        profile.gateway_id = None
    else:
        # random
        profile.gateway_country = None
        profile.gateway_id = None

    request.messages.info(_('Saved!'))
    return HTTPSeeOther(location=request.route_url('account'))
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:56,代码来源:account.py

示例13: setUp

    def setUp(self):
        self.config = testing.setUp()
        self.session = setup_database()
        with transaction.manager:
            self.u = User(username='freeuser', password='a')
            DBSession.add(self.u)

            self.pu = User(username='paiduser', password='a')
            self.pu.add_paid_time(datetime.timedelta(days=30))
            DBSession.add(self.pu)
开发者ID:Logolo,项目名称:ccvpn,代码行数:10,代码来源:models.py

示例14: setUp

    def setUp(self):
        super().setUp()

        self.u = User(username='freeuser', password='a')
        DBSession.add(self.u)
        self.session.flush()

        self.pu = User(username='paiduser', password='a')
        self.pu.add_paid_time(datetime.timedelta(days=30))
        DBSession.add(self.pu)
        self.session.flush()
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:11,代码来源:models.py

示例15: order_callback

def order_callback(request):
    _ = request.translate
    id = int(request.matchdict['hexid'], 16)
    o = DBSession.query(Order).filter_by(id=id).first()
    if not o:
        return HTTPNotFound()

    method = request.payment_methods.get(o.method)
    r = method.callback(request, o)
    DBSession.flush()
    return r
开发者ID:CCrypto,项目名称:ccvpn2,代码行数:11,代码来源:order.py


注:本文中的ccvpn.models.DBSession类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。