当前位置: 首页>>代码示例>>Python>>正文


Python DBSession.add方法代码示例

本文整理汇总了Python中lmkp.models.meta.DBSession.add方法的典型用法代码示例。如果您正苦于以下问题:Python DBSession.add方法的具体用法?Python DBSession.add怎么用?Python DBSession.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lmkp.models.meta.DBSession的用法示例。


在下文中一共展示了DBSession.add方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: succeed

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
        def succeed():
            """
            """

            # Request all submitted values
            profile_field = self.request.POST.get("profile")
            username_field = self.request.POST.get("username")
            firstname_field = self.request.POST.get("firstname")
            lastname_field = self.request.POST.get("lastname")
            password_field = self.request.POST.get("password")
            email_field = self.request.POST.get("email")

            # Get the selected profile
            selected_profile = Session.query(Profile).filter(
                Profile.code == profile_field).first()

            # Get the initial user group
            user_group = Session.query(Group).filter(
                Group.name == "editors").first()

            # Create an activation uuid
            activation_uuid = uuid.uuid4()

            # Create a new user
            new_user = User(username_field, password_field, email_field,
                            firstname=firstname_field,
                            lastname=lastname_field,
                            activation_uuid=activation_uuid,
                            registration_timestamp=datetime.now())

            # Set the user profile
            new_user.profiles = [selected_profile]
            new_user.groups = [user_group]
            # Commit the new user
            Session.add(new_user)

            activation_dict = {
                "firstname": new_user.firstname,
                "lastname": new_user.lastname,
                "activation_link": "http://%s/users/activate?uuid=%s&username="
                "%s" % (
                    self.request.environ['HTTP_HOST'], activation_uuid,
                    new_user.username)
            }
            email_text = render(
                get_customized_template_path(
                    self.request, 'emails/account_activation.mak'),
                activation_dict, self.request)

            self._send_email(
                [email_field], _(u"Activate your Account"), email_text)

            return render_to_response(
                get_customized_template_path(
                    self.request, 'users/registration_success.mak'),
                {}, self.request)
开发者ID:CDE-UNIBE,项目名称:lokp,代码行数:58,代码来源:user.py

示例2: _translate_keyvalue

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
    def _translate_keyvalue(original, translation, TableItem, isKey,
        locale, helptext_translation):
        """
        Helper function to insert or update a single translation for a key or a
        value
        """

        # Query the database to find english entry of key or value
        if isKey:
            english_query = Session.query(TableItem).\
                filter(TableItem.key == original).\
                filter(TableItem.fk_language == 1)
        else:
            english_query = Session.query(TableItem).\
                filter(TableItem.value == original).\
                filter(TableItem.fk_language == 1)
        eng = english_query.all()

        if eng is None or len(eng) == 0:
            return {'success': False, 'msg': 'No english value found for "%s", translation "%s" not inserted.' % (original, translation)}

        for e in eng:
            # Check if translation already exists for value
            if isKey:
                originalEntry = e.original
                translation_query = Session.query(TableItem).\
                    filter(TableItem.original == originalEntry).\
                    filter(TableItem.language == locale)
            else:
                originalEntry = e
                translation_query = Session.query(TableItem).\
                    filter(TableItem.original == originalEntry).\
                    filter(TableItem.language == locale)
            translation_entry = translation_query.first()

            if translation_entry is None:
                # No translation found, insert a new translation
                if isKey:
                    new_translation = TableItem(translation, e.type)
                else:
                    new_translation = TableItem(translation)
                new_translation.language = locale
                new_translation.original = originalEntry
                if helptext_translation != '':
                    new_translation.helptext = helptext_translation
                Session.add(new_translation)
            else:
                # There is already a translation, update it
                if isKey:
                    translation_entry.key = translation
                else:
                    translation_entry.value = translation
                if helptext_translation != '':
                    translation_entry.helptext = helptext_translation

        return {'success': True, 'msg': 'Translation "%s" inserted for value "%s".' % (translation, original)}
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:58,代码来源:translation.py

示例3: _add_to_db

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
def _add_to_db(db_object, name):
    s = Session()
    s.add(db_object)
    try:
        transaction.commit()
        result = 1
    except IntegrityError:
        transaction.abort()
        result = 0
    return result
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:12,代码来源:sample_values.py

