def login(): form = LoginForm().validate() openid = get_openid(form.code.data) if openid is None: raise NotFound('找不到openid') member_client = MemberClient.query.filter_by(openid=openid, client_type=1).first() if not member_client: with db.auto_commit(): member = Member() member.nickname = form.nickName.data member.sex = form.gender.data member.avatar = form.avatarUrl.data db.session.add(member) with db.auto_commit(): member_client = MemberClient() member_client.member_id = member.id member_client.client_type = 1 member_client.openid = openid db.session.add(member_client) else: member = member_client.member scope = 'UserScope' if member.auth == 1 and member.status == 1 else 'AdminScope' token = gene_token(id=member.id, scope=scope) return jsonify({'token': token})
def migrate_therapy_record(): with db.auto_commit(): items = OneToFive.query.filter_by().all() radio_array = [ '手术', '纵隔镜', '胸腔镜', '肺穿刺', '纤支镜', 'EBUS', 'EUS', '淋巴结活检', '其他' ] for item in items: if item._bioMet: item.bioMet = generate_value_with_radio_list( item._bioMet, radio_array) with db.auto_commit(): items = Surgery.query.filter_by().all() for item in items: if item._surSco: item.surSco = generate_value(item._surSco) if item._lymDis: item.lymDis = generate_value(item._lymDis) with db.auto_commit(): items = Radiotherapy.query.filter_by().all() for item in items: if item._radSite: item.radSite = generate_value(item._radSite) return 'ok'
def fake_comments(nums=500): with db.auto_commit(): for i in range(nums): # 已审核文章评论 data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=True, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) for i in range(int(nums *0.1)): # 未审核评论 data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=False, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) # 管理员评论 data = Comment( author='张小萌', email='*****@*****.**', site='example.com', body=faker.sentence(), timestamp=faker.date_time_this_year(), from_admin=True, reviewed=True, post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data) # 先 commit 评论之后才能生成针对评论的回复 with db.auto_commit(): for i in range(int(nums*0.05)): data = Comment( author=faker.name(), email=faker.email(), site=faker.url(), body=faker.sentence(), timestamp=faker.date_time_this_year(), reviewed=True, replied=Comment.query.get( random.randint(1, Comment.query.count())), post=Post.query.get(random.randint(1, Post.query.count())) ) db.session.add(data)
def perup(): with db.auto_commit(): for item in Permission.query.all(): db.session.delete(item) with db.auto_commit(): for item in app.url_map.iter_rules(): if item.endpoint != 'static': Permission.save(endpoint=item.endpoint) admin_role = Role.get_item_by_name(name='admin') admin_role.update( permissions=[permission for permission in Permission.list_items()])
def confirm_order(order): if order.order_status_enum != OrderStatus.DELIVERED: raise OrderException(msg='订单不是已发货状态,不能确认收货成功') with db.auto_commit(): order.order_status_enum = OrderStatus.NOCOMMENT db.session.add(order) return Success(msg='确认已收货成功, 请给个简单评论吧')
def get_access_token(): token = None token_info = AccessToken.query.filter_by( AccessToken.expired_time >= now_timestamp()).first() if token_info: token = token_info.access_token return token mina_config = current_app.config['MINA_APP'] url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}" \ .format(mina_config['appid'], mina_config['appkey']) r = requests.get(url=url) r.encoding = 'utf-8' if r.status_code != 200 or not r.text: return None data = json.loads(r.text) now = datetime.now() date = now + timedelta(seconds=data['expires_in'] - 200) with db.auto_commit(): token_info = AccessToken() token_info.access_token = data['access_token'] token_info.expired_time = date.timestamp() db.session.add(token_info) return data['access_token']
def single_emp(employee_id): """ 根据员工id获取,更新,删除员工信息 :param employee_id: 员工ID :return: """ employee = Employee.query.filter_by(id=employee_id).first_or_404(description="所查询的员工ID不存在") if request.method == "GET": return make_response(data=employee.dumps()) if request.method == "PUT": name, gender, department = employee_request_handler(request) old_employee_info = employee employee.name = name employee.gender = gender employee.department_id = department.id try: db.session.commit() except Exception: logging.error( "update employee error, employee info: %s, old employee info: %s. \n traceback error: %s" % ( employee.dumps(), old_employee_info.dumps(), traceback.format_exc())) abort(500) logging.info( "update a employee info: %s, before update the employee info: %s" % ( employee.dumps(), old_employee_info.dumps())) return make_response(data=employee.dumps()) if request.method == "DELETE": with db.auto_commit(): employee.delete() return make_response()
def Success(trad_id): """ 完成交易,只有请求者才能确定 注意需要验证超权 """ trad = Trad.query.filter_by(requester_id=current_user.id, id=trad_id).first_or_404() if trad.pending == PendingStatus.Waiting: if trad.pending == PendingStatus.Success: flash("交易已经完成") return redirect(url_for('web.trad_info')) with db.auto_commit(): trad.pending = PendingStatus.Success.value giver = User.query.get(trad.giver_id) giver.love_value += 10 if giver.love_value == 120: giver.love_value = 80 giver.star_value += 10 trad.launched = 0 flash('操作成功 ! ') else: flash('发生了一个错误 !') return redirect(url_for('web.trad_info'))
def redraw(wid): wish = Wish.query.filter_by(id=wid).first_or_404() with db.auto_commit(): wish.status = 0 return redirect(url_for('web.wish:my_wish'))
def init(username, password): """初始化数据库 admin 分类""" click.echo('初始化数据库中...') db.create_all() with db.auto_commit(): admin = Admin.query.first() if admin is not None: click.echo('管理员账号已存在,更新中...') admin.username = username admin.set_password(password) else: click.echo('创建默认管理员数据中...') admin = Admin( username=username, blog_title='Br Blog', blog_sub_title="Genius only means hard-working all one's life.", name='Jack Zhang', about='''永不放弃是人生要成功的一大因素, 只要能够坚持, 锲而不舍, 终会到达成功的彼岸的。''' ) admin.set_password(password) db.session.add(admin) category = Category.query.first() if category is None: click.echo('创建默认分类...') category = Category(name='Default') db.session.add(category) click.echo('Done.')
def activate(): data = request.get_json(silent=True) uid = data.get('uid') d = Domain.get_item_by_uid(uid, status=0) with db.auto_commit(): d.activate() return Success()
def save(self): """ 保存修改或提交的记录 :return: """ with db.auto_commit(): db.session.add(self)
def save_info(): data = request.get_json(silent=True) name = data.get('name') parent_uid = data.get('parent_uid') with db.auto_commit(): Zone.save(name=name, parent_uid=parent_uid) return Success()
def delete(self): """ 删除记录 ->目前是真删除 日后可能改成假删除 -> self.status = 0 :return: """ with db.auto_commit(): db.session.delete(self)
def save_a_drift(drift_form, current_gift): with db.auto_commit(): book = BookViewModel(current_gift.book) drift = Drift() drift_form.populate_obj(drift) drift.requester_id = current_user.id drift.requester_nickname = current_user.nickname drift.gift_id = current_gift.id drift.gifter_nickname = current_gift.user.nickname drift.gifter_id = current_gift.user.id drift.book_title = book.title drift.book_author = book.author drift.book_img = book.image drift.isbn = book.isbn current_user.beans -= current_app.config['BEANS_EVERY_DRIFT'] drift.add() send_email(current_gift.user.email, '有人想要一本书', 'email/get_gift.html', wisher=current_user, gift=current_gift)
def test_db_rollback(self): from app.models.department import Department try: with db.auto_commit(): db.session.add(Department(name="伏羲实验室")) except Exception as e: self.assertEqual(e.code, 500)
def preview_edit(id=None): form = PreviewForm() if form.validate_on_submit(): data = form.data preview = Preview.query.filter_by(id=id).first() with db.auto_commit(): # 修改logo名 file_logo = secure_filename(form.logo.data.filename) if not os.path.exists(app.config["UP_DIR"]): os.makedirs(app.config["UP_DIR"]) os.chmod(app.config["UP_DIR"], "rw") logo = change_filename(file_logo) # 保存logo图片 form.logo.data.save(app.config["UP_DIR"]+logo) preview.title=data['title'], preview.logo=logo db.session.add(preview) # 记录编辑预告操作 new_adminlog = OpLog( admin_id=session['id'], ip=session['login_ip'], reason="编辑预告: "+data['title']) db.session.add(new_adminlog) return redirect(url_for("admin.preview_add")) return render_template("admin/preview_add.html", form=form)
def preview_add(): form = PreviewForm() if form.validate_on_submit(): data = form.data # 如果已有该预告则不添加 if Preview.query.filter_by(title=data['title']).first(): flash("预告已经存在,请不要重复添加", "err") else: with db.auto_commit(): file_logo = secure_filename(form.logo.data.filename) if not os.path.exists(app.config["UP_DIR"]): os.makedirs(app.config["UP_DIR"]) os.chmod(app.config["UP_DIR"], "rw") logo = change_filename(file_logo) form.logo.data.save(app.config["UP_DIR"]+logo) new_preview = Preview( title=data['title'], logo=logo ) db.session.add(new_preview) # 记录添加预告操作 new_adminlog = OpLog( admin_id=session['id'], ip=session['login_ip'], reason="添加预告: "+new_preview.title) db.session.add(new_adminlog) return redirect(url_for("admin.preview_add")) return render_template("admin/preview_add.html", form=form)
def redraw_drift(did): with db.auto_commit(): drift = Drift.query.filter_by( id=did, requester_id=current_user.id).first_or_404() drift.pending = PendingStatus.Redraw current_user.beans += 1 return redirect(url_for('views.pending'))
def update_sale_date(order): """ 更新销售数据并返回模板消息内容 :param order: :return: """ order_foods = order.order_foods.filter_by().all() notice = [] with db.auto_commit(): if order_foods: date_from = datetime.strptime( datetime.now().strftime('%Y-%m-01 00:00:00'), '%Y-%m-%d %H:%M:%S').timestamp() date_to = datetime.strptime( datetime.now().strftime('%Y-%m-31 23:59:59'), '%Y-%m-%d %H:%M:%S').timestamp() for item in order_foods: food = item.food if not food: continue notice.append('{} {}份'.format(food.name, item.quantity)) # 当月数量 stat_info = db.session.query( func.sum(FoodSaleChangeLog.quantity). label('total')).filter( FoodSaleChangeLog.food_id == food.id, FoodSaleChangeLog.status == Status.EXIST.value).filter( FoodSaleChangeLog.create_time >= date_from, FoodSaleChangeLog.create_time <= date_to).first() food.month_count = stat_info.total food.total_count += item.quantity db.session.add(food) return notice
def save_a_drift(cls, drift_form, current_gift): with db.auto_commit(): book = BookViewModel(current_gift.book.first) drift = Drift() drift_form.populate_obj(drift) drift.gift_id = current_gift.id drift.requester_id = current_user.id drift.requester_nickname = current_user.nickname drift.gifter_nickname = current_gift.user.nickname drift.gifter_id = current_gift.user.id drift.book_title = book.title drift.book_author = book.author drift.book_img = book.image drift.isbn = book.isbn # 当请求生成时,不需要让这个礼物处于锁定状态 # 这样赠送者是可以收到多个索取请求的,由赠送者选择送给谁 # current_gift.launched = True # 请求者鱼豆-1 current_user.beans -= 1 # 但是赠送者鱼豆不会立刻+1 # current_gift.user.beans += 1 db.session.add(drift) send_email(current_gift.user.email, '有人想要一本书', 'email/get_gift', wisher=current_user, gift=current_gift)
def single_department(department_id): """ 获取、更新或删除单个部门组织 :param department_id: 部门id :return: """ department = Department.query.filter_by(id=department_id).first_or_404( description="部门ID不存在") if request.method == "GET": logging.info("get a department info: %s" % department.dumps()) return make_response(data=department.dumps_detail()) if request.method == "PUT": name, parent_id = department_request_handler(request, department) old_department_info = department department.name = name department.parent_id = parent_id try: db.session.commit() except Exception: logging.error( "update department error, department info: %s, old department info: %s. \n traceback error: %s" % (department.dumps(), old_department_info.dumps(), traceback.format_exc())) abort(500) logging.info( "update a department info: %s, before update the department info: %s" % (department.dumps(), old_department_info.dumps())) return make_response(data=department.dumps_detail()) if request.method == "DELETE": with db.auto_commit(): department.delete() logging.info("delete a department: %s" % department) return make_response()
def remove(): data = request.get_json(silent=True) uid = data.get('uid') d = Domain.get_item_by_uid(uid) with db.auto_commit(): d.remove() return Success()
def del_record_info(pid): tre_rec = TreRec.query.filter_by(pid=pid).order_by( TreRec.treNum.desc()).first() if tre_rec: with db.auto_commit(): tre_rec.delete() return Success()
def del_trad(trad_id): if current_user.student_id != '1602140129': abort(404) trad = Trad.query.get_or_404(trad_id) with db.auto_commit(): db.session.delete(trad) return redirect(url_for('web.admin'))
def upload_file(file): config_upload = current_app.config['UPLOAD'] resp = {'code': 200, 'msg': '操作成功~~', 'data': {}} filename = file.filename ext = filename.rsplit(".", 1)[1] # if ext not in config_upload['ext']: # resp['code'] = -1 # resp['msg'] = "不允许的扩展类型文件" # return resp root_path = current_app.root_path + config_upload['prefix_url'] file_dir = date_to_str(format="%Y%m%d") save_dir = root_path + file_dir if not os.path.exists(save_dir): os.mkdir(save_dir) os.chmod(save_dir, stat.S_IRWXU | stat.S_IRGRP | stat.S_IRWXO) file_name = str(uuid.uuid4()).replace("-", "") + "." + ext file.save("{0}/{1}".format(save_dir, file_name)) with db.auto_commit(): model_image = Image() model_image.file_key = file_dir + "/" + file_name db.session.add(model_image) resp['data'] = {'file_key': model_image.file_key} return resp
def save_info(): data = request.get_json(silent=True) name = data.get('name') permissions = data.get('permissions') with db.auto_commit(): Role.save(name=name, permissions=Permission.list_items_by_uids(permissions)) return Success()
def redraw_from_wish(isbn): wish = Wish.query.filter_by(isbn=isbn).first() if not wish: flash('该心愿不存在,删除失败') else: with db.auto_commit(): wish.status = 0 return redirect(url_for('web.my_wish'))
def create(cls, nickname, email, password): user = cls() with db.auto_commit(): user.nickname = nickname user.email = email user.password = password db.session.add(user) return user.id
def fake_categories(nums=5): with db.auto_commit(): # 优先生成默认分类 data = Category(name='default') db.session.add(data) for i in range(nums): data = Category(name=faker.word()) db.session.add(data)