Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 问题编号:, “客户端id”:客户端计数器, “date”:fake.date\u time\u此\u十年(在\u now=True之前,在\u now=False之后,tzinfo=None) }) 对于范围内的文章计数器(0,每期文章数): 附加条款({ “id”:(每期文章数量*发行id)+文章计数器, “问题id”:问题id, 'title':'{}-{}'。格式(client_title,fake.catch_phrase()), 'body':'{}-{}'。格式(client_title,fake.text(max_nb_chars=200)) }) db.session.bulk\u insert\u映射(客户端,客户端) db.session.bulk\u insert\u映射(问题,问题) db.session.bulk\u insert\u映射(文章,文章) db.session.commit() 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 构建示例数据库() app.run(debug=True)_Python_Flask_Sqlalchemy_Flask Admin - Fatal编程技术网

Python 问题编号:, “客户端id”:客户端计数器, “date”:fake.date\u time\u此\u十年(在\u now=True之前,在\u now=False之后,tzinfo=None) }) 对于范围内的文章计数器(0,每期文章数): 附加条款({ “id”:(每期文章数量*发行id)+文章计数器, “问题id”:问题id, 'title':'{}-{}'。格式(client_title,fake.catch_phrase()), 'body':'{}-{}'。格式(client_title,fake.text(max_nb_chars=200)) }) db.session.bulk\u insert\u映射(客户端,客户端) db.session.bulk\u insert\u映射(问题,问题) db.session.bulk\u insert\u映射(文章,文章) db.session.commit() 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 构建示例数据库() app.run(debug=True)

Python 问题编号:, “客户端id”:客户端计数器, “date”:fake.date\u time\u此\u十年(在\u now=True之前,在\u now=False之后,tzinfo=None) }) 对于范围内的文章计数器(0,每期文章数): 附加条款({ “id”:(每期文章数量*发行id)+文章计数器, “问题id”:问题id, 'title':'{}-{}'。格式(client_title,fake.catch_phrase()), 'body':'{}-{}'。格式(client_title,fake.text(max_nb_chars=200)) }) db.session.bulk\u insert\u映射(客户端,客户端) db.session.bulk\u insert\u映射(问题,问题) db.session.bulk\u insert\u映射(文章,文章) db.session.commit() 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': 构建示例数据库() app.run(debug=True),python,flask,sqlalchemy,flask-admin,Python,Flask,Sqlalchemy,Flask Admin,下面是一个使用SQLite的单个文件示例: 主要是简单的烧瓶,SQLalchemy和烧瓶管理员。感兴趣的类别是FilterByClientTitle class FilterByClientTitle(BaseSQLAFilter): # Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI def app

下面是一个使用SQLite的单个文件示例:

主要是简单的烧瓶,SQLalchemy和烧瓶管理员。感兴趣的类别是
FilterByClientTitle

class FilterByClientTitle(BaseSQLAFilter):
    # Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI
    def apply(self, query, value, alias=None):
        return query.join(Article.issue).join(Issue.client).filter(Client.title == value)

    # readable operation name. This appears in the middle filter line drop-down
    def operation(self):
        return u'equals'

    # Override to provide the options for the filter - in this case it's a list of the titles of the Client model
    def get_options(self, view):
        return [(client.title, client.title) for client in Client.query.order_by(Client.title)]
文章模型的视图有两个重要的设置/覆盖:

class ArticleView(BaseAdminView):

    # ......

    # No need to specify the column as we'll set the SQLalchemy filter directly in the filter's apply method
    column_filters = [FilterByClientTitle(column=None, name='Client Title')]

    # Need this so the filter options are always up-to-date
    @expose('/')
    def index_view(self):
        self._refresh_filters_cache()
        return super(ArticleView, self).index_view()
以下是完整的示例,需要随机数据库:

import datetime
from flask import Flask, url_for
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy

from flask_admin import Admin, expose
from faker import Faker

from flask_admin.contrib.sqla.filters import BaseSQLAFilter
from markupsafe import Markup

app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db.sqlite'
db = SQLAlchemy(app)


@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


class Client(db.Model):
    __tablename__ = 'clients'
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(1000))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.title


class Issue(db.Model):
    __tablename__ = 'issues'
    id = db.Column(db.Integer(), primary_key=True)
    date = db.Column(db.Date, default=datetime.date.today())
    client_id = db.Column(db.Integer(), db.ForeignKey('clients.id'), nullable=False)
    client = db.relationship(Client,  backref=db.backref('issues', uselist=True, cascade='all, delete-orphan'))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return unicode(self.date)


