第十一章:Flask入门之从零构建Python Web应用

Flask简介

基于python的web微框架, 只提供了一个稳健的核心, 其他功能全部是通过扩展实现的, 我们只需要学会各项扩展库的使用

Python 虚拟环境

是基于Python基础环境上虚拟出的一个工作环境, 目的是防止基础环境被污染, 便于项目对包的管理

虚拟环境管理方法

复制代码
#### virtualenv
复制代码
#### Virtualenvwrapper
复制代码
#### conda
复制代码
#### pipenv

安装

复制代码
#### `pip install pipenv`
复制代码
#### `pipenv install flask`

第一个应用

python 复制代码
#!/usr/bin/env python
from flask import Flask

# 初始化
app = Flask(__name__)
@app.route('/')
def index():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

使用

复制代码
#### `python app.py`

路由和视图函数

python 复制代码
#!/usr/bin/env python
from flask import Flask

# 初始化
app = Flask(__name__)
@app.route('/')
def index():
    return 'Hello World!'

@app.route('/a') ## 路由, 指向下面的视图函数
def add(): ## 视图函数
    return '1 + 1 = 2'

# 路由也可以传值
@app.route('/user/<username>')
def user_index(username): ## 在视图函数中指明变量名称
    return 'Hello {}' . format(username)

@app.route('/post/, <int: post_id>')
def show_post(post_id):
    return 'Post {}' . format(post_id)

if __name__ == '__main__':
    app.run(debug=True) ## 随时修改

URL重定向

url_for()

复制代码
#### 构造动态的URL

*

  ##### url_for('函数名', 命名参数, 其它参数)

*

  ```python
  #!/usr/bin/env python
  from flask import Flask
  from flask import url_for
  from flask import redirect

  # 初始化
  app = Flask(__name__)
  @app.route('/')
  def index():
      return 'Hello World!'

  @app.route('/a') ## 路由, 指向下面的视图函数
  def add(): ## 视图函数
      return '1 + 1 = 2'

  # 路由也可以传值
  @app.route('/user/<username>')
  def user_index(username): ## 在视图函数中指明变量名称
      return 'Hello {}' . format(username)

  @app.route('/post/, <int: post_id>')
  def show_post(post_id):
      return 'Post {}' . format(post_id)

  @app.route('/test')
  def test():
      print(url_for('index'))
      print(url_for('user_index', username = 'xxx'))
      print(url_for('show_post', post_id = 1))
      return 'test'

  @app.route('/<username>')
  def hello(username):
      if username == 'handsomexxx':
          return f'Hello {username}'
      else:
          return redirect(url_for('index'))

  if __name__ == '__main__':
      app.run(debug=True) ## 随时修改
  ```

模版渲染

render_template

复制代码
```python
#!/usr/bin/env python
from flask import Flask
from flask import url_for
from flask import redirect
from flask import render_template

# 初始化
app = Flask(__name__)
@app.route('/')
def index():
    return 'Hello World!'

@app.route('/a') ## 路由, 指向下面的视图函数
def add(): ## 视图函数
    return '1 + 1 = 2'

# 路由也可以传值
@app.route('/user/<username>')
def user_index(username): ## 在视图函数中指明变量名称
    return render_template('user_index.html', username = username) ## 模版渲染

@app.route('/post/, <int: post_id>')
def show_post(post_id):
    return 'Post {}' . format(post_id)

@app.route('/test')
def test():
    print(url_for('index'))
    print(url_for('user_index', username = 'xxx'))
    print(url_for('show_post', post_id = 1))
    return 'test'

@app.route('/<username>')
def hello(username):
    if username == 'handsomexxx':
        return f'Hello {username}'
    else:
        return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True) ## 随时修改
```

```html
<h1> hello, {{ username }}! </h1>
```

get 和 post

GET

python 复制代码
#!/usr/bin/env python
from flask import request
from flask import Flask

# 初始化
app = Flask(__name__)

