flask 笔记

本文介绍了Flask框架中的一些核心模块,包括`flask.helpers`的`make_response`、`url_for`、`flash`、`get_flashed_messages`等方法,以及`flask.wrappers`中的`Request`和`Response`类,还有`flask.views`的类视图概念。这些内容对于理解和使用Flask进行Web开发非常关键。

持续更新…

flask.helpers

  • make_response()
    生成一个Response对象,常用于自定义视图函数的返回内容
# 在返回response之前先修改headers #
    def index():
        response = make_response(render_template('index.html', foo=42))
        response.headers['X-Parachutes'] = 'parachutes are cool'
        return response
# 另一个用例是是强制视图函数的返回值成为响应,这对视图装饰器有帮助 # 
    response = make_response(view_function())
    response.headers['X-Parachutes'] = 'parachutes are cool'
  • url_for(endpoint, **values)
    用给定的方法生成一个url
@app.route('/')
def index():pass

@app.route('/login')
def login():pass

@app.route('/user/<username>)
def profile(username):pass

with app.test_request.context():
    print(url_for('index'))  # /
    print(url_for('login'))  # /login
    print(url_for('login',next='/'))  # /login?next=/
    print(url_for('profile',username='John Don'))  # /user/John%2Doe
  • flash(message, category=’message’)
    把消息闪现到下一个request。为了从session里面把flash信息移除,模板必须调用get_flashed_message()来获取闪现消息
flash('账号或密码错误')
return redirect(url_for('login'))
  • get_flashed_messages(with_categories=False, category_filter=[])
    默认只返回message,当with_categories=True时,返回值将是(category,message)的元组列表
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
  • send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True,cache_timeout=None, conditional=False, last_modified=None):
    发送文件内容到客户端。用最有效的可用方法和配置。默认用WSGI server提供的file_wrapper()支持。或者直接把应用程序的属性Flask.use_x_sendfile属性设置成True,以直接发出X-sendfile头。然而这需要支持X-Sendfile的底层服务器
    ———————————————————————————————-
    默认情况下,会自动尝试猜测mimetype,但也可以明确提供一个。
    application/octet-stream # mimetype
  • safe_join(directory, *pathnames)
    生成一个安全的path
@app.route('/wiki/<path:filename>')
        def wiki_page(filename):
            filename = safe_join(app.config['WIKI_FOLDER'], filename)
            with open(filename, 'rb') as fd:
                content = fd.read()  # Read and process the file content...
  • send_from_directory(directory, filename, **options):
    从给定的目录里面发送文件给客户端,内部是调用了safe_join()和send_file()两个方法
@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],filename, as_attachment=True)
  • send_static_file(self, filename)
    发送静态文件到客户端(从static文件夹里面),内部调用了send_from_directionary()
  • open_resource(self,resource,mode=’rb’)
    从app的资源文件夹(默认根目录)里面打开一个文件,操作方式也open()一样。RAW字符,也就是说没有换行什么的,都是是\n\r\t这样的

flask.wrappers

  • class JSONMixin(object)
// 检查mimetype是否是json,application/json或者application/*+json
// 推荐使用
@property
def is_json()

//如果is_json(),则解析里面的数据,返回一个字典
@property
def json()

// 解析并以JSON格式返回数据,如果MIMETYPE不为json,除了force为真,则返回None
def get_json(self, force=False, silent=False, cache=True):
    // force -> 忽略mimetype,强制转成json
    // slient -> 解析失败的时候不报错而返回None
    // cache -> 存储解析的JSON以返回后续调用。
  • class Request(RequestBase, JSONMixin):
// 字面意思,在配置文件里面写的
@property
def max_content_length()

// 字面意思
@property
def endpoint(self):
    // view func的函数名

//当前blueprint的名字
@property
def blueprint()

form属性 -> 表单的内容
form.get_list()方法 -> checkbox里面的内容 -> form.get_list('check') -> 返回列表
args属性 -> 经过解析的query_string
values属性 -> 一个包含 form 和 args 全部内容的 CombinedMultiDict,前面是args,后面是form
cookies属性 -> 包含cookie内容的dict
stream属性 -> 如果表单提交的数据没有以已知的 mimetype 编码,为性能考虑,数据会不经修改存储在这个流中。大多数情况下,使用可以把数据提供为字符串的 data 是更好的方法。流只返回一次数据。
headers属性 -> 请求头的一个类似dict格式
data属性 -> 如果进入的请求数据是 Flask 不能处理的 mimetype ,数据将作为字符串存于此。
files属性 -> 文件对象,可以用save()方法存到本地
environ属性 -> 底层的wsgi环境
method属性 -> http请求方法
is_xhr属性 ->当请求由 JavaScript 的 XMLHttpRequest 触发时,该值为 True 。 这只对支持 X-Requested-With 标头并把该标头设置为 XMLHttpRequest 的库奏效。这么做的库有 prototype 、 jQuery 以及 Mochikit 等更多。


  • class Response(ResponseBase, JSONMixin)

werkzeug里面的响应对象,具体可以看werkzeug.wrapper模块里面的响应对象
默认是HTML的mimetype,make_response()会照顾
headers -> 响应对象的头信息
status -> 字符串状态的响应状态
status_code -> 整数表示的响应状态
mimetype -> mimetype

// 方法
set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False)

flask.views

提供基于类的类似于Django的视图

class View(object) # 必须要实现一个dispath_request的方法。
// 方法
- def dispatch_request() # 必须要覆盖掉这个方法,在里面处理请求
- def as_view(cls, name, *class_args, **class_kwargs) -> 用来把类转换成一个视图函数,会调用dispath_request()方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值