Flask基础

一、 简介
1、 框架介绍
Flask是一个基于Python并且依赖于Jinja2模板引擎和Werkzeug WSGI 服务的一个微型框架
WSGI :Web Server Gateway Interface(WEB服务网关接口),定义了使用python编写的web app与web server之间接口格式

其他类型框架:

Django:比较“重”的框架,同时也是最出名的Python框架。包含了web开发中常用的功能、组件的框架(ORM、Session、Form、Admin、分页、中间件、信号、缓存、ContenType…),Django是走大而全的方向,最出名的是其全自动化的管理后台:只需要使用起ORM,做简单的对象定义,它就能自动生成数据库结构、以及全功能的管理后台。

Tornado:大特性就是异步非阻塞、原生支持WebSocket协议;

Flask: 一个轻量级的基于 Python 的 Web 框架

Bottle:是一个简单高效的遵循WSGI的微型python Web框架。说微型,是因为它只有一个文件,除Python标准库外,它不依赖于任何第三方模块。

2、 架构模式
Flask的架构模式-MTV

经典三层结构 :MVC模式
M :Models ,模型层,负责数据库建模
V :Views,视图层,用于处理用户显示的内容,如 :html
C :Controller,控制器,处理与用户交互的部分内容。处理用户的请求并给出响应
python常用:MTV模式
M :Models ,模型层,负责数据库建模
T :Templates ,模板层,用于处理用户显示的内容,如:html
V :Views ,视图层,处理与用户交互的部分内容。处理用户的请求并给出响应

3、 环境搭建

安装

pip install flask

在app.py中添加

from flask import Flask

app = Flask(name)

@app.route('/') # Flask路由
def hello_world():
return 'Hello World!'

if name == 'main':
app.run() # 运行网站

主程序会默认访问templates和static文件夹,如果,存放web文件的文件夹名称不是这两个,那么要在实例化Flask路由时,声明

flask中文网:https://flask.net.cn/

框架之配置

flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:

{
'DEBUG': get_debug_flag(default=False), # 是否开启Debug模式
'TESTING': False, # 是否开启测试模式
'PROPAGATE_EXCEPTIONS': None,
'PRESERVE_CONTEXT_ON_EXCEPTION': None,
'SECRET_KEY': None,
'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
'USE_X_SENDFILE': False,
'LOGGER_NAME': None,
'LOGGER_HANDLER_POLICY': 'always',
'SERVER_NAME': None,
'APPLICATION_ROOT': None,
'SESSION_COOKIE_NAME': 'session',
'SESSION_COOKIE_DOMAIN': None,
'SESSION_COOKIE_PATH': None,
'SESSION_COOKIE_HTTPONLY': True,
'SESSION_COOKIE_SECURE': False,
'SESSION_REFRESH_EACH_REQUEST': True,
'MAX_CONTENT_LENGTH': None,
'SEND_FILE_MAX_AGE_DEFAULT': timedelta(hours=12),
'TRAP_BAD_REQUEST_ERRORS': False,
'TRAP_HTTP_EXCEPTIONS': False,
'EXPLAIN_TEMPLATE_LOADING': False,
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSONIFY_PRETTYPRINT_REGULAR': True,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,
}

方式一:

app.config['DEBUG'] = True # PS: 由于Config对象本质上是字典,所以还可以使用app.config.update(...)

方式二:

app.config.from_pyfile("python文件名称")
"""
如:
settings.py
DEBUG = True

        app.config.from_pyfile("settings.py")

"""
app.config.from_envvar("环境变量名称") # 环境变量的值为python文件名称名称,内部调用from_pyfile方法

app.config.from_json("json文件名称") # JSON文件名称,必须是json格式,因为内部会执行json.loads

app.config.from_mapping({'DEBUG':True}) # 字典格式