class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String())
    body = db.Column(db.String())
    issue_id = db.Column(db.Integer(), db.ForeignKey('issues.id'), nullable=False)
    issue = db.relationship(Issue, backref=db.backref('articles', uselist=True, cascade='all, delete-orphan'))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return '{title} ... {body} ...'.format(title=self.title[:30], body=self.body[:30])


class BaseAdminView(ModelView):
    can_view_details = True
    named_filter_urls = True


class ClientView(BaseAdminView):
    column_list = ('id', 'title')
    column_default_sort = ('title', False)
    column_filters = ['id', 'title']


class IssueView(BaseAdminView):
    column_list = ('id', 'date', 'articles')
    column_default_sort = ('date', False)
    column_filters = ['id', 'date']

    column_formatters = {
        'articles': lambda v, c, m, n: Markup('<br>'.join([unicode(a) for a in m.articles])),
    }


class FilterByClientTitle(BaseSQLAFilter):
    # Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI
    def apply(self, query, value, alias=None):
        return query.join(Article.issue).join(Issue.client).filter(Client.title == value)

    # readable operation name. This appears in the middle filter line drop-down
    def operation(self):
        return u'equals'

    # Override to provide the options for the filter - in this case it's a list of the titles of the Client model
    def get_options(self, view):
        return [(client.title, client.title) for client in Client.query.order_by(Client.title)]


class ArticleView(BaseAdminView):
    column_list = ('title', 'body', 'issue', 'issue.client')
    column_labels = {
        'issue': 'Issue Date',
        'issue.client': 'Client Title'
    }
    column_default_sort = ('title', False)

    def issue_link(self, context, model, name):
        return Markup('<a href="{url}" title="Link to Issue">{date}</a>'.format(
            url=url_for('issue.index_view', flt1_id_equals=model.issue.id),
            date=model.issue.date)
        )

    def client_link(self, context, model, name):
        return Markup('<a href="{url}" title="Link to Client">{title}</a>'.format(
            url=url_for('client.index_view', flt1_id_equals=model.issue.client.id),
            title=model.issue.client.title)
        )

    # Display Issue Date and Client Title as links back to their filtered views
    column_formatters = {
        'title': lambda v, c, m, n: '{} ...'.format(m.title[:20]),
        'body': lambda v, c, m, n: '{} ...'.format(m.body[:40]),
        'issue': issue_link,
        'issue.client': client_link,
    }

    # No need to specify the column as we'll set the SQLalchemy filter directly in the filter's apply method
    column_filters = [FilterByClientTitle(column=None, name='Client Title')]

    # Need this so the filter options are always up-to-date
    @expose('/')
    def index_view(self):
        self._refresh_filters_cache()
        return super(ArticleView, self).index_view()


admin = Admin(app, template_mode="bootstrap3")
admin.add_view(ClientView(Client, db.session))
admin.add_view(IssueView(Issue, db.session))
admin.add_view(ArticleView(Article, db.session))


def build_sample_db():
    fake = Faker()
    number_of_clients = 100
    number_of_issues_per_client = 5
    number_of_articles_per_issues = 5
    db.drop_all()
    db.create_all()

    clients = []
    issues = []
    articles = []
    for client_counter in range(0, number_of_clients):
        client_title = fake.last_name()
        clients.append({
            'id': client_counter,
            'title': client_title
        })
        for issue_counter in range(0, number_of_issues_per_client):
            issue_id = number_of_issues_per_client * client_counter + issue_counter
            issues.append({
                'id': issue_id,
                'client_id': client_counter,
                'date': fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None)
            })

            for article_counter in range(0, number_of_articles_per_issues):
                articles.append({
                    'id': (number_of_articles_per_issues * issue_id) + article_counter,
                    'issue_id': issue_id,
                    'title': '{} - {}'.format(client_title, fake.catch_phrase()),
                    'body': '{} - {}'.format(client_title, fake.text(max_nb_chars=200))
                })

    db.session.bulk_insert_mappings(Client, clients)
    db.session.bulk_insert_mappings(Issue, issues)
    db.session.bulk_insert_mappings(Article, articles)
    db.session.commit()


if __name__ == '__main__':
    build_sample_db()
    app.run(debug=True)