示例4: _translate_category

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
    def _translate_category(original, translation, TableItem, locale):
        """
        Helper function to insert or update a single translation for a
        category.
        """

        # Query the database to find the english entry of the category
        english_query = Session.query(TableItem).\
            filter(TableItem.name == original).\
            filter(TableItem.fk_language == 1)
        eng = english_query.all()

        if len(eng) == 0:
            return {
                'success': False,
                'msg': 'No english value found for "%s", translation "%s" not '
                'inserted.' % (original, translation)
            }

        for e in eng:
            # Check if translation already exists
            translation_query = Session.query(TableItem).\
                filter(TableItem.original == e).\
                filter(TableItem.language == locale)
            translation_entry = translation_query.first()

            if translation_entry is None:
                # Insert a new translation
                new_translation = TableItem(translation)
                new_translation.language = locale
                new_translation.original = e
                Session.add(new_translation)
            else:
                # Update an existing translation
                translation_entry.name = translation

        return {
            'success': True,
            'msg': 'Translation "%s" inserted for value "%s".' % (
                translation, original)
        }
开发者ID:CDE-UNIBE,项目名称:lokp,代码行数:43,代码来源:translation.py

示例5: __check_geometry

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
 def __check_geometry(yaml_geom, profile_name):
     yaml_geom_geojson = geojson.loads(json.dumps(yaml_geom),
                                       object_hook=geojson.GeoJSON.to_instance)
     yaml_geom_shape = shapely.geometry.asShape(yaml_geom_geojson)
     # Query database
     db_profile = Session.query(Profile).\
         filter(Profile.code == profile_name).first()
     if db_profile is None:
         # Global profile does not yet exist, create it
         Session.add(Profile(profile_name, yaml_geom_shape.wkt))
         return "Geometry for profile '%s' created." % profile_name
     else:
         # Compare existing geometry with the one in config file
         geom_db = (shapely.wkb.loads(str(db_profile.geometry.geom_wkb))
                    if db_profile.geometry else None)
         if geom_db and geom_db.equals(yaml_geom_shape) is True:
             return ("Geometry for profile '%s' did not change."
                     % profile_name)
         else:
             # Update geometry from global profile
             db_profile.geometry = yaml_geom_shape.wkt
             return "Geometry for profile '%s' updated." % profile_name
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:24,代码来源:config.py

示例6: edit_translation

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
def edit_translation(request):

    _ = request.translate

    success = False
    msg = _('Translation not successful')
    if 'original' and 'translation' and 'language' and 'keyvalue' and 'item_type' in request.params:
        # find language
        language = Session.query(Language).filter(Language.locale == request.params['language']).all()
        if language and len(language) == 1:
            if request.params['keyvalue'] == 'key':
                # Activity or Stakeholder?
                Key = None
                if request.params['item_type'] == 'activity':
                    Key = A_Key
                elif request.params['item_type'] == 'stakeholder':
                    Key = SH_Key
                # find original (fk_a_key empty)
                original = Session.query(Key).filter(Key.key == request.params['original']).filter(Key.original == None).all()
                if original and len(original) == 1:
                    # check if a translation of this key is already there
                    oldTranslation = Session.query(Key).filter(Key.original == original[0]).filter(Key.language == language[0]).all()
                    if oldTranslation and len(oldTranslation) == 1:
                        # translation found, just update it.
                        oldTranslation[0].key = request.params['translation']
                        success = True
                        msg = _('Updated translation')
                    else:
                        # no translation available yet, add it to DB
                        translation = Key(request.params['translation'])
                        translation.original = original[0]
                        translation.language = language[0]
                        Session.add(translation)
                        success = True
                        msg = _('Added translation')
                else:
                    msg = 'Original key not found' # should never happen
            if request.params['keyvalue'] == 'value':
                # Activity or Stakeholder?
                Value = None
                if request.params['item_type'] == 'activity':
                    Value = A_Value
                elif request.params['item_type'] == 'stakeholder':
                    Value = SH_Value
                # find original (fk_a_value empty)
                original = Session.query(Value).filter(Value.value == request.params['original']).filter(Value.original == None).all()
                if original and len(original) == 1:
                    # check if a translation of this value is already there
                    oldTranslation = Session.query(Value).filter(Value.original == original[0]).filter(Value.language == language[0]).all()
                    if oldTranslation and len(oldTranslation) == 1:
                        # translation found, just update it.
                        oldTranslation[0].value = request.params['translation']
                        success = True
                        msg = _('Updated translation')
                    else:
                        # no translation available yet, add it to DB
                        translation = Value(request.params['translation'])
                        translation.original = original[0]
                        translation.language = language[0]
                        Session.add(translation)
                        success = True
                        msg = _('Added translation')
                else:
                    msg = 'Original value not found' # should never happen
        else:
            msg = 'Language not unique or not found in DB' # should never happen
    
    return {
        'success': success,
        'msg': msg
    }
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:73,代码来源:translation.py