app.config.from_object("python类或类的路径") # 传入一个类
"""
如:
app.config.from_object('pro_flask.settings.TestingConfig')
settings.py
class Config(object):
DEBUG = False
TESTING = False
DATABASE_URI = 'sqlite://:memory:'

        class ProductionConfig(Config):
            DATABASE_URI = 'mysql://user@localhost/foo'

        class DevelopmentConfig(Config):
            DEBUG = True

        class TestingConfig(Config):
            TESTING = True

    PS: 从sys.path中已经存在路径开始写
PS: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为True,则就是instance_path目录

框架之路由
2.1 添加路由

第一种

@app.route('/')
def hello_world():
return 'Hello World!'

第二种

def index():
return "index"

app.add_url_rule("/index", None, index)

2.2 反向生成
from flask import Flask, url_for, redirect

app = Flask(name)

@app.route('/')
def hello_world():
index_ = url_for("i") # 返回i对应的路由
print(index_) # 可以进行重定向
return redirect(index_) # 进行重定向

@app.route("/index/asdhjaskdg/sad", endpoint="i") # endpoint默认为函数名
def index():
return "index"

if name == 'main':
app.run()

2.3 路由系统
@app.route('/user/'):传递字符串类型的数据
@app.route('/post/int:post_id'):传递整型数据
@app.route('/post/float:post_id'):传递浮点类型数据
@app.route('/post/path:path'):传递路径
@app.route('/object:object'):传递自定义数据类型
from flask import Flask, url_for
from werkzeug.routing import BaseConverter

app = Flask(import_name=name)

1.定义自己的转换器

class RegexConverter(BaseConverter):

 # map是固定的参数,将整个列表进行带入,regex是写入的参数,添加进新的转换器类型
def __init__(self, map, regex):
    # 调用父类的初始化方法
    super(RegexConverter, self).__init__(map)
    self.regex = regex

def to_python(self, value):
    # 路由匹配时,匹配成功后传递给视图函数中参数的值
    return int(value)

def to_url(self, value):
    # 使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
    val = super(RegexConverter, self).to_url(value)
    print(val)
    return val

2.将自定义的转换器添加到flask的应用中

app.url_map.converters['regex'] = RegexConverter

@app.route('/index/<regex("\d+"):nid>')
def index(nid):
print(url_for('index', nid='888'))
return 'Index'

if name == 'main':
print(app.url_map) # 查看路由信息
app.run()

请求与响应
from flask import Flask, request, render_template, redirect, jsonify
, make_response # 返回响应头

app = Flask(name)

@app.route('/')
def index():
"""请求相关信息"""
# request.method
# request.args
# request.form
# request.values
# request.cookies
# request.headers
# request.path
# request.files
# obj = request.files['the_file_name']
# obj.save('/var/www/uploads/' + secure_filename(f.filename))
"""以上的是常用的"""
# request.full_path
# request.script_root
# request.url
# request.base_url
# request.url_root
# request.host_url
# request.host

"""响应相关"""
"""
响应头的使用
response = make_response(render_template('index.html'))  # 创建响应数据
print(type(response))
response.delete_cookie('key')  # 删除cookie
response.set_cookie('key', 'value')  # 设置cookie
response.headers['X-Something'] = 'A value'
return response
"""
return "hello world"  # 可以使用json.dumps({}) / jsonify({}) 返回JSON数据
# return render_template("index.html", n1=123)  # 渲染静态文件,第二个参数可以是字典解包,或者等号传参,传递给前端页面
# return redirect("/index")  # 重定向

if name == 'main':
app.run()

变量
index.html里面的内容

index
{{ k1 }}

{{ k2[0] }} {{ k2[1] }}

匿名函数运行的结果为:{{ k3("pwd") | safe }}

app.py 里面的内容

from flask import Flask, render_template, Markup

app = Flask(name)

def input_(value):
# 生成input标签
return Markup("" % value) # Markup 的功能和|safe一样,使得html内容可以渲染出来,关闭对文本信息的转义,其为过滤器

@app.route('/')
def index():
context = {
"k1": 123,
"k2": [11, 12, 13],
"k3": lambda x: input_(x),
}
return render_template("index.html", **context)

if name == 'main':
app.run()

2、 继承
parent.html

父类
头部
{% block content %} {% endblock %}
尾部

{% extends "parent.html" %}
{% block content %}

{{ k1 }}

{{ k2[0] }} {{ k2[1] }}

匿名函数运行的结果为:{{ k3("pwd") | safe }}

{% endblock %}

session
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥

字典中拥有的方法,session就拥有

posted @   Tree—wyh  阅读(99)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示