导入日期时间
从烧瓶导入烧瓶,url_
从flask_admin.contrib.sqla导入模型视图
从flask_sqlalchemy导入sqlalchemy
从flask_admin导入admin,公开
从冒牌货进口冒牌货
从flask_admin.contrib.sqla.filters导入BaseSQLAFilter
从markupsafe导入标记
app=烧瓶(名称)
#创建虚拟secrey密钥以便我们可以使用会话
app.config['SECRET_KEY']='123456790'
app.config['SQLALCHEMY\u DATABASE\u URI']='sqlite:///sample_db.sqlite'
db=SQLAlchemy(应用程序)
@应用程序路径(“/”)
def index():
返回“”
类客户端(db.Model):
__tablename_uu='客户端'
id=db.Column(db.Integer(),主键=True)
title=db.Column(db.String(1000))
定义(自我):
返回unicode(self).encode('utf-8')
def ___; unicode(自):
返回自己的标题
类别问题(数据库模型):
__tablename_uuu='issues'
id=db.Column(db.Integer(),主键=True)
date=db.Column(db.date,默认为datetime.date.today())
client_id=db.Column(db.Integer(),db.ForeignKey('clients.id'),nullable=False)
client=db.relationship(client,backref=db.backref('issues',uselist=True,cascade='all,delete orphan'))
定义(自我):
返回unicode(self).encode('utf-8')
def ___; unicode(自):
返回unicode(self.date)
类别文章(db.Model):
__tablename_uu='articles'
id=db.Column(db.Integer(),主键=True)
title=db.Column(db.String())
body=db.Column(db.String())
issue_id=db.Column(db.Integer(),db.ForeignKey('issues.id'),nullable=False)
issue=db.relationship(issue,backref=db.backref('articles',uselist=True,cascade='all,delete orphan'))
定义(自我):
返回unicode(self).encode('utf-8')
def ___; unicode(自):
返回“{title}…”。。。{body}…'.format(title=self.title[:30],body=self.body[:30])
类BaseAdminView(模型视图):
can\u view\u details=True
命名的\u过滤器\u URL=True
类ClientView(BaseAdminView):
列列表=('id','title')
列\默认\排序=('title',False)
列过滤器=['id','title']
类发布视图(BaseAdminView):
列列表=('id','date','articles')
列\默认\排序=('date',False)
列过滤器=['id','date']
列\u格式化程序={
“articles”:lambda v,c,m,n:Markup(“
”.join([unicode(a)表示m.articles中的a]), } 类FilterByClientTitle(BaseSQLAFilter): #重写以创建适当的查询,并使用筛选器UI传递的值对所述查询应用筛选器 def apply(自我、查询、值、别名=无): 返回query.join(Article.issue).join(issue.client).filter(client.title==value) #可读操作名。出现在中间的过滤线下拉 def操作(自): 返回“相等” #覆盖以提供过滤器的选项-在本例中,它是客户机模型标题的列表 def get_选项(自身、视图): 返回client.query.order\u by(client.title)中客户的[(client.title,client.title)] 类ArticleView(BaseAdminView): 列列表=('title','body','issue','issue.client') 列_标签={ “发行”:发行日期, “问题.客户”:“客户标题” } 列\默认\排序=('title',False) def问题链接(自身、上下文、模型、名称): 返回标记(“”.format( url=url\u for('issue.index\u view',flt1\u id\u=model.issue.id), 日期=型号。问题。日期) ) def客户端链接(自身、上下文、模型、名称): 返回标记(“”.format( url=url\u for('client.index\u view',flt1\u id\u=model.issue.client.id), title=model.issue.client.title) ) #显示问题日期和客户标题作为链接返回到其筛选视图 列\u格式化程序={ “title”:lambda v,c,m,n:“{}…”。格式(m.title[:20]), “body”:lambda v,c,m,n:“{}…”。格式(m.body[:40]), “问题”:问题链接, 'issue.client':客户端链接, } #无需指定列,因为我们将直接在过滤器的apply方法中设置SQLalchemy过滤器 column_filters=[FilterByClientTitle(column=None,name='Client Title')] #需要此选项,以便过滤器选项始终是最新的 @暴露(“/”) def索引_视图(自): self.\u刷新\u过滤器\u缓存() 返回super(ArticleView,self).index_view() admin=admin(应用程序,模板=“bootstrap3”) 管理添加视图(客户端视图(客户端,数据库会话)) 管理添加视图(发布视图(发布,数据库会话)) 管理添加视图(ArticleView(Article,db.session)) def build_sample_db(): 假 客户机数量=100 每个客户的问题数量=5 每期文章数量=5篇 db.drop_all() db.create_all() 客户=[] 问题=[] 艺术
import datetime
from flask import Flask, url_for
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy

from flask_admin import Admin, expose
from faker import Faker

from flask_admin.contrib.sqla.filters import BaseSQLAFilter
from markupsafe import Markup

app = Flask(__name__)

# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db.sqlite'
db = SQLAlchemy(app)


@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


class Client(db.Model):
    __tablename__ = 'clients'
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(1000))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return self.title


