本文整理汇总了Python中tools.db_utils.db函数的典型用法代码示例。如果您正苦于以下问题:Python db函数的具体用法?Python db怎么用?Python db使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了db函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:kakabomba,项目名称:profireader,代码行数:7,代码来源:views_file.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:31,代码来源:translate.py
示例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}))
开发者ID:kakabomba,项目名称:profireader,代码行数:7,代码来源:company.py
示例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)}
开发者ID:kakabomba,项目名称:profireader,代码行数:25,代码来源:views_portal.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:33,代码来源:pr_base.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:31,代码来源:translate.py
示例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}
开发者ID:kakabomba,项目名称:profireader,代码行数:9,代码来源:views_company.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:9,代码来源:materials.py
示例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))
开发者ID:kakabomba,项目名称:profireader,代码行数:10,代码来源:views_index.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:10,代码来源:portal.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:55,代码来源:portal.py
示例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()
开发者ID:kakabomba,项目名称:profireader,代码行数:12,代码来源:portal.py
示例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})
开发者ID:kakabomba,项目名称:profireader,代码行数:12,代码来源:company.py
示例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
开发者ID:kakabomba,项目名称:profireader,代码行数:14,代码来源:portal.py
示例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])
开发者ID:kakabomba,项目名称:profireader,代码行数:14,代码来源:portal.py
示例16: search_filter_default
def search_filter_default(self, division_id, company_id=None):
""" :param division_id: string with id from table portal_division,
optional company_id: string with id from table company. If provided
, this function will check if ArticleCompany has relation with our class.
:return: dict with prepared filter parameters for search method """
division = db(PortalDivision, id=division_id).one()
division_type = division.portal_division_type.id
visibility = Publication.visibility.in_(Publication.articles_visibility_for_user(
portal_id=division.portal_id)[0])
filter = None
if division_type == 'index':
filter = {'class': Publication,
'filter': and_(Publication.portal_division_id.in_(db(
PortalDivision.id, portal_id=division.portal_id).filter(
PortalDivision.portal_division_type_id != 'events'
)), Publication.status == Publication.STATUSES['PUBLISHED'], visibility),
'return_fields': 'default_dict', 'tags': True}
elif division_type == 'news':
if not company_id:
filter = {'class': Publication,
'filter': and_(Publication.portal_division_id == division_id,
Publication.status ==
Publication.STATUSES['PUBLISHED'], visibility),
'return_fields': 'default_dict', 'tags': True}
else:
filter = {'class': Publication,
'filter': and_(Publication.portal_division_id == division_id,
Publication.status ==
Publication.STATUSES['PUBLISHED'],
db(ArticleCompany, company_id=company_id,
id=Publication.article_company_id).exists(), visibility),
'return_fields': 'default_dict', 'tags': True}
elif division_type == 'events':
if not company_id:
filter = {'class': Publication,
'filter': and_(Publication.portal_division_id == division_id,
Publication.status ==
Publication.STATUSES['PUBLISHED'], visibility),
'return_fields': 'default_dict', 'tags': True}
else:
filter = {'class': Publication,
'filter': and_(Publication.portal_division_id == division_id,
Publication.status ==
Publication.STATUSES['PUBLISHED'],
db(ArticleCompany, company_id=company_id,
id=Publication.article_company_id).exists(), visibility),
'return_fields': 'default_dict', 'tags': True}
return filter
开发者ID:kakabomba,项目名称:profireader,代码行数:48,代码来源:materials.py
示例17: get_portals_where_company_send_article
def get_portals_where_company_send_article(company_id):
portals = {}
for m in db(Material, company_id=company_id).all():
for pub in m.publications:
portals[pub.portal_division.portal.id] = pub.portal_division.portal.name
return portals
开发者ID:kakabomba,项目名称:profireader,代码行数:7,代码来源:materials.py
示例18: edit_profile_submit
def edit_profile_submit(json, reader_portal_id):
divisions_and_comments = db(UserPortalReader, id=reader_portal_id).one().show_divisions_and_comments
for item in json['divisions']:
for show_division_and_comments in divisions_and_comments:
if item['division_id'] == show_division_and_comments.division_id:
show_division_and_comments.show_divisions_and_comments = item['show_divisions_and_comments']
return json
开发者ID:kakabomba,项目名称:profireader,代码行数:7,代码来源:views_index.py
示例19: subquery_portal_articles
def subquery_portal_articles(portal_id, filters, sorts):
sub_query = db(Publication)
list_filters = []
list_sorts = []
if 'publication_status' in filters:
list_filters.append(
{'type': 'select', 'value': filters['publication_status'], 'field': Publication.status})
if 'company' in filters:
sub_query = sub_query.join(Publication.company)
list_filters.append({'type': 'select', 'value': filters['company'], 'field': Company.id})
if 'date' in filters:
list_filters.append(
{'type': 'date_range', 'value': filters['date'], 'field': Publication.publishing_tm})
sub_query = sub_query. \
join(Publication.portal_division). \
join(PortalDivision.portal). \
filter(Portal.id == portal_id)
if 'title' in filters:
list_filters.append({'type': 'text', 'value': filters['title'], 'field': Publication.title})
if 'date' in sorts:
list_sorts.append({'type': 'date', 'value': sorts['date'], 'field': Publication.publishing_tm})
else:
list_sorts.append({'type': 'date', 'value': 'desc', 'field': Publication.publishing_tm})
sub_query = Grid.subquery_grid(sub_query, list_filters, list_sorts)
return sub_query
开发者ID:kakabomba,项目名称:profireader,代码行数:25,代码来源:materials.py
示例20: wrapper
def wrapper(*args, **kwargs):
if g.debug or g.testing:
if not func.__dict__.get('__check_rights__'):
print('Please add "check_right" decorator for your func!')
start = time.clock()
try:
ret = func(*args, **kwargs)
except:
import sys
print("Unexpected error:", sys.exc_info()[0])
return "Unexpected error:", sys.exc_info()[0]
# return redirect(url_for('index.index'))
end = time.clock()
profiler = db(Profiler, name=func.__name__, blueprint_name=func.__dict__['__endpoint__']).first()
method = ','.join([method for method in func.__dict__['__method__']]) if func.__dict__['__method__'] else None
if profiler:
profiler.update_profile(end-start, method)
else:
Profiler().create_profile(func.__name__, func.__dict__['__endpoint__'], end-start, method)
return ret
else:
if not func.__dict__['__check_rights__']:
raise Exception('method not allowed! Please add "check_right" decorator for your func!')
try:
ret = func(*args, **kwargs)
except:
import sys
print("Unexpected error:", sys.exc_info()[0])
return "Unexpected error:", sys.exc_info()[0]
return ret
开发者ID:kakabomba,项目名称:profireader,代码行数:31,代码来源:request_wrapers.py
注:本文中的tools.db_utils.db函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论