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


Python SQLFORM.factory方法代码示例

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


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

示例1: contact

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def contact():
    """
    Controller for a simple contact form.
    """
    mail = current.mail
    keydata = {}
    with open('applications/grammateus3/private/app.keys', 'r') as keyfile:
        for line in keyfile:
            k, v = line.split()
            keydata[k] = v

    form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()),
                           Field('message_title', requires=IS_NOT_EMPTY()),
                           Field('message', 'text', requires=IS_NOT_EMPTY()),
                           submit_button='Send message',
                           separator=' ')
    captcha = Recaptcha2(request,
                         keydata['captcha_public_key'],
                         keydata['captcha_private_key'])
    form.element('table').insert(-1, TR('', captcha, ''))
    if form.process().accepted:
        if mail.send(to='[email protected]',
                     reply_to=form.vars.your_email_address,
                     subject='OCP Contact: {}'.format(form.vars.message_title),
                     message=form.vars.message):
            response.flash = 'Thank you for your message.'
            response.js = "jQuery('#%s').hide()" % request.cid
        else:
            form.errors.your_email = "Sorry, we were unable to send the email"
    return dict(form=form)
开发者ID:monotasker,项目名称:grammateus3,代码行数:32,代码来源:default.py

示例2: bulk_update

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def bulk_update():
    """
    Controller function to perform a programmatic update to a field in one table.
    """
    response = current.response
    db = current.db
    myrecs = None
    form = SQLFORM.factory(
        Field('table', requires=IS_IN_SET(db.tables)),
        Field('field'),
        Field('query'),
        Field('new_value'))
    if form.process().accepted:
        query = eval(form.vars.query)
        try:
            recs = db(query)
            recs.update(**{form.vars.field: form.vars.new_value})
            myrecs = recs.select()
            response.flash = 'update succeeded'
        except Exception:
            print traceback.format_exc(5)
    elif form.errors:
        myrecs = BEAUTIFY(form.errors)
        response.flash = 'form has errors'

    return form, myrecs
开发者ID:mbelletti,项目名称:plugin_utils,代码行数:28,代码来源:plugin_utils.py

示例3: projeto

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def projeto():
    u"""Editar informações sobre o projeto marolo.

    Permite que um usuário com permissão de admin edite as informações sobre
    o projeto.
    """
    path = os.path.dirname(os.path.abspath(__file__))
    with open(path + '/../views/default/sobre_projeto.html', 'r') as arq:
        sobre_projeto = arq.read()
    ckeditor = current.globalenv['ckeditor']
    form = SQLFORM.factory(
        Field(
            'texto',
            'text',
            widget=ckeditor.widget,
            default=sobre_projeto,
            requires=IS_NOT_EMPTY()
        ),
        hideerror=True,
        message_onfailure=current.T('O conteúdo não pode ser vazio.')
    )
    form.elements('label', replace=None)
    if form.process().accepted:
        with open(path + '/../views/default/sobre_projeto.html',
                  'w') as arq:
            arq.write(form.vars.texto)
        current.session.flash = current.T(
            'Sobre o projeto editado com sucesso!'
        )
        redirect(URL('admin', 'listar', args='noticias'))
    return {'form': form}
开发者ID:augustopedro,项目名称:marolo,代码行数:33,代码来源:admin.py

示例4: handle_upload

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
    def handle_upload(self):
        """
        Get an upload from CKEditor and returns the new filename.

        Get an upload from CKEditor and returns the new filename that
        can then be inserted into a database. Returns (new_filename,
        old_filename, length, mime_type)
        """
        upload = current.request.vars.upload
        path = os.path.join(current.request.folder, 'uploads')

        if upload is not None:
            if hasattr(upload, 'file'):
                form = SQLFORM.factory(
                    Field('upload', 'upload', requires=IS_NOT_EMPTY(),
                          uploadfs=self.settings.uploadfs,
                          uploadfolder=path),
                    table_name=self.settings.table_upload_name,

                )

                old_filename = upload.filename
                new_filename = form.table.upload.store(upload.file,
                                                       upload.filename)
                if self.settings.uploadfs:
                    length = self.settings.uploadfs.getsize(new_filename)
                else:
                    length = os.path.getsize(os.path.join(path, new_filename))
                mime_type = upload.headers['content-type']

                return (new_filename, old_filename, length, mime_type)
            else:
                raise HTTP(401, 'Upload is not proper type.')
        else:
            raise HTTP(401, 'Missing required upload.')