class Issue(db.Model):
    __tablename__ = 'issues'
    id = db.Column(db.Integer(), primary_key=True)
    date = db.Column(db.Date, default=datetime.date.today())
    client_id = db.Column(db.Integer(), db.ForeignKey('clients.id'), nullable=False)
    client = db.relationship(Client,  backref=db.backref('issues', uselist=True, cascade='all, delete-orphan'))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return unicode(self.date)


class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String())
    body = db.Column(db.String())
    issue_id = db.Column(db.Integer(), db.ForeignKey('issues.id'), nullable=False)
    issue = db.relationship(Issue, backref=db.backref('articles', uselist=True, cascade='all, delete-orphan'))

    def __str__(self):
        return unicode(self).encode('utf-8')

    def __unicode__(self):
        return '{title} ... {body} ...'.format(title=self.title[:30], body=self.body[:30])


class BaseAdminView(ModelView):
    can_view_details = True
    named_filter_urls = True


class ClientView(BaseAdminView):
    column_list = ('id', 'title')
    column_default_sort = ('title', False)
    column_filters = ['id', 'title']


class IssueView(BaseAdminView):
    column_list = ('id', 'date', 'articles')
    column_default_sort = ('date', False)
    column_filters = ['id', 'date']

    column_formatters = {
        'articles': lambda v, c, m, n: Markup('<br>'.join([unicode(a) for a in m.articles])),
    }


class FilterByClientTitle(BaseSQLAFilter):
    # Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI
    def apply(self, query, value, alias=None):
        return query.join(Article.issue).join(Issue.client).filter(Client.title == value)

    # readable operation name. This appears in the middle filter line drop-down
    def operation(self):
        return u'equals'

    # Override to provide the options for the filter - in this case it's a list of the titles of the Client model
    def get_options(self, view):
        return [(client.title, client.title) for client in Client.query.order_by(Client.title)]


class ArticleView(BaseAdminView):
    column_list = ('title', 'body', 'issue', 'issue.client')
    column_labels = {
        'issue': 'Issue Date',
        'issue.client': 'Client Title'
    }
    column_default_sort = ('title', False)

    def issue_link(self, context, model, name):
        return Markup('<a href="{url}" title="Link to Issue">{date}</a>'.format(
            url=url_for('issue.index_view', flt1_id_equals=model.issue.id),
            date=model.issue.date)
        )

    def client_link(self, context, model, name):
        return Markup('<a href="{url}" title="Link to Client">{title}</a>'.format(
            url=url_for('client.index_view', flt1_id_equals=model.issue.client.id),
            title=model.issue.client.title)
        )

    # Display Issue Date and Client Title as links back to their filtered views
    column_formatters = {
        'title': lambda v, c, m, n: '{} ...'.format(m.title[:20]),
        'body': lambda v, c, m, n: '{} ...'.format(m.body[:40]),
        'issue': issue_link,
        'issue.client': client_link,
    }

    # No need to specify the column as we'll set the SQLalchemy filter directly in the filter's apply method
    column_filters = [FilterByClientTitle(column=None, name='Client Title')]

    # Need this so the filter options are always up-to-date
    @expose('/')
    def index_view(self):
        self._refresh_filters_cache()
        return super(ArticleView, self).index_view()


admin = Admin(app, template_mode="bootstrap3")
admin.add_view(ClientView(Client, db.session))
admin.add_view(IssueView(Issue, db.session))
admin.add_view(ArticleView(Article, db.session))


def build_sample_db():
    fake = Faker()
    number_of_clients = 100
    number_of_issues_per_client = 5
    number_of_articles_per_issues = 5
    db.drop_all()
    db.create_all()

    clients = []
    issues = []
    articles = []
    for client_counter in range(0, number_of_clients):
        client_title = fake.last_name()
        clients.append({
            'id': client_counter,
            'title': client_title
        })
        for issue_counter in range(0, number_of_issues_per_client):
            issue_id = number_of_issues_per_client * client_counter + issue_counter
            issues.append({
                'id': issue_id,
                'client_id': client_counter,
                'date': fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None)
            })

            for article_counter in range(0, number_of_articles_per_issues):
                articles.append({
                    'id': (number_of_articles_per_issues * issue_id) + article_counter,
                    'issue_id': issue_id,
                    'title': '{} - {}'.format(client_title, fake.catch_phrase()),
                    'body': '{} - {}'.format(client_title, fake.text(max_nb_chars=200))
                })

    db.session.bulk_insert_mappings(Client, clients)
    db.session.bulk_insert_mappings(Issue, issues)
    db.session.bulk_insert_mappings(Article, articles)
    db.session.commit()


if __name__ == '__main__':
    build_sample_db()
    app.run(debug=True)