• 技术文章 >Python框架 >Flask

    flask中模板引擎怎么用?

    小妮浅浅小妮浅浅2021-02-21 11:13:29原创7425

    在我们对flask的一些引擎使用时,就不得不提到其中的一个默认引擎了。有些初学flask的人对Jinja2还没有使用过,所以不知道该从何下手。本篇对于这种默认的引擎使用进行了整理,有对flask模板引擎感兴趣的,可以跟着我们一起来看看Jinja2的基础操作,具体的内容如下展开。

    1、flask默认的模板引擎是Jinja2

    目录结构:

    1

    2

    3

    /application.py

    /templates

        /oscuser.html

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    application.py

    #coding=utf-8

    __author__ = 'duanpeng'

      

      

    import MySQLdb

    from  flask import  Flask,request,render_template,session, redirect, url_for, escape

    app = Flask(__name__,static_folder='static',static_url_path='/static')

      

      

    #定义首页

    @app.route('/')

    def hello_world():

         user_agent = request.headers.get('User-Agent')

         return 'welcom! ,you browser is %s' % user_agent

      

      

    #定义404错误页面

    @app.errorhandler(404)

    def not_found(error):

        return render_template('error.html'), 404

      

      

      

    #定义动态页面

    @app.route('/user/<username>')

    def show_user_profile(username):

        # show the user profile for that user

        return 'User %s' % username

      

    #限制请求方式

    @app.route('/sayHello',methods=['post'])

    def sayHello():

         return "hello,who are you?"

    #限制请求只能为get方式

    @app.route('/touch',methods=['get'])

    def touch():

         return render_template('bank.html')

      

      

    #我的账号页面,与数据库交互,实现动态数据处理

    @app.route('/myaccount',methods=['get'])

    def mydata():

        try:

            #加载驱动 连接数据库    host ->ip port->端口

            conn = MySQLdb.connect(host='192.168.1.124',user='root',passwd='abcdef',db='abcdef',port=3306,charset='gb2312')

            cursor = conn.cursor()

            cursor.execute("select * from osc_users t where t.login_name = 'rainbow07693'")

            result  = cursor.fetchone()

            print(result[4])

            cursor.close()

            conn.close()

            return render_template('oscuser.html',userinfo=result)

        except MySQLdb.Error,e:

            print e

      

      

      

    if __name__ == '__main__':

    app.run(debug=True)

    以上就是flask中模板引擎的使用,相信大家已经对Jinja2的用法有了一定的认识。平时在课后也可以找有关的资料进行深入学习。更多Python框架指路:Flask

    专题推荐:flask模板引擎
    上一篇:Flask中SQLAlchemy配置SQLite 下一篇:flask中如何对数据库进行管理

    相关文章推荐

    • django框架和flask哪个简单?怎么用?• 如何比较python中的flask和django?• 如何使用Python的Flask框架开发web?• Flask框架的概念及特点

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网