开发者ID:augustopedro,项目名称:marolo,代码行数:37,代码来源:plugin_ckeditor.py

示例5: send_email

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def send_email():

    title = 'Contato'

    form = SQLFORM.factory(
        Field('name', requires=IS_NOT_EMPTY()),
        Field('email', requires =[ IS_EMAIL(error_message='invalid email!'), IS_NOT_EMPTY() ]),
        Field('subject', requires=IS_NOT_EMPTY()),
        Field('message', requires=IS_NOT_EMPTY(), type='text')
    )
    if form.process().accepted:
        session.name = form.vars.name
        session.email = form.vars.email
        session.subject = form.vars.subject
        session.message = form.vars.message

        x = mails.send(to=['[email protected]'],
            subject='loja de carros',
            message= "Olá esse é um email de teste da lja de carros.\nName:"+ session.name+" \nEmail : " + session.email +"\nSubject : "+session.subject +"\nMessage : "+session.message+ ".\n "
        )

        if x == True:
            response.flash = 'email sent sucessfully.'
        else:
            response.flash = 'fail to send email sorry!'

        #response.flash = 'form accepted.'
    elif form.errors:
        response.flash='form has errors.'

    form_carro = detalhes_geral(db2.carro, 2)

    (form_crud,table_crud) = pesquisa_geral(db2.carro)

    return locals()
开发者ID:JulianaTec,项目名称:TesteRepositorio3,代码行数:37,代码来源:veiculo.py

示例6: members

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def members():
    org = db.organization(request.args(0))

    if not request.args(1):
        fld_email = Field('email', 'string', label=T("Email"))
        fld_email.requires = IS_EMAIL()

        form = SQLFORM.factory(
            fld_email,
            formstyle='bootstrap3_inline',
            submit_button=T("Add user"),
            table_name='members')

        if form.process().accepted:
            u = db.auth_user(email=form.vars.email)
            if u is not None:
                # create new share
                if u.id in org.users:
                    form.errors.email = T(
                        "The user is already in the organization")
                else:
                    user_list = org.users
                    user_list.insert(0, u.id)
                    org.update_record(users=user_list)
                    g_id = auth.user_group(u.id)
                    auth.add_permission(g_id, 'read', db.organization, org.id)
            else:
                # no user with that email
                response.flash = ""
                form.errors.email = T("The user don't exists on this system")
    elif request.args(1) == 'delete':
        # remove the user on args(2) from the org members list
        # TODO: remove else any perms on the org desks
        user_to_remove = db.auth_user(request.args(2))
        if user_to_remove is not None:
            user_list = org.users
            user_list.remove(user_to_remove.id)
            org.update_record(users=user_list)
            # remove perms over the org
            auth.del_permission(
                auth.user_group(user_to_remove.id),
                'read',
                db.organization,
                org.id)
            # remove, also, all rights over the desks in the org.
            desk_perms = [
                'read_desk', 'update_items', 'push_items', 'update_desk']
            for desk_id in org.desks:
                for perm in desk_perms:
                    auth.del_permission(
                        auth.user_group(user_to_remove.id),
                        perm,
                        db.desk,
                        desk_id
                    )
        redirect(URL('org', 'members', args=[org.id]))

    return locals()
开发者ID:ybenitezf,项目名称:nstock,代码行数:60,代码来源:org.py

示例7: diff

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def diff():
    """
    Show the diff betwen the actual item and the archive one
    """
    item = application.getItemByUUID(request.args(0))
    if item is None:
        raise HTTP(404)
    item_archive = db.item_archive(request.args(1))
    if item_archive is None:
        raise HTTP(503)

    fields = []
    fields_archived = []

    # allow view of administrative metadata
    db.item.modified_by.readable = True
    db.item.modified_on.readable = True
    db.item_archive.modified_by.readable = True
    db.item_archive.modified_on.readable = True

    for f in db.item:
        if item[f.name] != item_archive[f.name]:
            f.comment = None
            fields.append(f)
            db.item_archive[f.name].comment = None
            fields_archived.append(db.item_archive[f.name])

    # build two readonly forms
    form_actual = SQLFORM.factory(
        *fields,
        record=item,
        readonly=True,
        showid=False,
        formstyle='divs'
        )
    form_archive = SQLFORM.factory(
        *fields_archived,
        record=item_archive,
        readonly=True,
        showid=False,
        formstyle='divs')

    return dict(item=item, form_actual=form_actual, form_archive=form_archive)