示例7: comment_add

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
def comment_add(request):

    _ = request.translate

    """
    Add a new comment
    """

    """
    CONFIGURATION
    """
    # Use captcha or not? Disable for example if no internet connection is
    # available. Also disable in JavaScript code (view.comments.CommentPanel)
    USE_CAPTCHA = False

    ret = {'success': False}

    # check if captcha is available
    if USE_CAPTCHA:
        if (request.POST['recaptcha_challenge_field'] is None
                or request.POST['recaptcha_response_field'] is None):
            ret['message'] = 'No captcha provided.'
            return ret

    # check if object is available
    if request.POST['object'] is None:
        ret['message'] = 'No object to comment upon provided.'
        return ret

    # check if comment is available
    if request.POST['comment'] is None:
        ret['message'] = 'No comment provided.'
        return ret

    # check if identifier is available
    if request.POST['identifier'] is None:
        ret['message'] = 'No identifier provided.'
        return ret

    if not USE_CAPTCHA:
        class C(object):
            is_valid = True
        response = C()
    else:
        # check captcha
        private_key = '6LfqmNESAAAAAKM_cXox32Nnz0Zo7nlOeDPjgIoh'
        response = captcha.submit(
            request.POST['recaptcha_challenge_field'],
            request.POST['recaptcha_response_field'], private_key,
            request.referer)

    if not response.is_valid:
        # captcha not correct
        ret['message'] = _('Captcha not correct.')
        ret['captcha_reload'] = True
        return ret
    else:
        # captcha correct, try to do insert
        if request.POST['object'] == 'activity':
            # check if identifier is a valid UUID
            try:
                a_uuid = uuid.UUID(request.POST['identifier'])
            except ValueError:
                ret['message'] = 'Not a valid UUID.'
                return ret

            # prepare the insert
            comment = Comment(request.POST['comment'])
            comment.activity_identifier = a_uuid
            comment.user = Session.query(User).filter(
                User.username == authenticated_userid(request)).first() \
                if authenticated_userid(request) else None

            # do the insert
            Session.add(comment)
            ret['message'] = _('Comment successfully inserted.')

        elif request.POST['object'] == 'stakeholder':
            ret['message'] = 'Stakeholder comments are not yet implemented.'
            return ret

        elif request.POST['object'] == 'involvement':
            ret['message'] = 'Involvement comments are not yet implemented.'
            return ret

        else:
            ret['message'] = _('Object not found.')
            return ret

    # if we've come this far, set success to 'True'
    ret['success'] = True

    return ret
开发者ID:CDE-UNIBE,项目名称:lokp,代码行数:95,代码来源:comments.py

