def test_ok(self, client, one_admin): # login with the client assert current_user.is_anonymous() url = url_for('view.admin_login') data = { 'username': one_admin.username, 'password': '******', } response = client.post(url, data=data) assert response.status_code == 302 assert not current_user.is_anonymous() url = url_for('view.create_user') data = { 'username': '******', 'email': '*****@*****.**', 'company_name': 'bigsec', 'total_count': -1, 'expire_time': -1, 'rate_limit': -1, 'allow_bulk_detect': 'y', 'allow_excel_detect': 'y', 'allow_voip_detect': 'y', 'allow_detail_display': 'y', 'allow_vote_define': 'y', 'allow_data_push': 'y', } response = client.post(url, data=data) assert response.status_code == 302 pytest.fail("not correct")
def get_user_info(self, request): """ Requires Flask-Login (https://pypi.python.org/pypi/Flask-Login/) to be installed and setup """ if not has_flask_login: return if not hasattr(current_app, "login_manager"): return try: is_authenticated = current_user.is_authenticated() except AttributeError: # HACK: catch the attribute error thrown by flask-login is not attached # > current_user = LocalProxy(lambda: _request_ctx_stack.top.user) # E AttributeError: 'RequestContext' object has no attribute 'user' return {} if is_authenticated: user_info = { "is_authenticated": True, "is_anonymous": current_user.is_anonymous(), "id": current_user.get_id(), } if "SENTRY_USER_ATTRS" in current_app.config: for attr in current_app.config["SENTRY_USER_ATTRS"]: if hasattr(current_user, attr): user_info[attr] = getattr(current_user, attr) else: user_info = {"is_authenticated": False, "is_anonymous": current_user.is_anonymous()} return user_info
def get_user_info(request): """ Requires Flask-Login (https://pypi.python.org/pypi/Flask-Login/) to be installed and setup """ try: from flask_login import current_user except ImportError: return None if not hasattr(current_app, 'login_manager'): return None if current_user.is_authenticated(): user_info = { 'is_authenticated': True, 'is_anonymous': current_user.is_anonymous(), 'id': current_user.get_id(), } if 'SENTRY_USER_ATTRS' in current_app.config: for attr in current_app.config['SENTRY_USER_ATTRS']: if hasattr(current_user, attr): user_info[attr] = getattr(current_user, attr) else: user_info = { 'is_authenticated': False, 'is_anonymous': current_user.is_anonymous(), } return user_info
def edit(path='/'): if path != '/': path = '/' + path record = models.Pages.pull_by_url(path) if record is None: if current_user.is_anonymous(): abort(404) else: return redirect('/' + path) elif current_user.is_anonymous() and not (rec.data.get('editable',False) and rec.data.get('accessible',False)): abort(401) else: if app.config.get('COLLABORATIVE',False): try: test = requests.get(app.config['COLLABORATIVE']) if test.status_code == 200: padsavailable = True else: padsavailable = False except: padsavailable = False # TODO: add a check - if index has more recent content than pad content, show a warning to sync the pad to index return render_template( 'pagemanager/edit.html', padsavailable=padsavailable, record=record )
def _retrieve_new_task(project_id): project = project_repo.get(project_id) if project is None: raise NotFound if not project.allow_anonymous_contributors and current_user.is_anonymous(): info = dict( error="This project does not allow anonymous contributors") error = [model.task.Task(info=info)] return error if request.args.get('external_uid'): resp = jwt_authorize_project(project, request.headers.get('Authorization')) if resp != True: return resp if request.args.get('limit'): limit = int(request.args.get('limit')) else: limit = 1 if limit > 100: limit = 100 if request.args.get('offset'): offset = int(request.args.get('offset')) else: offset = 0 if request.args.get('orderby'): orderby = request.args.get('orderby') else: orderby = 'id' if request.args.get('desc'): desc = fuzzyboolean(request.args.get('desc')) else: desc = False user_id = None if current_user.is_anonymous() else current_user.id user_ip = (anonymizer.ip(request.remote_addr or '127.0.0.1') if current_user.is_anonymous() else None) external_uid = request.args.get('external_uid') task = sched.new_task(project_id, project.info.get('sched'), user_id, user_ip, external_uid, offset, limit, orderby=orderby, desc=desc) return task
def before_request(): #exempt files are url's that do not require any authentication to access exempt_files = ["/check_email", "/check_phone", "/favicon.ico", url_for("static", filename="login.css"), url_for("static", filename="login_mobile.css"), url_for("static", filename="login_validator.js"), "/get_user"] for f in exempt_files: if request.path == f: return None #trying to access an account activation page if request.path.startswith("/v/"): return None #trying to access an page only accessible if you are not logged in if request.path == "/" or request.path == "/mobile" or \ request.path == "/login" or request.path == "/register": #no need for them to access, go home if not current_user.is_anonymous() and login.is_session_valid(): return redirect("/home") #trying to access a protected page else: #user is not valid if current_user.is_anonymous() or not login.is_session_valid(): #we want to save the URL theyre trying to go to so we can #redirect them there after they log in if request.path.startswith("/viewtaskdetails/"): session["pre_login_url"] = request.path return redirect("/") #session is valid else: #update their token current_user.last_request = int(time.time()) session["request_time"] = current_user.last_request db.session.commit() #if they"re not activated dont let them go anywhere if not current_user.activated and \ not (request.path == "/home" or \ request.path == "/logout" or \ request.path.endswith(".css") or \ request.path.endswith(".js")): return redirect("/home")
def sync(path=''): url = '/' + path.lstrip('/').rstrip('/') if url == '/': url = '/index' if url.endswith('.json'): url = url.replace('.json','') rec = models.Pages.pull_by_url(url) if current_user.is_anonymous(): abort(401) elif rec is None: abort(404) else: # save to ES if app.config.get('COLLABORATIVE',False): done1 = _sync_es_from_ep(rec) if done1: flash("Synchronised") else: flash("Error syncing") # save to FS if app.config.get('CONTENT_FOLDER',False): done2 = _sync_fs_from_es(rec) if done2: flash("Saved to disk") else: flash("Error saving to disk") return redirect(url_for('.edit', path=path))
def inner(*args, **kwargs): from .models import Ability desired_ability = Ability.query.filter_by(name=ability).first() user_abilities = [] current_user = get_user() print(current_user) try: is_anonymous = current_user.is_anonymous() except TypeError: is_anonymous = True if is_anonymous == False: for role in current_user.roles: user_abilities += role.abilities else: return redirect(url_for("main_controller.login")) if desired_ability in user_abilities: return func(*args, **kwargs) else: if request.is_xhr: # If this is an AJAX request return JSON instead. return jsonify({"success": False, "messages": [PERM_ERROR_MESSAGE]}) else: try: # If this template exists we should use it. return render_template("permission_denied.html") except: raise Forbidden(PERM_ERROR_MESSAGE)
def user_progress(project_id=None, short_name=None): """API endpoint for user progress. Return a JSON object with two fields regarding the tasks for the user: { 'done': 10, 'total: 100 } This will mean that the user has done a 10% of the available tasks for him """ if project_id or short_name: if short_name: project = project_repo.get_by_shortname(short_name) elif project_id: project = project_repo.get(project_id) if project: # For now, keep this version, but wait until redis cache is # used here for task_runs too query_attrs = dict(project_id=project.id) if current_user.is_anonymous(): query_attrs['user_ip'] = anonymizer.ip(request.remote_addr or '127.0.0.1') else: query_attrs['user_id'] = current_user.id taskrun_count = task_repo.count_task_runs_with(**query_attrs) tmp = dict(done=taskrun_count, total=n_tasks(project.id)) return Response(json.dumps(tmp), mimetype="application/json") else: return abort(404) else: # pragma: no cover return abort(404)
def is_accessible(self): return ( not AUTHENTICATE or ( not current_user.is_anonymous() and current_user.is_authenticated() ) )
def demo3_output(): if current_user.is_anonymous(): return redirect(url_for('login')) scenarios_query = current_user.scenarios.all() scenarios = [] for scenario in scenarios_query: scenarios.append(scenario.data) #print scenarios ## Chart Data and Labels ## Chart1_data_pts = [] Chart1_labels = [] for x in range(0,len(scenarios)): Chart1_data_pts.append([]) for y in range(0,len(scenarios[x]['net_worth']),12): Chart1_data_pts[x].append(scenarios[x]['net_worth'][y]) #for k,v in scenarios[x]['net_worth'].iteritems(): # Chart1_data_pts[x].append(v) for x in range(0,len(scenarios[0]['net_worth']),12): Chart1_labels.append(x) ## / Chart Data and Labels ## #return render_template('demo3_output.html', s=scenarios_query[1].data) return render_template('demo3_output.html', s=scenarios,Chart1_data_pts=Chart1_data_pts,Chart1_labels=Chart1_labels)
def get(self): if current_user.is_anonymous(): return render_template('admin/signin.html', form=forms.SignInForm(), next_url=request.args.get('next', url_for('admin.index'))) else: return redirect(request.args.get('next', url_for('admin.index')))
def index(): contracts = db.session.query( ContractBase.id, ContractBase.description, ContractBase.financial_id, ContractBase.expiration_date, ContractBase.current_stage, Stage.name.label('stage_name'), ContractBase.updated_at, User.email.label('assigned'), ContractProperty.value.label('spec_number'), ContractBase.contract_href ).join(ContractProperty).outerjoin(Stage).outerjoin(User).filter( db.func.lower(ContractBase.contract_type) == 'county', ContractBase.expiration_date is not None, db.func.lower(ContractProperty.key) == 'spec number', ).order_by(ContractBase.expiration_date).all() conductors = User.query.join(Role).filter( Role.name == 'conductor' ).all() user_starred = [] if current_user.is_anonymous() else current_user.get_starred() return render_template( 'conductor/index.html', contracts=contracts, user_starred=user_starred, current_user=current_user, conductors=[current_user] + conductors )
def post(self): """Add User ID to task as a favorite.""" try: self.valid_args() data = json.loads(request.data) if (len(data.keys()) != 1) or ('task_id' not in data.keys()): raise AttributeError if current_user.is_anonymous(): raise Unauthorized uid = current_user.id tasks = task_repo.get_task_favorited(uid, data['task_id']) if len(tasks) == 1: task = tasks[0] if len(tasks) == 0: task = task_repo.get_task(data['task_id']) if task is None: raise NotFound if task.fav_user_ids is None: task.fav_user_ids = [uid] else: task.fav_user_ids.append(uid) task_repo.update(task) self._log_changes(None, task) return Response(json.dumps(task.dictize()), 200, mimetype='application/json') except Exception as e: return error.format_exception( e, target=self.__class__.__name__.lower(), action='POST')
def get(self, oid): """Return all the tasks favorited by current user.""" try: if current_user.is_anonymous(): raise abort(401) uid = current_user.id limit, offset, orderby = self._set_limit_and_offset() last_id = request.args.get('last_id') print last_id desc = request.args.get('desc') if request.args.get('desc') else False desc = fuzzyboolean(desc) tasks = task_repo.filter_tasks_by_user_favorites(uid, limit=limit, offset=offset, orderby=orderby, desc=desc, last_id=last_id) data = self._create_json_response(tasks, oid) return Response(data, 200, mimetype='application/json') except Exception as e: return error.format_exception( e, target=self.__class__.__name__.lower(), action='GET')
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(request.args.get('next') or url_for('items.user', username=user.username)) oauth = OAuthSignIn.get_provider(provider) name, username = oauth.callback() if username is None: flash('Authentication failed.') return redirect(url_for('main.index')) # Look if user already exists user = User.get_by_username(username) if not user: # create the user. try to use the name, # but if not set, then use the portion of email if name is None or name == "": name = email.split('@')[0] user = User(username=username, name=name) db.session.add(user) db.session.commit() # Log in the user, by default remembering them for their next visit # unless they log out. login_user(user, remember=True) return redirect(request.args.get('next') or url_for('items.user', username=user.username))
def oauth_authorize(provider): # Flask-Login function if not current_user.is_anonymous(): return redirect(request.args.get('next') or url_for('items.user', username=user.username)) oauth = OAuthSignIn.get_provider(provider) return oauth.authorize()
def is_it_active(): ''' If Ip is Active :param: :return: [JSON] "status": 0, "message": "User Not Login!", "data": {} ''' if current_user.is_anonymous(): return jsonify({ "status": 0, "message": "User Not Login!", "data": {} }) else : return jsonify({ "status": 1, "message": "User has Login!", "data": { "id" : current_user.userID, "nickname" : current_user.nickName, "isAuth" : current_user.isAuthenticated, "username" : current_user.userName, "email" : current_user.email, "qq" : current_user.qq, "compressPicture": current_user.compressPicture } })
def _update_object(self, obj): if not current_user.is_anonymous(): obj.owner_id = current_user.id owners = obj.owners_ids or [] if current_user.id not in owners: owners.append(current_user.id) obj.owners_ids = owners
def thread_show(art_id, thr_id): form = CommentForm() likeform = LikeForm() artist = Artist.query.filter_by(id=art_id).first_or_404() thread = Thread.query.filter_by(id=thr_id).first_or_404() thread.uni_content = unicode(escape(thread.content)).replace("\r\n", "<br />") # 查询评论 type_id: 1-问题,2-曲谱,3-二手交易,4-活动,5-艺人 comments_select = comments_query(5, thr_id) if current_user.is_anonymous() or current_user.id != thread.uid: thread.hot = thread.hot + 1 db.session.commit() is_like = None if current_user.is_authenticated(): is_like = Like.query.filter_by(uid=current_user.id).filter_by(like_type=2)\ .filter_by(like_id=art_id).first() if request.method == 'POST' and form.validate_on_submit(): comment = Comment() comment.save(form, current_user.id, 5, thr_id) thread.comments_num = thread.comments_num + 1 db.session.commit() comments_select = comments_query(5, thr_id) return redirect(url_for('artists.thread_show', art_id=art_id, thr_id=thr_id)) #return render_template('artists/comments_ajax.html', comments=comments_select, thread=thread) return render_template('artists/thread_show.html', comments=comments_select, thread=thread, form=form,\ artist=artist, likeform=likeform, is_like=is_like)
def oauth_callback(provider): if not current_user.is_anonymous(): return redirect(url_for('simple_page.index')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash(getttext(u'Authentication failed'), 'danger') return redirect(url_for('simple_page.index')) # check if user exists and if no creates new user = User.query.filter_by(social_id=social_id).first() if user is None: user = User( username=username, password='', email=email, social_id=social_id ) db.session.add(user) db.session.commit() login_user(user, remember=True) user.update_login_info() return redirect(url_for('simple_page.index'))
def tab_show(id): form = CommentForm(formdata=request.values) likeform = LikeForm() tab = Tab.query.filter_by(id=id).first_or_404() content = unicode(escape(tab.content)).replace(' ', ' ').replace('\r\n', '<br />') if tab.tabs_type == 5: tab.tab_imgs = tab.tabs_path.split('|') dic_codes = dict([(code.id,code.code_name) for code in Dic_code.query.all()]) if tab.instrument != 13: instrument = dic_codes[tab.instrument] + u'谱' else: instrument = u'乐谱' # 查询评论 type_id: 1-问题,2-曲谱,3-二手交易,4-活动,5-艺人 comments = comments_query(2, id) if current_user.is_anonymous() or current_user.id != tab.uid: tab.hot = tab.hot + 1 db.session.commit() is_like = None if current_user.is_authenticated(): is_like = Like.query.filter_by(uid=current_user.id).filter_by(like_type=1)\ .filter_by(like_id=id).first() if request.method == 'POST' and form.validate_on_submit(): comment = Comment() comment.save(form, current_user.id, 2, id) db.session.commit() return redirect(url_for('tabs.tab_show', id=id)) return render_template('tabs/tab_show.html', form=form, tab=tab, comments=comments, content=content,\ is_like=is_like, likeform=likeform, instrument=instrument)
def reset_password(token): """ Handles the reset password process. """ if not current_user.is_anonymous(): return redirect(url_for("forum.index")) form = ResetPasswordForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() expired, invalid, data = user.verify_reset_token(form.token.data) if invalid: flash("Your password token is invalid.", "danger") return redirect(url_for("auth.forgot_password")) if expired: flash("Your password is expired.", "danger") return redirect(url_for("auth.forgot_password")) if user and data: user.password = form.password.data user.save() flash("Your password has been updated.", "success") return redirect(url_for("auth.login")) form.token.data = token return render_template("auth/reset_password.html", form=form)
def get_twitter_token(): # pragma: no cover """Get Twitter token from session.""" if current_user.is_anonymous(): return None return((current_user.info['twitter_token']['oauth_token'], current_user.info['twitter_token']['oauth_token_secret']))
def question_show(id): form = CommentForm(formdata=request.values) question = Question.query.filter_by(id=id).first_or_404() question.uni_content = unicode(escape(question.content)).replace("\r\n", "<br />") comments = comments_query(1, id) dic_codes = dict([(code.id,code.code_name) for code in Dic_code.query.all()]) big_cates = Dic_code.query.filter_by(parent_id=2).all() for big_cate in big_cates: big_cate.children = Dic_code.query.filter(Dic_code.parent_id == big_cate.type_id).order_by(Dic_code.id) if current_user.is_anonymous() or current_user.id != question.uid: question.hot = question.hot + 1 db.session.commit() if request.method == 'POST' and form.validate_on_submit(): comment = Comment() comment.save(form, current_user.id, 1, id) question.modify_time = datetime.now() question.comments_num = question.comments_num + 1 db.session.commit() return redirect(url_for('questions.question_show', id=id)) return render_template('questions/question_show.html', question=question, big_cates=big_cates, \ dic_codes=dic_codes, comments=comments, form=form)
def delete_command(id): c = Command.query.get_or_404(id) if current_user.is_anonymous() or current_user != c.user: abort(403) db.session.delete(c) db.session.commit() return jsonify(result="OK")
def _edit_command(id): c = Command.query.get_or_404(id) if current_user.is_anonymous() or current_user != c.user: abort(403) c.text = request.form["command"] c.description = request.form["description"] db.session.commit() return jsonify(result="OK")
def _unpublish_command(id): c = Command.query.get_or_404(id) if current_user.is_anonymous() or current_user != c.user: abort(403) c.is_public = False db.session.commit() return jsonify(result="OK")
def demo3_output_detail(): if current_user.is_anonymous(): return redirect(url_for('login')) scenarios_query = current_user.scenarios.all() scenarios = [] for scenario in scenarios_query: scenarios.append(scenario.data) return render_template('demo3_output_detail.html', s=scenarios)
def get_main_page(): if not current_user.is_anonymous(): for key in session.iterkeys(): print key print session[key] return render_template('main.html', nickname=current_user._mail) else: return render_template('index.html')
def is_accessible(self): if current_user.is_anonymous(): return url_for('users.login', next=request.url) if current_user.role.name == 'superadmin': return True
def decorated(*args, **kwargs): if current_user.is_anonymous() is False: return redirect(url_for('index.index')) return f(*args, **kwargs)
def orders(form=None): if form is None and not current_user.is_anonymous(): form = OrderForm() form.populate() return render_template('orders.html', orders=get_orders(), form=form)
def is_current_user_anonymous(): try: result = current_user.is_anonymous() except: result = current_user.is_anonymous return result
def is_accessible(self): return ( not AUTHENTICATE or (not current_user.is_anonymous() and current_user.is_superuser()) )
def is_accessible(self): return ( not AUTHENTICATE or (not current_user.is_anonymous() and current_user.data_profiling()) )
def not_logged_in(form, field): return current_user.is_anonymous()
def show(post_id): ''' comment status 1:通过 2:待审核 3:未通过 4:已删除 5:自动审核通过 :return: ''' # post view_data = p_post(filter={'_id': ObjectId(post_id), 'status': 1}) if "redirect" in view_data: return redirect(view_data['redirect']) if not current_user.is_anonymous(): if current_user.id in view_data['post']['praise_id']: view_data['praise_status'] = True # comment c_filter = { 'case_id': ObjectId(post_id), "$or": [{ 'status': 1 }, { 'status': 2 }, { 'status': 3 }, { 'status': 5 }] } view_data = dict(view_data, **p_comments(request, post_id, filter=c_filter)) # 侧边栏 # 推荐 sort_f = [('praise', -1), ('pv', -1)] filter = { 'status': 1, 'type': view_data['post']['type'], '_id': { '$ne': ObjectId(post_id) } } view_data['recommend'] = recommend_posts(sort=sort_f, filter=filter) # 标签 view_data['post_tags'] = post_tags( filter={'user_id': view_data['post']['user_id']}) view_data['title'] = "{}-{}".format(view_data['post']['title'], config['title'].TITLE) view_data['post_url'] = "{}{}".format( config['post'].DOMAIN, url_for('post.show', post_id=post_id)) view_data['dest'] = "" for tag in view_data["post"]["tag"]: view_data['dest'] = "{},{}".format(view_data['dest'], tag) if "redirect" in view_data: return redirect(view_data['redirect']) ua_key = 'noobw_ua' if ua_key in request.cookies: ua_id = request.cookies.get(ua_key) r = p_post_pv_1(post_id, ua_id) if r: view_data['post']['pv'] += 1 else: r = p_post_pv_1(post_id, 0) if r: view_data['post']['pv'] += 1 resp = make_response( render_template('post/show/post.html', view_data=view_data)) resp.set_cookie('noobw_ua', uuid(), config['cookie'].POST_TIMEOUT) return resp return render_template('{}/post/show/post.html'.format(Theme.THEME_NAME), view_data=view_data)
def unconfirmed(): if current_user.is_anonymous() or current_user.confirmed: return redirect(url_for('site.dash')) return render_template('auth/unconfirmed.html')
def inject_user_pads(): ''' inject list of user pads in template context ''' if not current_user.is_anonymous(): return dict(pads=current_user.pads.all()) return dict(pads=[])
def unconfirmed(): if current_user.is_anonymous() or current_user.confirmed: return redirect(url_for('main.index')) return render_template('auth/unconfirmed.html', Message=Message)
def is_accessible(self): if current_user.is_anonymous(): return url_for('users.login', next=request.path) if current_user.role.name in self.accepted_roles: return True
def index(): if current_user.is_anonymous(): return common_render('splash.jinja') else: return common_render('dashboard.jinja')
def get_google_token(): # pragma: no cover """Get Google Token from session.""" if current_user.is_anonymous(): return session.get('oauth_token') else: return (current_user.info['google_token']['oauth_token'], '')
def unconfirmed(): if current_user.is_anonymous() or current_user.confirmed: return redirect('index') return render_template('unconfirmed.html')
def is_accessible(self): return (not AUTHENTICATE or (not current_user.is_anonymous() and current_user.is_authenticated()))
def filter(self, record): user_id = current_user.email if not current_user.is_anonymous( ) else 'anonymous' record.user_id = user_id return True
def is_accessible(self): if current_user.is_anonymous(): return False if current_user.role.name in self.accepted_roles: return True return False
def decorated_function(*args, **kwargs): if current_user.is_anonymous() or current_user.role.name not in roles: flash('You do not have sufficent permissions to do that!', 'alert-danger') return redirect(request.args.get('next') or '/') return view_function(*args, **kwargs)
def answer_questionnaire(id): questionnaire = questionnaire.query.get_or_404(id) releases = questionnaireRelease.query.filter_by(questionnaire_id=id).all() if len(releases) == 0: flash("对不起,该问卷尚未发布") return render_template("warning.html") release = releases[-1] renderQuestions = get_question_dict(questionnaire) length = len(renderQuestions) if release.mode == 0 and current_user.is_anonymous() == True: flash("对不起,您需要登陆才能回答该问卷") return render_template("warning.html") if release.mode == 1: ip = request.remote_addr ans_count = questionnaireAnswer.query.filter_by( questionnaire_id=id).filter_by(ip=ip).count() if ans_count >= release.times: flash("对不起,您的总回答次数已达到上限") return render_template("warning.html") if release.mode == 2: ip = request.remote_addr current_time = datetime.utcnow() today_ans_count = questionnaireAnswer.query.filter_by( questionnaire_id=id).filter_by(ip=ip).filter( db.cast(questionnaireAnswer.timestamp, db.DATE) == db.cast( current_time, db.DATE)).count() if today_ans_count >= release.times: flash("对不起,您今日的回答次数已达到上限") return render_template("warning.html") if request.method == "POST": questionnaire_answer = questionnaireAnswer( questionnaire_id=id, author_id=current_user.id if current_user.is_anonymous() == False else None, ip=request.remote_addr, timestamp=datetime.utcnow(), ) db.session.add(questionnaire_answer) db.session.commit() for i in range(length): if renderQuestions[i]["question"].relation is None: if renderQuestions[i]["question"].type in [0, 2, 3, 4]: if ('ques_' + str(i) + '.ans') not in request.form and renderQuestions[i][ "question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) elif ('ques_' + str(i) + '.ans') in request.form: if ('ques_' + str(i) + '.ans') in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.ans'], ) db.session.add(qans) elif renderQuestions[i]["question"].type == 1: ans_count = 0 for j in range(len(renderQuestions[i]["options"])): if ('ques_' + str(i) + '.ans-' + str(j)) in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.ans-' + str(j)], ) ans_count += 1 db.session.add(qans) if ans_count == 0 and renderQuestions[i][ "question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) elif renderQuestions[i]["question"].type == 5: if (('ques_' + str(i) + '.lat') not in request.form or ('ques_' + str(i) + '.lng') not in request.form ) and renderQuestions[i]["question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) else: if ('ques_' + str(i) + '.lat') in request.form and ( 'ques_' + str(i) + '.lng') in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.lat'] + " ; " + request.form['ques_' + str(i) + '.lng'], ) db.session.add(qans) else: # 必答情况 must = False relate_question = renderQuestions[i][ "question"].relation.relate_ques relate_option = renderQuestions[i][ "question"].relation.relate_option if renderQuestions[relate_question]["question"].type == 0: if ('ques_' + str(relate_question) + '.ans') not in request.form or request.form[ 'ques_' + str(relate_question) + '.ans'] != str(relate_option): must = False else: must = True elif renderQuestions[relate_question]["question"].type == 1: if ('ques_' + str(relate_question) + '.ans-' + str(relate_option)) not in request.form: must = False else: must = True if renderQuestions[i]["question"].type in [0, 2, 3, 4]: if must == True and ( 'ques_' + str(i) + '.ans') not in request.form and renderQuestions[i][ "question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) elif must == True: if ('ques_' + str(i) + '.ans') in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.ans'], ) db.session.add(qans) elif renderQuestions[i]["question"].type == 1: ans_count = 0 for j in range(len(renderQuestions[i]["options"])): if ('ques_' + str(i) + '.ans-' + str(j)) in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.ans-' + str(j)], ) ans_count += 1 db.session.add(qans) if must == True and ans_count == 0 and renderQuestions[i][ "question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) elif renderQuestions[i]["question"].type == 5: if (('ques_' + str(i) + '.lat') not in request.form or ('ques_' + str(i) + '.lng') not in request.form ) and renderQuestions[i]["question"].must_do == True: db.session.delete(questionnaire_answer) db.session.commit() flash('问题' + str(i + 1) + '是必答题,您还没有作答', 'error') return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length) elif must == True: if ('ques_' + str(i) + '.lat') in request.form and ( 'ques_' + str(i) + '.lng') in request.form: qans = QuestionAnswer( questionnaire_answer_id=questionnaire.id, question_id=renderQuestions[i]["question"].id, answer=request.form['ques_' + str(i) + '.lat'] + " ; " + request.form['ques_' + str(i) + '.lng'], ) db.session.add(qans) db.session.commit() flash("提交成功!感谢您的参与") return render_template("warning.html") return render_template('answer_questionnaire.html', questionnaire=questionnaire, renderQuestions=renderQuestions, length=length)