本文整理汇总了Python中ccvpn.models.DBSession.query方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.query方法的具体用法?Python DBSession.query怎么用?Python DBSession.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ccvpn.models.DBSession
的用法示例。
在下文中一共展示了DBSession.query方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: status
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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)),
}
示例2: orders
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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}
示例3: api_gateway_auth
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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)
示例4: api_gateway_connect
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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))
示例5: profiles_edit_post
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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'))
示例6: account_post
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def account_post(request):
_ = request.translate
redirect = HTTPSeeOther(location=request.route_url('account'))
profiles_limit = 10
profile_name = request.POST.get('profilename')
profile_delete = request.POST.get('delete')
if profile_name:
p = Profile()
if not p.validate_name(profile_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=profile_name).first()
if used:
request.messages.error(_('Name already used.'))
return redirect
# Check if this user's under the profile number limit
profiles_count = DBSession.query(func.count(Profile.id)) \
.filter_by(uid=request.user.id).scalar()
if profiles_count > profiles_limit:
request.messages.error(_('You have too many profiles.'))
return redirect
p.name = profile_name
p.uid = request.user.id
DBSession.add(p)
DBSession.flush()
return HTTPSeeOther(location=request.route_url('account_profiles_edit', id=p.id))
if profile_delete:
try:
profile_delete = int(profile_delete)
except ValueError:
return redirect
p = DBSession.query(Profile) \
.filter_by(id=int(profile_delete)) \
.filter(Profile.name != '') \
.filter_by(uid=request.user.id) \
.first()
if not p:
request.messages.error(_('Unknown profile.'))
return redirect
DBSession.delete(p)
return redirect
示例7: profiles_edit
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def profiles_edit(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'))
return {
'profile': profile,
'edit_post_url': request.route_url('account_profiles_edit', id=profile.id),
'gw_countries': set(i[0] for i in DBSession.query(Gateway.country).all()),
}
示例8: logs
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def logs(request):
items_count = DBSession.query(func.count(VPNSession.id)) \
.filter_by(user_id=request.user.id) \
.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
logs = DBSession.query(VPNSession).filter_by(user_id=request.user.id) \
.order_by(VPNSession.connect_date.desc()) \
.limit(page_items).offset(offset)
return {'logs': logs, 'page': page, 'pages': pages}
示例9: initialize_db
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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)
示例10: get_future_expire
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def get_future_expire(days=3):
"""This function get user accounts that will expire in a few days.
"""
limit_date = datetime.now() + timedelta(days=days)
q = DBSession.query(User) \
.filter(User.email != '') \
.filter(User.email != None)
# Expire now < expiration < N days
q = q.filter(User.paid_until > datetime.now())
q = q.filter(User.paid_until < limit_date)
# Only send notice if the last one was before the first time we could have
# sent a notice
# [last notice] < [expiration - 3days] < [this notice] < [expiration]
if DBSession.bind.dialect.name == 'sqlite':
a1 = func.julianday(User.paid_until)
a2 = func.julianday(User.last_expiry_notice)
cond = a1 - a2 > days
else:
cond = User.paid_until - User.last_expiry_notice > timedelta(days=days)
q = q.filter(or_(User.last_expiry_notice == None, cond))
users = list(q.all())
log.debug('found %d accounts that expire in less than %d days',
len(users), days)
return users
示例11: forgot
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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 {}
示例12: order_view
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def order_view(request):
id = int(request.matchdict['hexid'], 16)
o = DBSession.query(Order).filter_by(id=id).first()
if not o:
return HTTPNotFound()
if not request.user.is_admin and request.user.id != o.uid:
return HTTPUnauthorized()
return {'o': o}
示例13: get_item
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def get_item(self, id):
item_id = self.request.GET['id']
item = DBSession.query(self.model).filter_by(id=item_id).first()
template = 'admin/item.mako'
if item is None:
raise HTTPNotFound()
return render_to_response(self.item_template or template,
self.tvars(dict(item=item)))
示例14: _get_uid
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
def _get_uid(self, input):
if input.startswith('#'):
return input[1:]
user = DBSession.query(User).filter_by(username=input).first()
if not user:
# TODO: handle that correctly
raise HTTPBadRequest()
return user.id
示例15: main
# 需要导入模块: from ccvpn.models import DBSession [as 别名]
# 或者: from ccvpn.models.DBSession import query [as 别名]
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)