示例8: handle_upload

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
def handle_upload(request, filedict):
    """
    Handle the upload of a new file.
    http://code.google.com/p/file-uploader/
    """

    TEMP_FOLDER_NAME = "temp"

    ret = {"success": False, "msg": ""}

    filename = None
    filetype = None
    file = None

    try:
        filename = filedict["filename"]
        file = filedict["fp"]
        filetype = filedict["mimetype"]
    except:
        ret["msg"] = _("Not all necessary values were provided.")
        valid = False

    if filename is None or file is None or filetype is None:
        ret["msg"] = "Uploaded file not found."

    # Check upload directory
    upload_path = upload_directory_path(request)
    if upload_path is None or not os.path.exists(upload_path):
        ret["msg"] = _("Upload directory not specified or not found.")
        return ret

    # Check filetype
    fileextension = get_valid_file_extension(request, filetype)
    if fileextension is None:
        ret["msg"] = _("File type is not valid.")
        return ret

    # Check filesize
    size = get_file_size(file)
    if size > upload_max_file_size(request):
        ret["msg"] = _("File is too big.")
        return ret

    # Do the actual file processing

    # Strip leading path from file name to avoid directory traversal
    # attacks
    old_filename = os.path.basename(filename)

    # Internet Explorer will attempt to provide full path for filename
    # fix
    old_filename = old_filename.split("\\")[-1]

    # Remove the extension and check the filename
    clean_filename = ".".join(old_filename.split(".")[:-1])
    clean_filename = _clean_filename(clean_filename)

    # Make sure the filename is not too long
    if len(clean_filename) > 500:
        clean_filename = clean_filename[:500]

    # Append the predefined file extension
    clean_filename = "%s%s" % (clean_filename, fileextension)

    # Use a randomly generated UUID as filename
    file_identifier = uuid.uuid4()
    new_filename = "%s%s" % (file_identifier, fileextension)

    # Check if the directories already exist. If not, create them.
    if not os.path.exists(os.path.join(upload_path, TEMP_FOLDER_NAME)):
        os.makedirs(os.path.join(upload_path, TEMP_FOLDER_NAME))

    new_filepath = os.path.join(upload_path, TEMP_FOLDER_NAME, new_filename)

    # Open the new file for writing
    f = open(new_filepath, "wb", 10000)

    datalength = 0

    # Read the file in chunks
    for chunk in _file_buffer(file):
        f.write(chunk)
        datalength += len(chunk)
    f.close()

    # Open the file again to get the hash
    hash = get_file_hash(new_filepath)

    # Database values
    db_file = File(identifier=file_identifier, name=clean_filename, mime=filetype, size=datalength, hash=hash)
    Session.add(db_file)

    log.debug("The uploaded file (%s) was saved as %s at %s" % (clean_filename, new_filename, new_filepath))

    ret["filename"] = clean_filename
    ret["fileidentifier"] = str(file_identifier)

    ret["msg"] = _("File was successfully uploaded")
    ret["success"] = True

#.........这里部分代码省略.........
开发者ID:CDE-UNIBE,项目名称:lokp,代码行数:103,代码来源:files.py

示例9: _add_to_db

# 需要导入模块: from lmkp.models.meta import DBSession [as 别名]
# 或者: from lmkp.models.meta.DBSession import add [as 别名]
def _add_to_db(config, Key, Value):

    stack = []
    stack.append('Scan results:')

    # check for english language (needs to have id=1)
    language = Session.query(Language).get(1)
    if language is None:
        # language not found, insert it.
        language = Language(1, 'English', 'English', 'en')
        Session.add(language)
        stack.append('Language (English) added.')

    # get keys already in database. their fk_sh_key must be None (= original)
    db_keys = []
    for db_key in Session.query(Key.key).filter(Key.fk_key == None).all():
        db_keys.append(db_key.key)

    # get values already in database. their fk_sh_value must be None (= original)
    db_values = []
    for db_value in Session.query(Value.value).filter(Value.fk_value == None).all():
        db_values.append(db_value.value)

    config_items = config["fields"]["mandatory"].items() + config["fields"]["optional"].items()
    for key, value in config_items:
        # check if key is already in database
        if key in db_keys:
            # key is already there, do nothing
            stack.append('Key already in database: %s' % key)
        else:
            # key is not yet in database, insert it
            new_key = Key(key=key)
            new_key.language = language
            Session.add(new_key)
            stack.append('Key added to database: %s' % key)

        # do the same with values
        if value.items():
            for k, val in value.items():
                if k == 'predefined':
                    for v in val:
                        # check if value is already in database
                        if v in db_values:
                            # value is already there, do nothing
                            stack.append('Value already in database: %s' % v)
                        else:
                            # value is not yet in database, insert it
                            new_value = Value(v)
                            new_value.language = language
                            Session.add(new_value)
                            stack.append('Value added to database: %s' % v)
                # Values from local YAML are one level deeper
                if k == 'values':
                    for k2, v2 in val.items():
                        if k2 == 'predefined':
                            for v in v2:
                                # check if value is already in database
                                if v in db_values:
                                    # value is already there, do nothing
                                    stack.append('Value already in database: %s' % v)
                                else:
                                    # value is not yet in database, insert it
                                    new_value = Value(v)
                                    new_value.language = language
                                    Session.add(new_value)
                                    stack.append('Value added to database: %s' % v)

    return {'messagestack': stack}
开发者ID:sinnwerkstatt,项目名称:lokp,代码行数:70,代码来源:config.py


注:本文中的lmkp.models.meta.DBSession.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。