本文整理汇总了Python中c2cgeoportal_commons.models.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类c2cgeoportal_commons.models.DBSession
的用法示例。
在下文中一共展示了DBSession.add方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setup_method
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def setup_method(self, _):
# Always see the diff
# https://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff
self.maxDiff = None
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import Theme, LayerGroup, Interface, LayerWMS
main = Interface(name="desktop")
ogc_server, _ = create_default_ogcserver()
layer_wms = LayerWMS(name="__test_layer_wms", public=True)
layer_wms.layer = "testpoint_unprotected"
layer_wms.interfaces = [main]
layer_wms.ogc_server = ogc_server
layer_group = LayerGroup(name="__test_layer_group")
layer_group.children = [layer_wms]
theme = Theme(name="__test/theme")
theme.interfaces = [main]
theme.children = [
layer_group
]
DBSession.add(theme)
transaction.commit()
示例2: main
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def main():
parser = argparse.ArgumentParser(
description="Create and populate the database tables."
)
parser.add_argument(
'-i', '--iniconfig',
default='geoportal/production.ini',
help='project .ini config file'
)
parser.add_argument(
'-n', '--app-name',
default="app",
help='The application name (optional, default is "app")'
)
options = parser.parse_args()
# read the configuration
fileConfig(options.iniconfig, defaults=os.environ)
get_app(options.iniconfig, options.app_name, options=os.environ)
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import Interface, OGCServer, Theme, LayerGroup, LayerWMS
session = DBSession()
interfaces = session.query(Interface).all()
ogc_server = session.query(OGCServer).filter(OGCServer.name == "source for image/png").one()
layer_borders = LayerWMS("Borders", "borders")
layer_borders.interfaces = interfaces
layer_borders.ogc_server = ogc_server
layer_density = LayerWMS("Density", "density")
layer_density.interfaces = interfaces
layer_density.ogc_server = ogc_server
group = LayerGroup("Demo")
group.children = [layer_borders, layer_density]
theme = Theme("Demo")
theme.children = [group]
theme.interfaces = interfaces
session.add(theme)
transaction.commit()
示例3: setup_method
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def setup_method(self, _):
self.maxDiff = None
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.static import User
user = User(username="__test_user1", password="__test_user1")
DBSession.add(user)
DBSession.flush()
self.old_remember = pyramid.security.remember
self.user = None
def remember(request, user=None):
self.user = user
pyramid.security.remember = remember
示例4: setup_method
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def setup_method(self, _):
# Always see the diff
# https://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff
self.maxDiff = None
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import Theme, LayerGroup, Interface, LayerWMS, Metadata
desktop = Interface(name="desktop")
ogc_server_internal, _ = create_default_ogcserver()
layer_wms = LayerWMS(name="__test_layer_internal_wms", public=True)
layer_wms.layer = "__test_layer_internal_wms"
layer_wms.ogc_server = ogc_server_internal
layer_wms.interfaces = [desktop]
layer_wms.metadatas = [
Metadata("string", "string"),
Metadata("list", "1, 2, a"),
Metadata("boolean", "y"),
Metadata("boolean2", "no"),
Metadata("boolean3", "Hello"),
Metadata("integer", "1"),
Metadata("float", "5.5"),
Metadata("json", '{"test": 123}'),
Metadata("json_wrong", '{"test": 123'),
Metadata("date", "Sep 25 2003"),
Metadata("time", "10:36:28"),
Metadata("datetime", "Sep 25 10:36:28 BRST 2003"),
Metadata("date2", "Sep 25 10:36:28 BRST 2003"),
Metadata("time2", "Sep 25 10:36:28 BRST 2003"),
Metadata("datetime2", "Hello"),
Metadata("url1", "http://example.com/hi?a=b#c"),
Metadata("url2", "static:///path/icon.png"),
Metadata("url3", "static://static/path/icon.png"),
Metadata("url4", "static://cgxp/path/icon.png"),
Metadata("url5", "static://project:static/path/icon.png"),
Metadata("url6", "static://project:cgxp/path/icon.png"),
Metadata("url7", "config://server"),
Metadata("url8", "config://server/index.html"),
Metadata("url9", "/dummy/static/icon.png"),
Metadata("url10", "dummy/static/icon.png"),
Metadata("url11", "https:///static/icon.png"),
Metadata("url12", "static://test"),
Metadata("url13", "static://test/"),
Metadata("url14", "config:///static/icon.png"),
Metadata("url15", "config://unknown_server"),
Metadata("url16", "https://"),
Metadata("url17", "https:///"),
Metadata("url18", "https:///static"),
Metadata("url19", ""),
Metadata("url20", "/"),
Metadata("unknown", "Hello"),
]
layer_group = LayerGroup(name="__test_layer_group")
layer_group.children = [layer_wms]
theme = Theme(name="__test_theme")
theme.interfaces = [desktop]
theme.children = [layer_group]
DBSession.add(theme)
transaction.commit()
示例5: setup_method
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def setup_method(self, _):
# Always see the diff
# https://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff
self.maxDiff = None
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import \
Theme, LayerGroup, Interface, LayerWMS, LayerWMTS, Dimension
ogc_server, _ = create_default_ogcserver()
main = Interface(name="main")
layer_wms_1 = LayerWMS(name="__test_layer_wms_1", public=True)
layer_wms_1.layer = "__test_layer_wms_1"
layer_wms_1.interfaces = [main]
layer_wms_1.ogc_server = ogc_server
Dimension("A", "a", layer_wms_1)
layer_wms_2 = LayerWMS(name="__test_layer_wms_2", public=True)
layer_wms_2.layer = "__test_layer_wms_2"
layer_wms_2.interfaces = [main]
layer_wms_2.ogc_server = ogc_server
Dimension("A", "b", layer_wms_2)
layer_wms_3 = LayerWMS(name="__test_layer_wms_3", public=True)
layer_wms_3.layer = "__test_layer_wms_3"
layer_wms_3.interfaces = [main]
layer_wms_3.ogc_server = ogc_server
Dimension("A", None, layer_wms_3)
layer_wms_4 = LayerWMS(name="__test_layer_wms_4", public=True)
layer_wms_4.layer = "__test_layer_wms_4"
layer_wms_4.interfaces = [main]
layer_wms_4.ogc_server = ogc_server
Dimension("A", "a", layer_wms_4)
layer_wms_5 = LayerWMS(name="__test_layer_wms_5", public=True)
layer_wms_5.layer = "__test_layer_wms_5"
layer_wms_5.interfaces = [main]
layer_wms_5.ogc_server = ogc_server
Dimension("B", "b", layer_wms_5)
layer_wms_6 = LayerWMS(name="__test_layer_wms_6", public=True)
layer_wms_6.layer = "__test_layer_wms_6"
layer_wms_6.interfaces = [main]
layer_wms_6.ogc_server = ogc_server
Dimension("FILTER", "countries:\"name\" IN ( 'Germany' , 'Italy' )", layer_wms_6)
layer_wmts = LayerWMTS(name="__test_layer_wmts", public=True)
layer_wmts.url = "http://example.com/1.0.0/WMTSCapabilities.xml"
layer_wmts.layer = "map"
layer_wmts.interfaces = [main]
Dimension("B", "b", layer_wmts)
layer_wmts_2 = LayerWMTS(name="__test_layer_wmts_2", public=True)
layer_wmts_2.url = "http://example.com/1.0.0/WMTSCapabilities.xml"
layer_wmts_2.layer = "map"
layer_wmts_2.interfaces = [main]
Dimension("FILTER", "countries:\"name\" IN ( 'Germany' , 'Italy' )", layer_wmts_2)
layer_group_1 = LayerGroup(name="__test_layer_group_1")
layer_group_1.children = [layer_wms_1, layer_wmts, layer_wmts_2]
layer_group_2 = LayerGroup(name="__test_layer_group_2")
layer_group_2.children = [layer_wms_1, layer_wms_2]
layer_group_3 = LayerGroup(name="__test_layer_group_3")
layer_group_3.children = [layer_wms_1, layer_wms_3]
layer_group_4 = LayerGroup(name="__test_layer_group_4")
layer_group_4.children = [layer_wms_1, layer_wms_4]
layer_group_5 = LayerGroup(name="__test_layer_group_5")
layer_group_5.children = [layer_wms_1, layer_wms_5, layer_wms_6]
layer_group_6 = LayerGroup(name="__test_layer_group_6")
layer_group_6.children = [layer_wms_3]
theme = Theme(name="__test_theme")
theme.interfaces = [main]
theme.children = [
layer_group_1, layer_group_2, layer_group_3,
layer_group_4, layer_group_5, layer_group_6,
]
DBSession.add(theme)
transaction.commit()
示例6: create
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def create(self):
if "url" not in self.request.params:
raise HTTPBadRequest("The parameter url is required")
url = self.request.params["url"]
# see: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestline
if len(url) > 8190: # pragma: no cover
raise HTTPBadRequest("The parameter url is too long ({} > {})".format(len(url), 8190))
# Check that it is an internal URL...
uri_parts = urlparse(url)
hostname = uri_parts.hostname
if "allowed_hosts" in self.settings:
if hostname not in self.settings["allowed_hosts"]: # pragma: no cover
raise HTTPBadRequest("The requested host is not allowed.")
else:
if hostname != self.request.server_name:
raise HTTPBadRequest("The requested host '{0!s}' should be '{1!s}'".format(
hostname, self.request.server_name
))
shortened = False
for base in self.short_bases:
base_parts = urlparse(base)
if uri_parts.path.startswith(base_parts.path):
shortened = True
ref = uri_parts.path.split("/")[-1]
tries = 0
while not shortened:
ref = "".join(
random.choice(string.ascii_letters + string.digits)
for i in range(self.settings.get("length", 4))
)
test_url = DBSession.query(Shorturl).filter(Shorturl.ref == ref).all()
if len(test_url) == 0:
break
tries += 1 # pragma: no cover
if tries > 20: # pragma: no cover
message = "No free ref found, considere to increase the length"
logging.error(message)
raise HTTPInternalServerError(message)
user_email = self.request.user.email \
if self.request.user is not None else None
email = self.request.params.get("email")
if not shortened:
short_url = Shorturl()
short_url.url = url
short_url.ref = ref
short_url.creator_email = user_email
short_url.creation = datetime.now()
short_url.nb_hits = 0
DBSession.add(short_url)
if "base_url" in self.settings:
s_url = self.settings["base_url"] + ref
else:
s_url = self.request.route_url("shortener_get", ref=ref)
email = email or user_email
smtp_config = self.request.registry.settings.get("smtp", {})
if \
email is not None and \
"email_from" in self.settings and \
"email_subject" in self.settings and \
"email_body" in self.settings: # pragma: no cover
text = self.settings["email_body"] % {
"full_url": url,
"short_url": s_url,
"message": self.request.params.get("message", ""),
}
send_email(
self.settings["email_from"],
[email],
text.encode("utf-8"),
self.settings["email_subject"],
smtp_config
)
set_common_headers(
self.request, "shortener", NO_CACHE
)
return {"short_url": s_url}
示例7: _create_layer
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def _create_layer(self, exclude_properties=False, metadatas=None, geom_type=False):
""" This function is central for this test class. It creates
a layer with two features, and associates a restriction area
to it. """
import transaction
from sqlalchemy import Column, Table, types, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy2 import Geometry
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import RestrictionArea, LayerWMS
self.__class__._table_index += 1
id = self.__class__._table_index
engine = DBSession.c2c_rw_bind
connection = engine.connect()
if not self.metadata:
self.metadata = declarative_base(bind=engine).metadata
tablename = "geo_table_{0:d}".format(id)
schemaname = "geodata"
table1 = Table(
"{0!s}_child".format(tablename), self.metadata,
Column("id", types.Integer, primary_key=True),
Column("name", types.Unicode),
schema=schemaname
)
self._tables.append(table1)
table2 = Table(
tablename, self.metadata,
Column("id", types.Integer, primary_key=True),
Column("child_id", types.Integer,
ForeignKey("{0!s}.{1!s}_child.id".format(schemaname, tablename))),
Column("name", types.Unicode, nullable=False),
Column("deleted", types.Boolean),
Column("last_update_user", types.Unicode),
Column("last_update_date", types.DateTime),
Column("date", types.Date),
Column("start_time", types.Time),
# Column("interval", Interval()),
Column("short_name1", types.String, nullable=True),
Column("short_name2", types.String(50), nullable=True),
Column("short_number", types.Integer, nullable=True),
Column("double_number", types.Float(precision=4)),
Column("large_binary", types.LargeBinary(length=60), nullable=True),
Column("value", types.Enum("one", "two", "three", name="an_enum_value")),
Column("numeric", types.Numeric(precision=5, scale=2), nullable=True),
Column("numeric2", types.Numeric(), nullable=True),
schema=schemaname
)
if geom_type:
table2.append_column(
Column("geom", Geometry("POINT", srid=21781))
)
else:
table2.append_column(
Column("geom", Geometry(srid=21781))
)
self._tables.append(table2)
table2.drop(checkfirst=True)
table1.drop(checkfirst=True)
table1.create()
table2.create()
ins = table1.insert().values(name="c1é")
connection.execute(ins).inserted_primary_key[0]
ins = table1.insert().values(name="c2é")
connection.execute(ins).inserted_primary_key[0]
layer = LayerWMS(name="test_WMS_1", public=True)
layer.layer = "test_wms"
layer.id = id
layer.geo_table = "{0!s}.{1!s}".format(schemaname, tablename)
layer.interfaces = [self.main]
layer.ogc_server = self.ogc_server
if exclude_properties:
layer.exclude_properties = "name"
if metadatas:
layer.metadatas = metadatas
DBSession.add(self.layer_group_1)
self.layer_group_1.children = self.layer_group_1.children + [layer]
DBSession.add(self.layer_group_1)
ra = RestrictionArea()
ra.name = "__test_ra"
ra.layers = [layer]
ra.roles = [self.role]
ra.readwrite = True
DBSession.add(ra)
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
class Import:
def __init__(self, options):
self.options = options
self.imported = set()
settings = get_config("config.yaml")
package = settings["package"]
self.fts_languages = settings["fulltextsearch"]["languages"]
self.languages = settings["available_locale_names"]
# must be done only once we have loaded the project config
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import FullTextSearch, Interface, Theme, Role
self.session = DBSession()
self.session.execute(FullTextSearch.__table__.delete().where(FullTextSearch.from_theme == True)) # noqa
self._ = {}
for lang in self.languages:
self._[lang] = translation(
"{}-client".format(package), os.path.join(package, "locale/"), [lang])
query = self.session.query(Interface)
if options.interfaces is not None:
query = query.filter(
Interface.name.in_(options.interfaces)
)
self.interfaces = query.all()
self.public_theme = {}
self.public_group = {}
for interface in self.interfaces:
self.public_theme[interface.id] = []
self.public_group[interface.id] = []
for theme in self.session.query(Theme).filter_by(public=True).all():
self._add_theme(theme)
for role in self.session.query(Role).all():
for theme in self.session.query(Theme).all():
self._add_theme(theme, role)
transaction.commit()
def _add_fts(self, item, interface, action, role):
from c2cgeoportal_commons.models.main import FullTextSearch
key = (
item.name if self.options.name else item.id,
interface.id,
role.id if role is not None else None
)
if key not in self.imported:
self.imported.add(key)
for lang in self.languages:
fts = FullTextSearch()
fts.label = self._[lang].gettext(item.name)
fts.role = role
fts.interface = interface
fts.lang = lang
fts.public = role is None
fts.ts = func.to_tsvector(self.fts_languages[lang], fts.label)
fts.actions = [{
"action": action,
"data": item.name,
}]
fts.from_theme = True
self.session.add(fts)
def _add_theme(self, theme, role=None):
fill = False
for interface in self.interfaces:
if interface in theme.interfaces:
for child in theme.children:
fill = self._add_block(child, interface, role) or fill
if fill and self.options.themes:
if role is None:
self.public_theme[interface.id].append(theme.id)
if role is None or theme.id not in self.public_theme[interface.id]:
self._add_fts(theme, interface, "add_theme", role)
def _add_block(self, group, interface, role):
return self._add_group(group, interface, self.options.blocks, role)
def _add_folder(self, group, interface, role):
return self._add_group(group, interface, self.options.folders, role)
def _add_group(self, group, interface, export, role):
from c2cgeoportal_commons.models.main import LayerGroup
fill = False
for child in group.children:
if isinstance(child, LayerGroup):
fill = self._add_folder(child, interface, role) or fill
else:
fill = self._add_layer(child, interface, role) or fill
#.........这里部分代码省略.........
示例9: main
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def main():
"""
Emergency user create and password reset script
example, reset toto password to foobar:
./docker-compose-run manage_users -p foobar toto
example, create user foo with password bar and role admin:
./docker-compose-run manage_users -c -r role_admin -p bar foo
to get the options list, do:
./docker-compose-run manage_users -h
"""
usage = """Usage: %prog [options] USERNAME
Reset a user password.
The username is used as password if the password is not provided with the corresponding option.
User can be created if it does not exist yet."""
parser = argparse.ArgumentParser(description=usage)
parser.add_argument(
"-i", "--app-config",
default="geoportal/production.ini", dest="app_config",
help="The application .ini config file (optional, default is "
"'production.ini')"
)
parser.add_argument(
"-n", "--app-name",
default="app", dest="app_name",
help="The application name (optional, default is 'app')"
)
parser.add_argument(
"-p", "--password",
help="Set password (if not set, username is used as password"
)
parser.add_argument(
"-c", "--create",
action="store_true", default=False,
help="Create user if it does not already exist"
)
parser.add_argument(
"-r", "--rolename",
default="role_admin",
help="The role name which must exist in the database"
)
parser.add_argument(
"-e", "--email",
default=None,
help="The user email"
)
parser.add_argument(
'user',
nargs='1',
help="The user"
)
options = parser.parse_args()
username = options.user
app_config = options.app_config
app_name = options.app_name
if app_name is None and "#" in app_config:
app_config, app_name = app_config.split("#", 1)
if not os.path.isfile(app_config):
parser.error("Cannot find config file: {0!s}".format(app_config))
# loading schema name from config and setting its value to the
# corresponding global variable from c2cgeoportal_geoportal
# Ignores pyramid deprecation warnings
warnings.simplefilter("ignore", DeprecationWarning)
fileConfig(app_config, defaults=os.environ)
get_app(app_name, options.app_name, options=os.environ)
# must be done only once we have loaded the project config
from c2cgeoportal_commons.models import DBSession, main, static
print("\n")
# check that user exists
sess = DBSession()
query = sess.query(static.User).filter_by(username="{0!s}".format(username))
result = query.count()
if result == 0:
if not options.create:
# if doesn"t exist and no -c option, throw error
raise Exception("User {0!s} does not exist in database".format(username))
else:
print(("User {0!s} does not exist in database, creating".format(username)))
# if does not exist and -c option, create user
password = options.password if options.password is not None else username
email = options.email if options.email is not None else username
# get roles
query_role = sess.query(main.Role).filter(
main.Role.name == "{0!s}".format(options.rolename))
#.........这里部分代码省略.........
示例10: setup_method
# 需要导入模块: from c2cgeoportal_commons.models import DBSession [as 别名]
# 或者: from c2cgeoportal_commons.models.DBSession import add [as 别名]
def setup_method(self, _):
# Always see the diff
# https://docs.python.org/2/library/unittest.html#unittest.TestCase.maxDiff
self.maxDiff = None
from c2cgeoportal_commons.models import DBSession
from c2cgeoportal_commons.models.main import Theme, LayerGroup, Interface, OGCServer, LayerWMS, LayerWMTS
main = Interface(name="main")
ogc_server_internal, _ = create_default_ogcserver()
ogc_server_external = OGCServer(name="__test_ogc_server_external", url="http://wms.geo.admin.ch/", image_type="image/jpeg")
layer_internal_wms = LayerWMS(name="__test_layer_internal_wms", public=True)
layer_internal_wms.layer = "__test_layer_internal_wms"
layer_internal_wms.interfaces = [main]
layer_internal_wms.ogc_server = ogc_server_internal
layer_external_wms = LayerWMS(name="__test_layer_external_wms", layer="ch.swisstopo.dreiecksvermaschung", public=True)
layer_external_wms.interfaces = [main]
layer_external_wms.ogc_server = ogc_server_external
layer_wmts = LayerWMTS(name="__test_layer_wmts", public=True)
layer_wmts.url = "http://example.com/1.0.0/WMTSCapabilities.xml"
layer_wmts.layer = "map"
layer_wmts.interfaces = [main]
layer_group_1 = LayerGroup(name="__test_layer_group_1")
layer_group_1.children = [layer_internal_wms]
layer_group_2 = LayerGroup(name="__test_layer_group_2")
layer_group_2.children = [layer_external_wms]
layer_group_3 = LayerGroup(name="__test_layer_group_3")
layer_group_3.children = [layer_wmts]
layer_group_4 = LayerGroup(name="__test_layer_group_4")
layer_group_4.children = [layer_group_1, layer_group_2]
layer_group_5 = LayerGroup(name="__test_layer_group_5")
layer_group_5.children = [layer_group_1, layer_group_3]
layer_group_6 = LayerGroup(name="__test_layer_group_6")
layer_group_6.children = [layer_internal_wms]
layer_group_7 = LayerGroup(name="__test_layer_group_7")
layer_group_7.children = [layer_group_1, layer_group_6]
layer_group_8 = LayerGroup(name="__test_layer_group_8")
layer_group_8.children = [layer_group_2, layer_group_6]
theme = Theme(name="__test_theme")
theme.interfaces = [main]
theme.children = [
layer_group_1, layer_group_2, layer_group_3,
layer_group_4, layer_group_5,
layer_group_7, layer_group_8,
]
DBSession.add(theme)
transaction.commit()