开发者ID:ybenitezf,项目名称:nstock,代码行数:45,代码来源:item.py

示例8: editar_usuario

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def editar_usuario():
    u"""Edição ou deleção de um usuário.

    Permite que um usuário com permissão de admin edite ou apague um usuário.
    Observação: Não é possível editar a senha de um usuário.
    """
    user_id = current.request.args(0, cast=int,
                                   otherwise=URL('default', 'index'))
    db = current.globalenv['db']
    query = db.auth_user.id == user_id
    query &= db.auth_user.id == db.auth_membership.user_id
    user_data = db(query).select(
        db.auth_user.first_name,
        db.auth_user.last_name,
        db.auth_user.email,
        db.auth_membership.group_id,
    ).first()

    for campo, valor in user_data.auth_user.items():
        db.auth_user[campo].default = valor
    for campo, valor in user_data.auth_membership.items():
        db.auth_membership[campo].default = valor
    db.auth_user.email.requires = IS_EMAIL(
        error_message=current.T('Email inválido!')
    )
    db.auth_user.password.writable = False
    db.auth_user.password.readable = False
    db.auth_membership.user_id.writable = False
    db.auth_membership.user_id.readable = False
    form_update = SQLFORM.factory(
        db.auth_user,
        db.auth_membership,
        Field('apagar', 'boolean', default=False, label='Marque para apagar'),
        submit_button="Enviar"
    )

    if form_update.process().accepted:
        if form_update.vars.apagar:
            db(db.auth_user.id == user_id).delete()
            db(db.auth_membership.user_id == user_id).delete()
            current.session.flash = current.T('Usuário apagado com sucesso!')
            redirect(URL('admin', 'listar_usuarios'))

        db(db.auth_user.id == user_id).update(
            **db.auth_user._filter_fields(form_update.vars)
        )
        db(db.auth_membership.user_id == user_id).update(
            **db.auth_membership._filter_fields(form_update.vars)
        )
        current.session.flash = current.T('Usuário editado com sucesso!')
        redirect(URL('admin', 'listar_usuarios'))

    return {'form_update': form_update}
开发者ID:augustopedro,项目名称:marolo,代码行数:55,代码来源:admin.py

