本文整理汇总了Python中c2corg_api.models.DBSession类的典型用法代码示例。如果您正苦于以下问题:Python DBSession类的具体用法?Python DBSession怎么用?Python DBSession使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBSession类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _collection_post
def _collection_post(
self, schema, before_add=None, after_add=None):
user_id = self.request.authenticated_userid
document_in = self.request.validated
document = schema.objectify(document_in)
document.document_id = None
if before_add:
before_add(document, user_id=user_id)
DBSession.add(document)
DBSession.flush()
DocumentRest.create_new_version(document, user_id)
if document.type != AREA_TYPE:
update_areas_for_document(document, reset=False)
if after_add:
after_add(document, user_id=user_id)
if document_in.get('associations', None):
create_associations(document, document_in['associations'], user_id)
notify_es_syncer(self.request.registry.queue_config)
return {'document_id': document.document_id}
示例2: _get_history
def _get_history(self, document_id, lang):
# FIXME conditional permission check (when outings implemented)
# is_outing = DBSession.query(Outing) \
# .filter(Outing.document_id == document_id).count()
# if is_outing > 0:
# # validate permission (authenticated + associated)
# # return 403 if not correct
title = DBSession.query(DocumentLocale.title) \
.filter(DocumentLocale.document_id == document_id) \
.filter(DocumentLocale.lang == lang) \
.first()
if not title:
raise HTTPNotFound('no locale document for "{0}"'.format(lang))
versions = DBSession.query(DocumentVersion) \
.options(joinedload('history_metadata').joinedload('user')) \
.filter(DocumentVersion.document_id == document_id) \
.filter(DocumentVersion.lang == lang) \
.order_by(DocumentVersion.id) \
.all()
return {
'title': title.title,
'versions': [serialize_version(v) for v in versions]
}
示例3: get
def get(self):
id = self.request.validated['id']
lang = self.request.validated['lang']
# FIXME conditional permission check (when outings implemented)
# is_outing = DBSession.query(Outing) \
# .filter(Outing.document_id == id).count()
# if is_outing > 0:
# # validate permission (authenticated + associated)
# # return 403 if not correct
title = DBSession.query(DocumentLocale.title) \
.filter(DocumentLocale.document_id == id) \
.filter(DocumentLocale.culture == lang) \
.first()
if not title:
raise HTTPNotFound('no locale document for ' + lang)
versions = DBSession.query(DocumentVersion) \
.options(joinedload('history_metadata').joinedload('user')) \
.filter(DocumentVersion.document_id == id) \
.filter(DocumentVersion.culture == lang) \
.order_by(DocumentVersion.id) \
.all()
return {
'title': title.title,
'versions': [self._serialize_version(v) for v in versions]
}
示例4: collection_post
def collection_post(self):
association = schema_association.objectify(self.request.validated)
association.parent_document_type = \
self.request.validated['parent_document_type']
association.child_document_type = \
self.request.validated['child_document_type']
if exists_already(association):
raise HTTPBadRequest(
'association (or its back-link) exists already')
DBSession.add(association)
DBSession.add(
association.get_log(self.request.authenticated_userid))
update_cache_version_associations(
[{'parent_id': association.parent_document_id,
'parent_type': association.parent_document_type,
'child_id': association.child_document_id,
'child_type': association.child_document_type}], [])
notify_es_syncer_if_needed(association, self.request)
update_feed_association_update(
association.parent_document_id, association.parent_document_type,
association.child_document_id, association.child_document_type,
self.request.authenticated_userid)
return {}
示例5: setUp
def setUp(self): # noqa
self.app = TestApp(self.app)
registry = self.app.app.registry
self.mailer = get_mailer(registry)
self.email_service = EmailService(self.mailer, settings)
EmailService.instance = None
self.config = testing.setUp()
self.connection = self.engine.connect()
# begin a non-ORM transaction
self.trans = self.connection.begin()
# DBSession is the scoped session manager used in the views,
# reconfigure it to use this test's connection
DBSession.configure(bind=self.connection)
# create a session bound to the connection, this session is the one
# used in the test code
self.session = self.Session(bind=self.connection)
self.queue_config = registry.queue_config
reset_queue(self.queue_config)
reset_cache_key()
示例6: get_creators
def get_creators(document_ids):
""" Get the creator for the list of given document ids.
"""
t = DBSession.query(
ArchiveDocument.document_id.label('document_id'),
User.id.label('user_id'),
User.name.label('name'),
over(
func.rank(), partition_by=ArchiveDocument.document_id,
order_by=HistoryMetaData.id).label('rank')). \
select_from(ArchiveDocument). \
join(
DocumentVersion,
and_(
ArchiveDocument.document_id == DocumentVersion.document_id,
ArchiveDocument.version == 1)). \
join(HistoryMetaData,
DocumentVersion.history_metadata_id == HistoryMetaData.id). \
join(User,
HistoryMetaData.user_id == User.id). \
filter(ArchiveDocument.document_id.in_(document_ids)). \
subquery('t')
query = DBSession.query(
t.c.document_id, t.c.user_id, t.c.name). \
filter(t.c.rank == 1)
return {
document_id: {
'name': name,
'user_id': user_id
} for document_id, user_id, name in query
}
示例7: remove_token
def remove_token(token):
now = datetime.datetime.utcnow()
condition = Token.value == token and Token.expire > now
result = DBSession.execute(Token.__table__.delete().where(condition))
if result.rowcount == 0:
log.debug("Failed to remove token %s" % token)
DBSession.flush()
示例8: validate_association
def validate_association(request):
"""Check if the given documents exist and if an association between the
two document types is valid.
"""
parent_document_id = request.validated.get('parent_document_id')
child_document_id = request.validated.get('child_document_id')
parent_document_type = None
if parent_document_id:
parent_document_type = DBSession.query(Document.type). \
filter(Document.document_id == parent_document_id).scalar()
if not parent_document_type:
request.errors.add(
'body', 'parent_document_id', 'parent document does not exist')
child_document_type = None
if child_document_id:
child_document_type = DBSession.query(Document.type). \
filter(Document.document_id == child_document_id).scalar()
if not child_document_type:
request.errors.add(
'body', 'child_document_id', 'child document does not exist')
if parent_document_type and child_document_type:
association_type = (parent_document_type, child_document_type)
if association_type not in valid_associations:
request.errors.add(
'body', 'association', 'invalid association type')
示例9: main
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
# Configure SQLAlchemy
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
# Configure ElasticSearch
configure_es_from_config(settings)
config = Configurator(settings=settings)
config.include('cornice')
config.registry.queue_config = get_queue_config(settings)
bypass_auth = False
if 'noauthorization' in settings:
bypass_auth = asbool(settings['noauthorization'])
if not bypass_auth:
config.include("pyramid_jwtauth")
# Intercept request handling to validate token against the database
config.add_tween('c2corg_api.jwt_database_validation_tween_factory')
# Inject ACLs
config.set_root_factory(RootFactory)
else:
log.warning('Bypassing authorization')
# Scan MUST be the last call otherwise ACLs will not be set
# and the permissions would be bypassed
config.scan(ignore='c2corg_api.tests')
return config.make_wsgi_app()
示例10: collection_delete
def collection_delete(self):
association_in = schema_association.objectify(self.request.validated)
association = self._load(association_in)
if association is None:
# also accept {parent_document_id: y, child_document_id: x} when
# for an association {parent_document_id: x, child_document_id: x}
association_in = Association(
parent_document_id=association_in.child_document_id,
child_document_id=association_in.parent_document_id)
association = self._load(association_in)
if association is None:
raise HTTPBadRequest('association does not exist')
if is_main_waypoint_association(association):
raise HTTPBadRequest(
'as the main waypoint of the route, this waypoint can not '
'be disassociated')
log = association.get_log(
self.request.authenticated_userid, is_creation=False)
DBSession.delete(association)
DBSession.add(log)
return {}
示例11: post
def post(self):
request = self.request
user = request.validated['user']
user.password = request.validated['password']
# The user was validated by the nonce so we can log in
token = log_validated_user_i_know_what_i_do(user, request)
if token:
settings = request.registry.settings
response = token_to_response(user, token, request)
try:
client = get_discourse_client(settings)
r = client.redirect_without_nonce(user)
response['redirect_internal'] = r
except:
# Since only the password is changed, any error with discourse
# must not prevent login and validation.
log.error(
'Error logging into discourse for %d', user.id,
exc_info=True)
user.clear_validation_nonce()
try:
DBSession.flush()
except:
log.warning('Error persisting user', exc_info=True)
raise HTTPInternalServerError('Error persisting user')
return response
else:
request.errors.status = 403
request.errors.add('body', 'user', 'Login failed')
return None
示例12: set_linked_routes
def set_linked_routes(waypoint, lang):
"""
Set associated routes for the given waypoint including associated routes
of child and grandchild waypoints.
Note that this function returns a dict and not a list!
"""
with_query_waypoints = _get_select_children(waypoint)
route_ids = get_first_column(
DBSession.query(Route.document_id)
.select_from(with_query_waypoints)
.join(Association, with_query_waypoints.c.document_id == Association.parent_document_id)
.join(Route, Association.child_document_id == Route.document_id)
.filter(Route.redirects_to.is_(None))
.order_by(with_query_waypoints.c.priority.desc(), Route.document_id.desc())
.limit(NUM_ROUTES)
.all()
)
total = (
DBSession.query(Route.document_id)
.select_from(with_query_waypoints)
.join(Association, with_query_waypoints.c.document_id == Association.parent_document_id)
.join(Route, Association.child_document_id == Route.document_id)
.filter(Route.redirects_to.is_(None))
.count()
)
waypoint.associations["all_routes"] = get_documents_for_ids(route_ids, lang, route_documents_config, total)
示例13: update_feed_document_update
def update_feed_document_update(document, user_id, update_types):
"""Update the feed entry for a document:
- update `area_ids` if the geometry has changed.
- update `activities` if figures have changed.
- update `user_ids` if the document is an outing and the participants
have changed.
Only when updating `user_ids`, the "actor" of the feed entry is changed.
And only then the time is updated and the `change_type` set to `updated`
to push the entry to the top of the feed.
"""
if document.redirects_to:
# TODO delete existing feed entry?
# see https://github.com/c2corg/v6_api/issues/386
return
if document.type in [IMAGE_TYPE, USERPROFILE_TYPE, AREA_TYPE]:
return
DBSession.flush()
# update areas
if UpdateType.GEOM in update_types:
update_areas_of_changes(document)
# updates activities
if document.type in [ARTICLE_TYPE, OUTING_TYPE, ROUTE_TYPE] and \
UpdateType.FIGURES in update_types:
update_activities_of_changes(document)
# update users_ids/participants (only for outings)
if document.type != OUTING_TYPE:
return
update_participants_of_outing(document.document_id, user_id)
示例14: collection_post
def collection_post(self):
settings = self.request.registry.settings
locale = self.request.validated['locale']
title = "{}_{}".format(locale.document_id, locale.lang)
content = '<a href="{}">{}</a>'.format(
self.request.referer,
locale.title)
category = settings['discourse.category']
# category could be id or name
try:
category = int(category)
except:
pass
client = get_discourse_client(settings)
try:
response = client.client.create_post(content,
title=title,
category=category)
except:
raise HTTPInternalServerError('Error with Discourse')
if "topic_id" in response:
document_topic = DocumentTopic(topic_id=response['topic_id'])
locale.document_topic = document_topic
update_cache_version_direct(locale.document_id)
DBSession.flush()
return response
示例15: _get_documents
def _get_documents(
self, clazz, schema, clazz_locale, adapt_schema, custom_filter,
include_areas, set_custom_fields, meta_params, load_documents):
base_query = DBSession.query(clazz).\
filter(getattr(clazz, 'redirects_to').is_(None))
base_total_query = DBSession.query(getattr(clazz, 'document_id')).\
filter(getattr(clazz, 'redirects_to').is_(None))
if custom_filter:
base_query = custom_filter(base_query)
base_total_query = custom_filter(base_total_query)
base_query = add_load_for_locales(base_query, clazz, clazz_locale)
base_query = base_query.options(joinedload(getattr(clazz, 'geometry')))
if clazz == Outing:
base_query = base_query. \
order_by(clazz.date_end.desc()). \
order_by(clazz.document_id.desc())
else:
base_query = base_query.order_by(clazz.document_id.desc())
base_query = add_load_for_profiles(base_query, clazz)
base_total_query = add_profile_filter(base_total_query, clazz)
if include_areas:
base_query = base_query. \
options(
joinedload(getattr(clazz, '_areas')).
load_only(
'document_id', 'area_type', 'version', 'protected',
'type').
joinedload('locales').
load_only(
'lang', 'title',
'version')
)
documents, total = load_documents(base_query, base_total_query)
set_available_langs(documents, loaded=True)
lang = meta_params['lang']
if lang is not None:
set_best_locale(documents, lang)
if include_areas:
self._set_areas_for_documents(documents, lang)
if set_custom_fields:
set_custom_fields(documents, lang)
return {
'documents': [
to_json_dict(
doc,
schema if not adapt_schema else adapt_schema(schema, doc)
) for doc in documents
],
'total': total
}