Python之路,Day05-构建一个Web应用

本节内容

1、回顾:Python你已经知道了甚么?

2、构建一个Web应用的流程

3、安装Flask

4、Flask的工作原理

5、路由规则、url构建

6、http方法

7、静态文件

8、渲染模板

9、在html页面中加载静态资源

 

1、回顾:Python你已经知道了甚么?

 

 

 

2、构建一个Web应用的流程

 

 

 

 

 3、安装Flask

在使用pycharm中创建Flask:

第一种方法:

1.可以先建Pure Python

 

然后在项目python环境中添加flask环境:

 

在project:201909 中install Package <==>在命令行创建一个envy 201909环境,然后 pip install flask

 

第二种方法:

可以直接在pycharm中创建flask项目

 

 4、Flask的工作原理

 

 1 # -*- coding:utf-8 -*-
 2 # Author:Zhichao
 3 
 4 from flask import Flask
 5 
 6 app = Flask(__name__)
 7 
 8 
 9 @app.route('/')
10 def hello() -> str:
11     """向web打招呼"""
12     return 'Hello world from Flask'
13 
14 app.run(debug=True)
Flask基本原理
"""The flask object implements a WSGI application and acts as the central
object. It is passed the name of the module or package of the
application. Once it is created it will act as a central registry for
the view functions, the URL rules, template configuration and much more.

The name of the package is used to resolve resources from inside the
package or the folder the module is contained in depending on if the
package parameter resolves to an actual python package (a folder with
an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).

For more information about resource loading, see :func:`open_resource`."""

 

 



app.run()参数介绍:
   def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):


 5、路由规则、url构建

参考:https://flask.palletsprojects.com/

     http://www.pythondoc.com/flask/index.html

5.1 路由

现代 web 应用都使用有意义的 URL ,这样有助于用户记忆,网页会更得到用户的青睐, 提高回头率。

使用 route() 装饰器来把函数绑定到 URL:

1 @app.route('/')
2 def index():
3     return 'Index Page'
4 
5 @app.route('/hello')
6 def hello():
7     return 'Hello, World'

 

5.2 变量规则

 

通过把 URL 的一部分标记为 <variable_name> 就可以在 URL 中添加变量。标记的

部分会作为关键字参数传递给函数。通过使用 <converter:variable_name> ,可以

选择性的加上一个转换器,为变量指定规则。请看下面的例子:

 1 # -*- coding:utf-8 -*-
 2 # Author:Zhichao
 3 
 4 from flask import Flask, url_for
 5 
 6 app = Flask(__name__)
 7 
 8 @app.route('/')
 9 def hello() -> str:
10     """向web打招呼"""
11     return 'Hello world from Flask'
12 
13 @app.route('/about')
14 def about():
15     """show the user about for that user"""
16     return 'The about page'
17 
18 @app.route('/projects/')
19 def projects():
20     """show the user projects for that user"""
21     return 'The project page'
22 
23 @app.route('/user/<username>')
24 def show_user_profile(username):
25     """show the user profile for that user"""
26     return 'User %s' % username
27 
28 @app.route('/post/<string:post_username>/<int:post_id>')
29 def show_post(post_username, post_id):
30     """show the post with the given id, the id is an integer"""
31     return 'Username %s id %d' % (post_username, post_id)
32 
33 @app.route('/path/<path:subpath>')
34 def show_subpath(subpath):
35     """show the subpath after /path/"""
36     return 'Subpath %s' % subpath
37 
38 app.run(debug=True)

 

5.3 唯一的 URL / 重定向行为

以下两条规则的不同之处在于是否使用尾部的斜杠 '/':

1 @app.route('/projects/')
2 def projects():
3     return 'The project page'
4 
5 @app.route('/about')
6 def about():
7     return 'The about page'

projects的URL是中规中矩的,尾部有一个斜杠,看起来就如同一个文件夹。访问一个没有斜杠结尾的URL时Flask会自动进行重定向,帮你在尾部加上一个斜杠。

about的URL没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这个URL时添加了尾部斜杠就会得到一个 404 错误。这样可以保持URL唯一,并帮助搜索引擎避免重复索引同一页面。

5.4 URL 构建

为什么不在把 URL 写死在模板中,而要使用反转函数 url_for() 动态构建?

  1. 反转通常比硬编码 URL 的描述性更好。

  2. 你可以只在一个地方改变 URL ,而不用到处乱找。

  3. URL 创建会为你处理特殊字符的转义和 Unicode 数据,比较直观。

  4. 生产的路径总是绝对路径,可以避免相对路径产生副作用。

  5. 如果你的应用是放在 URL 根路径之外的地方(如在 /myapplication 中,不在 / 中), url_for() 会为你妥善处理。

 1 from flask import Flask, escape, url_for
 2 
 3 app = Flask(__name__)
 4 
 5 @app.route('/')
 6 def index():
 7     return 'index'
 8 
 9 @app.route('/login')
10 def login():
11     return 'login'
12 
13 @app.route('/user/<username>')
14 def profile(username):
15     return '{}\'s profile'.format(escape(username))
16 
17 with app.test_request_context():
18     print(url_for('index'))
19     print(url_for('login'))
20     print(url_for('login', next='/'))
21     print(url_for('profile', username='John Doe'))

 

 6.HTTP方法

 根据 HTTP 标准,HTTP 请求可以使用多种请求方法。

 

比较 GET 与 POST

 

 

 

 

 

 

 

 

 

 

 

posted @ 2019-10-20 16:13  智超(Zhichao)  阅读(1832)  评论(0编辑  收藏  举报