学习狗书flask web,发现有时候db.session.add(current_user),有时db.session.add(current_user._get_current_object())

当修改数据库的数据的时候,需要运行db.session.add()和db.session.commit()
但是我发现,db.session.add()的东西不一样,比如在main\views.py的edit_profile()中

	current_user.name = form.name.data
    current_user.location = form.location.data
    current_user.about_me = form.about_me.data
    db.session.add(current_user._get_current_object())   # here
    db.session.commit()

而在auth\views.py的change_password()中用的是

	current_user.password = form.password.data
    db.session.add(current_user)             #here
    db.session.commit()

我没看出来这两者的使用场景的区别,为什么第一个得用.get_current_object()函数呢?
在send_email()中也用到了current
_app._get_current_object(),但是我知道那和异步通信有关,是为了解除current_app()的线程隔离,详情参考:python- flask current_app详解,与 current_app._get_current_object()的区别以及异步发送邮件实例
官方文档的最后也有提及:The Request Context

但是这里是为什么?

第一步,惯例先看源码:

"""Return the current object this proxy is bound to. If the proxy is
    unbound, this raises a ``RuntimeError``.

    This should be used if you need to pass the object to something that
    doesn't understand the proxy. It can also be useful for performance
    if you are accessing the object multiple times in a function, rather
    than going through the proxy multiple times.
    """

大概意思是用不了current_user 的时候就用current_user._get_current_object().还有如果需要多次访问的话使用_get_current_object() 比使用current_user代理的性能高,而edit_profile()确实涉及到多次访问。


下面贴上几个我在解决困惑时给到我启发的帖子:提到了上下文
[AF] current_user vs. current_user._get_current_object()

本书作者也来回答了,current_app.get_current_object().是为了解决多线程,current_user.get_current_object() 是在db.relationship中
current_app vs current_app._get_current_object
虽然我这里只谈到了current
_user

以及GitHub上的给我proxy的启发
https://github.com/miguelgrinberg/flasky/issues/348

更新:学到后面的博客文章,发现也适用于解释:
post = Post(body=form.body.data, author=current_user._get_current_object())
用current_user._get_current_object()而不是current_user
另外这里用author而不是author_id 是因为在model.py的User表的relationship的backref中为Post表定义了属性“author”
posts = db.relationship('Post', backref='author', lazy='dynamic')

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
请帮我写一段单元测试,来测试以下代码:from flask import render_template, Blueprint, request, abort from flask_login import login_required, current_user from sqlalchemy import select, between, or_, desc from flbs.sign.sign_model import OperationLog, User from flbs.extensions import db from datetime import datetime dashboard_bp = Blueprint('dashboard', __name__) @dashboard_bp.before_request @login_required def add_operation_log(): # OperationLog.add_operation_log(current_user.userid, current_user.username) pass @dashboard_bp.route('/dashboard') def dashboard(): if 'd1' not in current_user.permissions: return abort(403) page = request.args.get('page', default=1) try: page = int(page) except ValueError: page = 1 daterange = request.args.get('daterange', default=datetime.now().strftime('%Y-%m-%d') + ' - ' + datetime.now().strftime( '%Y-%m-%d')) date_1 = daterange[:10] date_2 = daterange[-10:] + ' 23:59:59.999999' user = request.args.get('user', '').strip() module = request.args.get('module', '').strip() sql_query = select(OperationLog).where(between(OperationLog.c_date, datetime.strptime(date_1, "%Y-%m-%d"), datetime.strptime(date_2, "%Y-%m-%d %H:%M:%S.%f"))) if user: sql_query = sql_query.where(or_(OperationLog.userid == user, OperationLog.username == user)) if module: sql_query = sql_query.where( or_(OperationLog.endpoint.like("%" + module + "%"), OperationLog.full_path.like("%" + module + "%"))) sql_query = sql_query.order_by(desc(OperationLog.id)) # print(sql_query) paginated = db.paginate(select=sql_query, page=page, per_page=10) # 分页 pagination_query = {'daterange': daterange, 'user': user, 'module': module} return render_template('dashboard/dashboard.html', header_title='flask-sqlalchemy', tips='test pagination', user=user, daterange=daterange, module=module, paginated=paginated, endpoint=request.endpoint, total=paginated.total, full_path=request.full_path, pagination_query=pagination_query)
05-25

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值