本文整理汇总了Python中tools.db_utils.db函数的典型用法代码示例。如果您正苦于以下问题:Python db函数的具体用法?Python db怎么用?Python db使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了db函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: crop_image
def crop_image(image_id, coordinates, zoom, params):
from ..models.company import Company
image_query = db(File, id=image_id).one() # get file object
company_owner = db(Company).filter(or_(
Company.system_folder_file_id == image_query.root_folder_id,
Company.journalist_folder_file_id == image_query.root_folder_id)).one() # get company file owner
return File.crop(image_query, coordinates, zoom, company_owner, params)
示例2: try_to_get_phrase
def try_to_get_phrase(template, phrase, url, portal_id=None, allow_html=''):
a_filter = dict(template=template, name=phrase, portal_id=portal_id)
# TODO: OZ by OZ: this functions exists because we sometemes inmsert recort in flashing process (see on_value_changed decorator)
# and we can`t use ORM
def insert_record(**values):
from profapp import utils
g.db().execute(('INSERT INTO "%s" (template, name, portal_id, allow_html, url, %s) '
'VALUES (:template, :name, :portal_id, :allow_html, :url, :%s)') %
(TranslateTemplate.__tablename__, ', '.join(TranslateTemplate.languages),
", :".join(TranslateTemplate.languages)),
params=utils.dict_merge(a_filter, {'allow_html': allow_html, 'url': url},
{l: phrase for l in TranslateTemplate.languages}, values))
return db(TranslateTemplate, **a_filter).first()
exist = db(TranslateTemplate, **a_filter).first()
if portal_id and not exist:
exist_for_another = db(TranslateTemplate, template=template, name=phrase,
portal_id=TranslateTemplate.exemplary_portal_id).first()
# TODO: OZ by OZ: how to select template portal? now we grab phrases from most recent portal, and there can be some unappropriate values
if not exist_for_another:
exist_for_another = db(TranslateTemplate, template=template, name=phrase).filter(
TranslateTemplate.portal != None).order_by(expression.asc(TranslateTemplate.cr_tm)).first()
if exist_for_another:
return insert_record(**{l: getattr(exist_for_another, l) for l in TranslateTemplate.languages})
if not exist:
return insert_record()
return exist
示例3: get_allowed_statuses
def get_allowed_statuses(company_id=None, portal_id=None):
if company_id:
sub_query = db(MemberCompanyPortal, company_id=company_id).filter(
MemberCompanyPortal.status != "DELETED").all()
else:
sub_query = db(MemberCompanyPortal, portal_id=portal_id)
return sorted(list({partner.status for partner in sub_query}))
示例4: portal_banners_load
def portal_banners_load(json, company_id):
portal = Company.get(company_id).own_portal
if 'action_name' in json:
if json['action_name'] == 'create':
place = db(PortalAdvertismentPlace, portal_layout_id=portal.portal_layout_id,
place=json['row']['place']).one()
newrow = PortalAdvertisment(portal_id=portal.id, html=place.default_value if place.default_value else '',
place=json['row']['place']).save()
return {'grid_action': 'refresh_row', 'row': newrow.get_client_side_dict()}
elif json['action_name'] == 'delete':
PortalAdvertisment.get(json['id']).delete()
return {'grid_action': 'delete_row'}
elif json['action_name'] == 'set_default':
adv = PortalAdvertisment.get(json['id'])
place = db(PortalAdvertismentPlace, portal_layout_id=portal.portal_layout_id, place=adv.place).one()
adv.html = place.default_value
adv.save()
return {}
else:
banners = PortalAdvertisment.get_portal_advertisments(portal)
return {'page': 1,
'grid_data': banners,
'grid_filters': {},
'total': len(banners)}
示例5: __search_start
def __search_start(self, *args: dict, **kwargs):
""" Don't use this method, use Search().search() method """
subquery_search = self.__get_subquery(*args, ord_by=kwargs.get('order_by'))
if self.__pagination:
from ..controllers.pagination import pagination as pagination_func
subquery_search, self.__pages, page, _ = pagination_func(subquery_search, page=self.__page,
items_per_page=self.__items_per_page)
subquery_search = subquery_search.subquery()
join_search = []
for arg in args:
join_params = arg.get('join') or arg['class']
join_search.append(db(subquery_search).join(join_params,
arg['class'].id == subquery_search.c.index).subquery())
objects = collections.OrderedDict()
to_order = {}
_order_by = kwargs.get('order_by') or Search.ORDER_MD_TM
ord_by = 'text' if type(_order_by) in (str, list, tuple) \
else self.__order_by_to_str[_order_by]
for search in join_search:
for cls in db(search).all():
objects[cls.index] = {'id': cls.index, 'table_name': cls.table_name,
'order': getattr(cls, ord_by), 'md_tm': cls.md_tm}
to_order[cls.index] = (getattr(cls, ord_by), getattr(cls, 'md_tm'))
objects = {obj['id']: obj for obj in
collections.OrderedDict(sorted(objects.items())).values()}
ordered = sorted(tuple(to_order.items()), reverse=False if self.__desc_asc == 'asc' else True,
key=operator.itemgetter(1))
self.__reload_func(len(ordered), *args)
if self.__return_objects:
objects = self.__get_objects_from_db(*args, ordered_objects_list=ordered)
else:
objects = collections.OrderedDict((id, objects[id]) for id, ord in ordered)
return objects, self.__pages, self.__page
示例6: subquery_search
def subquery_search(filters=None, sorts=None, edit=None):
sub_query = db(TranslateTemplate)
list_filters = []
list_sorts = []
if edit:
exist = db(TranslateTemplate, template=edit['template'], name=edit['name']).first()
i = datetime.datetime.now()
TranslateTemplate.get(exist.id).attr(
{edit['col']: edit['newValue'], 'md_tm': i}).save().get_client_side_dict()
if 'url' in filters:
list_filters.append({'type': 'select', 'value': filters['url'], 'field': TranslateTemplate.url})
if 'template' in filters:
list_filters.append({'type': 'select', 'value': filters['template'], 'field': TranslateTemplate.template})
if 'name' in filters:
list_filters.append({'type': 'text', 'value': filters['name'], 'field': TranslateTemplate.name})
if 'uk' in filters:
list_filters.append({'type': 'text', 'value': filters['uk'], 'field': TranslateTemplate.uk})
if 'en' in filters:
list_filters.append({'type': 'text', 'value': filters['en'], 'field': TranslateTemplate.en})
if 'portal.name' in filters:
sub_query = sub_query.join(Portal,
Portal.id == TranslateTemplate.portal_id)
list_filters.append({'type': 'text', 'value': filters['portal.name'], 'field': Portal.name})
if 'cr_tm' in sorts:
list_sorts.append({'type': 'date', 'value': sorts['cr_tm'], 'field': TranslateTemplate.cr_tm})
elif 'ac_tm' in sorts:
list_sorts.append({'type': 'date', 'value': sorts['ac_tm'], 'field': TranslateTemplate.ac_tm})
else:
list_sorts.append({'type': 'date', 'value': 'desc', 'field': TranslateTemplate.cr_tm})
sub_query = Grid.subquery_grid(sub_query, list_filters, list_sorts)
return sub_query
示例7: search_for_company_to_join
def search_for_company_to_join(json):
companies, there_is_more = load_for_infinite_scroll(
db(Company).filter(~db(UserCompany, user_id=g.user.id, company_id=Company.id).exists()). \
filter(and_(
Company.status == 'ACTIVE', Company.name.ilike("%" + json['text'] + "%")), ~Company.id.in_(json['loaded'])). \
order_by(Company.name), items=3)
return {'companies': [company.get_client_side_dict() for company in companies],
'there_is_more': there_is_more}
示例8: articles_visibility_for_user
def articles_visibility_for_user(portal_id):
employer = True
visibilities = Publication.VISIBILITIES.copy()
if not db(UserCompany, user_id=getattr(g.user, 'id', None),
status=UserCompany.STATUSES['ACTIVE']).filter(
UserCompany.company_id == db(Portal.company_owner_id, id=portal_id)).count():
visibilities.pop(Publication.VISIBILITIES['CONFIDENTIAL'])
employer = False
return visibilities.keys(), employer
示例9: list_reader_from_front
def list_reader_from_front(portal_id):
portal = Portal.get(portal_id)
if g.user:
portals = db(Portal).filter((Portal.id.in_(db(UserPortalReader.portal_id, user_id=g.user.id)))).all()
if portal in portals:
return redirect(url_for('index.list_reader'))
else:
return redirect(url_for('index.reader_subscribe', portal_id=portal_id))
else:
return redirect(url_for('index.auth_before_subscribe_to_portal', portal_id=portal_id))
示例10: search_for_portal_to_join
def search_for_portal_to_join(company_id, searchtext):
"""This method return all portals which are not partners current company"""
portals = []
for portal in db(Portal).filter(Portal.name.ilike("%" + searchtext + "%")).all():
member = db(MemberCompanyPortal, company_id=company_id, portal_id=portal.id).first()
if member and member.status in Portal.ALLOWED_STATUSES_TO_JOIN:
portals.append(portal.get_client_side_dict())
elif not member:
portals.append(portal.get_client_side_dict())
return portals
示例11: validate
def validate(self, is_new):
ret = super().validate(is_new, regexps={
'name': '[^\s]{2,}',
'host': '^(([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])\.)+([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]{1,})$'})
errors = ret['errors']
warnings = ret['warnings']
if db(Portal, company_owner_id=self.own_company.id).filter(Portal.id != self.id).count():
errors['form'] = 'portal for company already exists'
if db(Portal, host=self.host).filter(Portal.id != self.id).count():
errors['host'] = 'host already taken by another portal'
import socket
try:
host = socket.gethostbyname(self.host)
host_ip = str(host)
if not 'host' in errors and 'host' in warnings and not host_ip in Config.OUR_IPS:
warnings['host'] = 'Wrong Ip-address'
except Exception as e:
warnings['host'] = 'cannot resolve hostname. maybe unregistered'
grouped_by_division_type = {}
grouped_by_company_member = {}
for inddiv, div in enumerate(self.divisions):
if not re.match('[^\s]{3,}', div.name):
utils.dict_deep_replace('pls enter valid name', errors, 'divisions', div.id, 'name')
# number of division of some type
utils.dict_deep_inc(grouped_by_division_type, div.portal_division_type.id)
if div.portal_division_type.id == PortalDivision.TYPES['company_subportal']:
utils.dict_deep_inc(grouped_by_company_member, div.settings['company_id'])
for check_division_type in db(PortalDivisionType).all():
utils.dict_deep_replace(0, grouped_by_division_type, check_division_type.id, if_not_exists=True)
if check_division_type.min > grouped_by_division_type[check_division_type.id]:
errors['add_division'] = 'you need at least %s `%s`' % (check_division_type.min, check_division_type.id)
if check_division_type.max < grouped_by_division_type[check_division_type.id]:
for inddiv, div in enumerate(self.divisions):
if div.portal_division_type.id == check_division_type.id:
utils.dict_deep_replace(
'you can have only %s `%s`' % (check_division_type.max, check_division_type.id),
errors, 'divisions', div.id, 'type')
for inddiv, div in enumerate(self.divisions):
if div.portal_division_type.id == PortalDivision.TYPES['company_subportal']:
if grouped_by_company_member.get(div.settings['company_id'], 0) > 1:
utils.dict_deep_replace('you have more that one subportal for this company',
warnings, 'divisions', div.id, 'settings')
return ret
示例12: apply_company_to_portal
def apply_company_to_portal(company_id, portal_id):
from ..models.company import Company
"""Add company to MemberCompanyPortal table. Company will be partner of this portal"""
member = db(MemberCompanyPortal).filter_by(portal_id=portal_id, company_id=company_id).first()
if member:
member.set_client_side_dict(MemberCompanyPortal.STATUSES['APPLICANT'])
member.save()
else:
g.db.add(MemberCompanyPortal(company=Company.get(company_id),
portal=db(Portal, id=portal_id).one(),
plan=db(MemberCompanyPortalPlan).first()))
g.db.flush()
示例13: apply_request
def apply_request(company_id, user_id, bool):
"""Method which define when employer apply or reject request from some user to
subscribe to this company. If bool == True(Apply) - update rights to basic rights in company
and status to active, If bool == False(Reject) - just update status to rejected."""
if bool == 'True':
stat = UserCompany.STATUSES['ACTIVE']
UserCompany.update_rights(user_id, company_id, UserCompany.RIGHTS_AT_COMPANY_DEFAULT)
else:
stat = UserCompany.STATUSES['REJECTED']
db(UserCompany, company_id=company_id, user_id=user_id,
status=UserCompany.STATUSES['APPLICANT']).update({'status': stat})
示例14: get_filter_for_portals_and_plans
def get_filter_for_portals_and_plans(portal_name=None, start_end_tm=None, package_name=None):
filter_params = []
if portal_name:
filter_params.append(UserPortalReader.portal_id.in_(db(Portal.id).filter(
Portal.name.ilike('%' + portal_name + '%'))))
if start_end_tm:
from_tm = datetime.datetime.utcfromtimestamp(int(start_end_tm['from'] + 1) / 1000)
to_tm = datetime.datetime.utcfromtimestamp(int(start_end_tm['to'] + 86399999) / 1000)
filter_params.extend([UserPortalReader.start_tm >= from_tm,
UserPortalReader.start_tm <= to_tm])
if package_name:
filter_params.append(UserPortalReader.portal_plan_id == db(ReaderUserPortalPlan.id).filter(
ReaderUserPortalPlan.name.ilike('%' + package_name + '%')))
return filter_params
示例15: get_portals_and_plan_info_for_user
def get_portals_and_plan_info_for_user(user_id, page, items_per_page, filter_params):
from ..controllers.pagination import pagination
query, pages, page, count = pagination(db(UserPortalReader, user_id=user_id).filter(filter_params),
page=int(page), items_per_page=int(items_per_page))
for upr in query:
yield dict(id=upr.id, portal_id=upr.portal_id, status=upr.status, start_tm=upr.start_tm,
portal_logo=upr.portal.logo['url'],
end_tm=upr.end_tm if upr.end_tm > datetime.datetime.utcnow() else 'Expired at ' + upr.end_tm,
plan_id=upr.portal_plan_id,
plan_name=db(ReaderUserPortalPlan.name, id=upr.portal_plan_id).one()[0],
portal_name=upr.portal.name, portal_host=upr.portal.host, amount=upr.amount,
portal_divisions=[{division.name: division.id}
for division in upr.portal.divisions])