ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Flask框架学习(一)

2021-04-14 16:32:49  阅读:177  来源: 互联网

标签:框架 Flask app rule 学习 my hello 模板


一、简介

Flask是一款基于python的简单web框架。Flask基于Werkzeug WSGI工具包和Jinja2模板引擎。

WSGI(Web Server Gateway Interface), web服务器网管接口,已被用作python web应用程序开发的标准。WSGI是web服务器和web应用程序之间通用接口的规范。

Werkzeug是一个WSGI工具包,它实现了请求,响应对象和实用函数。这使得能够在其上构建web框架。Flask框架使用Werkzeug作为其基础之一。

Jinja2是一个流行的模板引擎。web模板系统将模板与特定数据源组合以呈现动态网页。

Flask通常被称为微框架,它旨在保持应用程序的核心简单且可扩展。Flask没有用于数据库处理的内置抽象层,也没有形成验证支持。相反,Flask支持扩展以向应用程序添加此类功能。

二、flask环境

练习环境windows

默认安装好python环境,并配置好环境变量。打开dos窗口,使用如下命令安装:

pip install Flask

安装完成,界面提示安装成功。打开python IDE工具,我这常用的是PyCharm,新建一个python文件。demo如下:

 1 from flask import Flask
 2 
 3 app = Flask(__name__)
 4 """
 5 必须在程序前导入flask包的Flask类,Flask类的一个实例对象是WSGI应用程序,创建一个程序对象app。
 6 Flask(__name__)意思是使用当前模块的名称作为参数
 7 """
 8 
 9 @app.route('/')
10 def hello_world1():
11 """
12 app.route(rule, **options)函数是一个装饰器,给定URL规则与调用的相关函数。
13     - rule参数表示与该函数的URL绑定
14     - options参数表示要转发给基础Rule对象的参数列表
15 """
16     return 'hello world!'
17 
18 if __name__ == '__main__':
19     app.run(debug=True)

“/”URL与hello_world1()函数绑定。当运行服务,在浏览器中打开web服务器主页时,将呈现该函数的输出。最后,Flask类的run()方法在本地开发服务器上运行应用程序。

app.run(host, port, debug, options)

运行结果:

 

 服务运行现况:

在运行时将参数debug属性设置为True来启用Debug模式,代码进行修改时,服务直接生效,无需重启服务。

三、flask路由

路由功能是web框架中一个很重要的功能,它将不同的请求转发给不同的函数处理。本质就是URL与该URL要调用的视图函数的绑定关系。

 1 # 源文件中route()方法的代码
 2 def route(self, rule, **options):
 3         """A decorator that is used to register a view function for a
 4         given URL rule.  This does the same thing as :meth:`add_url_rule`
 5         but is intended for decorator usage::
 6 
 7             @app.route('/')
 8             def index():
 9                 return 'Hello World'
10 
11         For more information refer to :ref:`url-route-registrations`.
12 
13         :param rule: the URL rule as string
14         :param endpoint: the endpoint for the registered URL rule.  Flask
15                          itself assumes the name of the view function as
16                          endpoint
17         :param options: the options to be forwarded to the underlying
18                         :class:`~werkzeug.routing.Rule` object.  A change
19                         to Werkzeug is handling of method options.  methods
20                         is a list of methods this rule should be limited
21                         to (``GET``, ``POST`` etc.).  By default a rule
22                         just listens for ``GET`` (and implicitly ``HEAD``).
23                         Starting with Flask 0.6, ``OPTIONS`` is implicitly
24                         added and handled by the standard request handling.
25         """
26 
27         def decorator(f):
28             endpoint = options.pop("endpoint", None)
29             self.add_url_rule(rule, endpoint, f, **options)
30             return f
31 
32         return decorator

app对象的add_url_rule()函数也可用于将URL与函数绑定。写法上,装饰器这种用法更常用。

1 @app.route('/hello')
2 def hello_world():
3         return 'hello world!'
1 def hello_world():
2         return 'hello world'
3 app.add_url_rule('/', 'hello', hello_world)

以上两个程序段实现相同的功能。

四、flask模板

在前面的实例中,视图函数的主要作用是生成请求的响应,这是最简单请求.实际上,视图函数有两个作用:

  • 处理业务逻辑
  • 返回响应内容

在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本.

  • 模板其实是一个包含响应文本的文件,其中用占位符(变量)表示动态部分,告诉模板引擎其具体的值需要从使用的数据中获取
  • 使用真实值替换变量,再返回最终得到的字符串,这个过程称为'渲染'
  • Flask 是使用 Jinja2 这个模板引擎来渲染模板

使用模板的好处

  • 视图函数只负责业务逻辑和数据处理(业务逻辑方面)
  • 而模板则取到视图函数的数据结果进行展示(视图展示方面)
  • 代码结构清晰,耦合度低

模板的基本使用

在项目下创建 templates 文件夹,用于存放所有模板文件,并在目录下创建一个模板文件 html 文件 hello.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 我的模板html内容
 9 </body>
10 </html>

创建视图函数,将该模板内容进行渲染返回

1 from flask import Flask, render_template
2 
3 app = Flask(__name__)
4 
5 @app.route('/')
6 def index():
7     return render_template('hello.html')

模板变量

代码中传入字符串,列表,字典到模板中

 1 from flask import Flask, render_template
 2 
 3 app = Flask(__name__)
 4 
 5 @app.route('/')
 6 def index():
 7     # 往模板中传入的数据
 8     my_str = 'Hello Word'
 9     my_int = 10
10     my_array = [3, 4, 2, 1, 7, 9]
11     my_dict = {
12         'name': 'xiaoming',
13         'age': 18
14     }
15     return render_template('hello.html',
16                            my_str=my_str,
17                            my_int=my_int,
18                            my_array=my_array,
19                            my_dict=my_dict
20                            )

模板中代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6 </head>
 7 <body>
 8   我的模板html内容
 9   <br />{{ my_str }}
10   <br />{{ my_int }}
11   <br />{{ my_array }}
12   <br />{{ my_dict }}
13 </body>
14 </html>

运行效果

1 我的模板html内容
2 Hello Word
3 10
4 [3, 4, 2, 1, 7, 9]
5 {'name': 'xiaoming', 'age': 18}

 

标签:框架,Flask,app,rule,学习,my,hello,模板
来源: https://www.cnblogs.com/marvintester/p/14658513.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有