@app.route('/user/<password>'):
def user_password(password):
    print('User-Agent: ', request.headers.get('User-Agent'))
    print('time: ', request.args.get('time'))
    print('q: ', request.args.get('q'))
    print('issingle: '. request.args.get('issingle'))
    return f'password is {password}'

if __name__ == '__main__':
    app.run(debug=True) ## 随时修改

POST

python 复制代码
#!/usr/bin/env python
from flask import request
from flask import Flask

# 初始化
app = Flask(__name__)

@app.route('/register', method = ['GET', 'POST'])
def register():
    print('method: ', request.method)
    print('name', request.form['name'])
    print('password', request.from.get('password'))
    pritn('hobbies: ', request.form.getlist('hobbies'))
    print('age: ', request.form.get('age', default = 18))
    return 'register successd!'

if __name__ == '__main__':
    app.run(debug=True) ## 随时修改
python 复制代码
#!/usr/bin/env python
import requests

# 设置需要发送的数据
user_info = {'name': 'xxx', 'password': '123', 'hobbies': ['code', 'game', 'run']}

# 向URL发送POST请求
r = requests.post('http://127.0.0.1:5000/register', data = user_info)
print(r.text)

SESSION

python 复制代码
#!/usr/bin/env python
from flask import session   
from flask import Flask

# 初始化
app = Flask(__name__)

# 不使用安全码, 浏览器会报错
app.secret_key = 'adadhjkhajhh'

@app.route('/set_session')
def set_session():
    ## 设置session的持久化
    session.permanent = True
    session['username'] = 'xxx'
    return '成功设置 session'

@app.route('/get_session')
def get_session():
    value = session.get('username')
    return f'成功获取session值为 {value}'

if __name__ == '__main__':
    app.run(debug=True) ## 随时修改
python 复制代码
#!/usr/bin/env python
from flask import Flask
from flask import make_response

# 初始化
app = Flask(__name__)

@app.route('/user/<username>')
def user_index(username): ## 在视图函数中指明变量名称
    if username == 'invalid':
        abort(404)
    return render_template('user_index.html')

# 不使用安全码, 浏览器会报错
app.secret_key = 'adadhjkhajhh'

@app.route('/set_session')
def set_session():
    ## 设置session的持久化
    session.permanent = True
    session['username'] = 'xxx'
    return '成功设置 session'

@app.route('/get_session')
def get_session():
    value = session.get('username')
    return f'成功获取session值为 {value}'

@app.route('set_cookie')
def set_cookie(username):
    resp = make_response(render_template('user_index.html', username = username))
    resp.set_cookie('username', username)
    return resp

@app.route('/get_cookie')
def get_cookie():
    username = request.cookies.get('username')
    return f'Hello {username}' 

#@app.errorhandler(404)
#def not_found(error):
#    return render_template('404.html'), 404

if __name__ == '__main__':
    app.run(debug = True)   
html 复制代码
<h1>error!</h1>

相关推荐
郝学胜-神的一滴41 分钟前
Effective Python 条款 10 :海象运算符_=
开发语言·python·程序人生·开源
wuyk55543 分钟前
Python零基础入门第十四章:异常处理(try-except)
开发语言·python
2601_962078191 小时前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
卷无止境4 小时前
智能体开发环境ADE浅析,编程工具的下一次范式跃迁
后端·python
CharlesYu018 小时前
前端性能优化的第一性原理,是不断缩短“用户发起意图 → 获得可用结果”之间的时间
前端
2601_962300818 小时前
机器学习贴士:使用Python编写MapReduce
hadoop·python·机器学习·mapreduce·数据处理
平头哥技术团队8 小时前
Day 21 _ 页内锚点_给每段起个 id,目录写 href=_#id_,点一下页面就滚到那一段
前端·html·html5
xyz_CDragon8 小时前
GitHub上4个爆款AI开源Skill:拍照后不用P图,用Codex一键生成高级海报(附效果图+使用教程)
人工智能·python·github·codex·skill
weixin199701080169 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
持敬chijing9 小时前
Python-数据类型-列表
开发语言·python·青少年编程