Python Web

BootStrap-Flask使用指南

2020-01-10  本文已影响0人  北邮郭大宝

BootStrap-Flask是《Flask Web 开发实战》作者李辉维护的一个小工具,旨在提供Bootstrap和Flask集成的宏,可以快速构建自己的Web项目。这里简单介绍一下使用方法。

1.安装和初始化

$ pip install bootstrap-flask

​初始化和其他组件一样

from flask_bootstrap import Bootstrap
from flask import Flask
​
app = Flask(__name__)
​
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
​
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'secret string')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.root_path, 'data.db')

2. 宏定义

BootStrap-Flask主要提供的宏有如下几个:


1578409827787.jpg

下面挑几个常用的介绍一下,其他的可以参考其文档。

2.1 导航栏

使用方法:

render_nav_item(endpoint, text, badge='', use_li=False, **kwargs)

demo:

{% extends 'base.html' %}
{% from 'bootstrap/nav.html' import render_nav_item %}
​
{% block title %}  BootStrap-Flask nav {% endblock title%}
​
{% block content %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="navbar-nav mr-auto">
        {{ render_nav_item('index', 'Home') }}
        {{ render_nav_item('breadcrumb', 'Breadcrumb') }}
        {{ render_nav_item('field', 'Field') }}
        {{ render_nav_item('form', 'Form') }}
        {{ render_nav_item('form_row', 'Form_Row') }}
        {{ render_nav_item('message', 'Flash') }}
        {{ render_nav_item('pager', 'Pager') }}
    </div>
</nav>
{% endblock content %}

效果:


1578567031904.jpg

2.2 表单1

使用方法:
render_form(form, action="", method="post", extra_classes=None, role="form", form_type="basic", horizontal_columns=('lg', 2, 10), enctype=None, button_map={}, id="", novalidate=False, render_kw={})

demo:

class Login(FlaskForm):
    username = StringField('Name', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit = SubmitField('Submit')
    
@app.route('/form')
def form():
    form = Login()
    return render_template('form.html', form=form)
{% extends 'base.html' %}
{% from 'bootstrap/form.html' import render_form %}
​
{% block title %}  BootStrap-Flask Form {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_form example</h3>
    <div >
        {{ render_form(form, button_map={'submit': 'success'}) }}
    </div>
</div>
{% endblock content %}

效果:


1578567431266.jpg

2.3 表单2

使用方法:
render_form_row(fields, row_class='form-row', col_class_default='col', col_map={})

demo:

class Login2(FlaskForm):
    username = StringField('Name', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    email = StringField('Email', validators=[DataRequired(), email()])
    remember = BooleanField('Remember', default=True)
    submit = SubmitField('Submit')
​
@app.route('/form_row')
def form_row():
    form = Login2()
    return render_template('form_row.html', form=form)
{% extends 'base.html' %}
{% from 'bootstrap/form.html' import render_form_row %}
​
{% block title %}  BootStrap-Flask  {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_form_row example</h3>
    <form method="post">
        {{ form.csrf_token() }}
        {{ render_form_row([form.username, form.password], col_map={'username': 'col-md-4'}) }}
        {{ render_form_row([form.email]) }}
        {{ render_form_row([form.remember]) }}
        {{ render_form_row([form.submit]) }}
</form>
</div>
{% endblock content %}

效果:


1578568397001.jpg

2.4 分页符

使用方法:
render_pager(pagination, fragment='', prev=('<span aria-hidden="true">←</span> Previous')|safe, next=('Next <span aria-hidden="true">→</span>')|safe, align='', **kwargs)

demo:

app.config['STUDENT_PER_PAGE'] = 5
​
class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30))
​
@app.route('/pager')
def pager():
    page = request.args.get('page', 1, type=int)
    per_page = app.config['STUDENT_PER_PAGE']
    pagination = Student.query.order_by(Student.id.asc()).paginate(page, per_page=per_page)
    students = pagination.items
    return render_template('pager.html', pagination=pagination, students=students)
{% extends 'base.html' %}
{% from 'bootstrap/pagination.html' import render_pager %}
​
{% block title %}  BootStrap-Flask Pager {% endblock title%}
​
{% block content %}
<div style="margin: 100px">
    <h3>render_pager example</h3>
    <div>
        {% if students %}
            {% for student in students %}
                <h3 class="text-primary"><p>{{ student.username }}</p></h3>
            {% endfor %}
        {% endif %}
    </div>
    {{ render_pager(pagination, prev='上一页', next='下一页', align='center') }}
</div>
{% endblock content %}

效果:


1578568611135.jpg

3. 总结

总体使用还是比较方便的,主要是对于不想花过多时间投入到前端Web开发来说,是比较好的工具。详细的信息可以参阅其文档:https://bootstrap-flask.readthedocs.io/en/latest/

上一篇下一篇

猜你喜欢

热点阅读