示例9: gather_from_field

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def gather_from_field(tablename, fieldname, regex_str, exclude,
                      filter_func=None, unique=True):
    """
    Return a list of all strings satisfying the supplied regex.

    The fieldnames argument should be a list, so that multiple target fields
    can be searched at once.

    The optional 'unique' keyword argument determines whether duplicates will
    be removed from the list. (Defaults to True.)

    The optional 'filterfunc' keyword argument allows a function to be passed
    which which will be used to alter the gathered strings. This alteration will
    happen before duplicate values are removed. So, for example, the strings
    can be normalized for case or accent characters if those variations are
    not significant.
    """

    db = current.db
    form = SQLFORM.factory(Field('target_field'),
                           Field('target_table'),
                           Field('filter_func'),
                           Field('trans_func'),
                           Field('write_table'),
                           Field('write_field'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        filter_func = eval(vv.filter_func) if vv.filter_func else None
        trans_func = eval(vv.trans_func) if vv.trans_func else None

        items = []
        rows = db(db[vv.target_table].id > 0).select()
        for r in rows:
            items.append(r['target_field'])

        if filter_func:
            items = filter(filter_func, items)
        if trans_func:
            items = [trans_func(i) for i in items]
        if vv.unique:
            items = list(set(items))
        items = [i for i in items if i not in exclude]

    elif form.errors:
        items = BEAUTIFY(form.errors)

    return form, items
开发者ID:mbelletti,项目名称:plugin_utils,代码行数:52,代码来源:plugin_utils.py

示例10: new

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
    def new(self):
        if not self.session.auth:
            redirect(self.CURL('default', 'user', args='login', vars=dict(_next=self.CURL('article', 'new', args=self.request.args))))
        arg = self.request.args(0)
        query = self.db.content_type.identifier == arg
        content_type = self.db(query).select().first() or redirect(self.CURL('home', 'index'))
        self.context.viewname = content_type.viewname
        content = self.define_content_type(content_type.classname)
        path = os.path.join(self.request.folder, 'uploads/')
        if not self.request.env.web2py_runtime_gae:
            self.db.article.picture.uploadfolder = path
            self.db.article.thumbnail.uploadfolder = path
        else:
            self.db.article.picture.uploadfield = "picture_blob"
            self.db.article.thumbnail.uploadfield = "thumbnail_blob"
        self.db.article.author.default = self.session.auth.user.id
        self.db.article.thumbnail.compute = lambda r: THUMB2(r['picture'], gae=self.request.env.web2py_runtime_gae)
        self.db.article.medium_thumbnail.compute = lambda r: THUMB2(r['picture'], gae=self.request.env.web2py_runtime_gae, nx=400, ny=400, name='medium_thumb')

        self.db.article.content_type_id.default = content_type.id
        category_set = self.db(self.db.Category.content_type == content_type.id)
        self.db.article.category_id.requires = IS_IN_DB(category_set, self.db.Category.id, "%(name)s")
        self.context.form = SQLFORM.factory(self.db.article, content.entity, table_name="article", formstyle='divs', separator='')
        self.context.customfield = customfield
        if self.context.form.process().accepted:
            try:
                article_id = self.db.article.insert(**self.db.article._filter_fields(self.context.form.vars))
                self.context.form.vars.article_id = article_id
                self.context.form.vars.type_id = content_type.id
                content_id = content.entity.insert(**content.entity._filter_fields(self.context.form.vars))
                if not content_id:
                    raise Exception("Content not added")
            except Exception:
                self.db.rollback()
                self.response.flash = self.T("error including %s." % content_type.title)
            else:
                self.db.commit()
                self.session.flash = self.T("%s included." % content_type.title)
                self.context.article = self.db.article[article_id]
                self.context.article.update_record(search_index="|".join(str(value) for value in self.context.form.vars.values()))

                if not self.context.article.draft:
                    self.new_article_event('new_article')
                    count = int(self.context.article.author.articles) + 1
                    self.context.article.author.update_record(articles=count)
                else:
                    count = int(self.context.article.author.draft_articles) + 1
                    self.context.article.author.update_record(draft_articles=count)

                redirect(self.CURL('article', 'show', args=[article_id, IS_SLUG()(self.context.form.vars.title)[0]]))
开发者ID:kaiquewdev,项目名称:Movuca,代码行数:52,代码来源:article.py

示例11: create

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def create():
    """
    Create a Item of a given content type
    """
    item_type = request.args(0)
    ct = application.getContentType(item_type)
    if ct is None:
        raise HTTP(404)

    fields = [
        db.item.headline,
        db.item.keywords,
        db.item.genre,
        db.item.item_type,
    ]
    db.item.item_type.default = item_type
    db.item.item_type.writable = False
    db.item.item_type.readable = False

    # aks for preconditions:
    cond, values = ct.check_create_conditions()

    if cond is False:
        user_desk = application.getUserDesk()
        if 'message' in values.keys():
            message = values['message']
        else:
            message = T('Some conditions for the item creation are not met.')
        session.flash = message
        redirect(URL('desk', 'index.html', args=[user_desk.id]))

    else:
        # get the proposed values and initialize the form
        if 'headline' in values.keys():
            db.item.headline.default = values['headline']
        if 'keywords' in values.keys():
            db.item.keywords.default = values['keywords']
        if 'genre' in values.keys():
            db.item.genre.default = values['genre']

    form = SQLFORM.factory(*fields, submit_button=T("Continue"))

    if form.process(dbio=False).accepted:
        item_id = application.createItem(item_type, form.vars)
        application.indexItem(item_id)
        redirect(application.getItemURL(item_id))

    return locals()
开发者ID:ybenitezf,项目名称:nstock,代码行数:50,代码来源:item.py

示例12: make_rows_from_field

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def make_rows_from_field():
    """
    Use values from one table to create new records in another.

    The strings provided for

    The values for source_fields, target_fields, filter_funcs, and
    transform_funcs will be aligned by index.
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('target_table'),
                           Field('source_table'),
                           Field('source_fields', 'list:string'),
                           Field('target_fields', 'list:string'),
                           Field('filter_funcs', 'list:string'),
                           Field('trans_funcs', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        sourcerows = db(db[vv.target_table].id > 0).select()
        out = []
        for srow in sourcerows:
            trow = []
            for idx, f in enumerate(vv.source_fields):
                tval = vv.trans_funcs[idx](srow[f]) \
                    if len(vv.trans_funcs) > idx else srow[f]
                if len(vv.filter_funcs) > idx:
                    if not vv.filter_funcs[idx](tval):
                        tval = None
                if tval:
                    trow[vv.target_fields[idx]] = tval
            out.append(trow)

        if vv.unique:
            out = list(set(out))
        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
开发者ID:mbelletti,项目名称:plugin_utils,代码行数:47,代码来源:plugin_utils.py

示例13: make_rows_from_filenames

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def make_rows_from_filenames():
    """
    TODO: unfinished
    """
    db = current.db
    out = []
    form = SQLFORM.factory(Field('folder_path'),
                           Field('target_field'),
                           Field('target_table'),
                           Field('filter_func'),
                           Field('extra_fields', 'list:string'),
                           Field('unique', 'boolean', default=True),
                           Field('testing', 'boolean', default=True))

    if form.process().accepted:
        vv = form.vars
        mypath = vv.folder_path
        fullpath = os.path.join()
        dirpath, dirnames, filenames = os.walk(mypath).next()
        xfield, xfunc = tuple([(x[0].strip(), x[1].strip()) for x in vv.extra_fields.split(',')])
        if xfunc:
            xfunc = eval(xfunc)
        filter_func = eval(vv.filter_func)

        out = []
        for f in filenames:
            kwargs = {}
            kwargs[vv.target_field] = f
            if xfunc:
                kwargs[xfield] = xfunc(f)
            if filter_func and not filter_func(f):
                kwargs = None
            if kwargs:
                out.append(kwargs)

        if not vv.testing:
            db[vv.target_table].bulk_insert(out)

    elif form.errors:
        out = BEAUTIFY(form.errors)

    return form, out
开发者ID:mbelletti,项目名称:plugin_utils,代码行数:44,代码来源:plugin_utils.py

示例14: print_rows_as_dicts

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def print_rows_as_dicts():
    """docstring for print_select"""
    db = current.db
    message = 'Click to display the query result as a list of dictionaries.'
    form = SQLFORM.factory(Field('table', 'str'),
                           Field('field', 'str'),
                           Field('value', 'str'),
                           Submit='Evaluate')
    if form.process().accepted:
        tbl = form.vars.table
        fld = form.vars.field
        val = literal_eval(form.vars.value)
        rows = db(db[tbl][fld] == val).select().as_list()
        if not rows:
            rows = db(db[tbl][fld] == int(val)).select().as_list()
        message = rows
    elif form.errors:
        message = BEAUTIFY(form.errors)
    print message
    return form, message
开发者ID:mbelletti,项目名称:plugin_utils,代码行数:22,代码来源:plugin_utils.py

示例15: create

# 需要导入模块: from gluon import SQLFORM [as 别名]
# 或者: from gluon.SQLFORM import factory [as 别名]
def create():
    if not session.marked_items:
        session.flash = T('You must mark some items first')
        redirect(URL('default', 'index'))

    fields = []
    # i need the input of the based item fields
    fdl_headline = db.item.headline
    fields.append(fdl_headline)
    fdl_keywords = db.item.keywords
    keywords_list = []
    for item_id in session.marked_items:
        _item = application.getItemByUUID(item_id)
        keywords_list.extend(_item.keywords)
    keywords_list = list(set(keywords_list))  # remove any dup
    fdl_keywords.default = keywords_list
    fields.append(fdl_keywords)
    fields.append(db.item.genre)
    fdl_item_type = db.item.item_type
    fdl_item_type.writable = False
    fdl_item_type.readable = False
    fdl_item_type.default = 'package'
    fields.append(db.plugin_package_content.description)

    form = SQLFORM.factory(
        *fields,
        table_name='plugin_package_item'  # to allow the correct file name
    )

    if form.process(dbio=False).accepted:
        form.vars.item_id = application.createItem('package', form.vars)
        form.vars.item_list = session.marked_items
        db.plugin_package_content.insert(
            **db.plugin_package_content._filter_fields(form.vars)
        )
        application.indexItem(form.vars.item_id)
        session.marked_items = []
        redirect(URL('default', 'index'))

    return locals()
开发者ID:ybenitezf,项目名称:nstock,代码行数:42,代码来源:plugin_package.py


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