def home(): if current_user.is_authenticated() and (not current_user.active): logout_user() login_form = (not current_user.is_authenticated()) and LoginForm() or None # Gallery items (gallery_items, is_gallery_showlimited, gallery_forms) = get_gi_vars() gi_add_form = current_user.is_authenticated() and Form() or None gi_reorder_form = get_gi_reorder_form() # Events (events_upcoming, events_past, is_events_showlimited, event_forms) = get_event_vars() event_add_form = current_user.is_authenticated() and Form() or None template_vars = dict(login_form=login_form, contact_form=ContactForm(), stc_blocks=get_stc_blocks(), rtc_blocks=get_rtc_blocks(), ic_blocks=get_ic_blocks(), gallery_items=gallery_items, is_gallery_showlimited=is_gallery_showlimited, gallery_forms=gallery_forms, gi_add_form=gi_add_form, gi_reorder_form=gi_reorder_form, events_upcoming=events_upcoming, events_past=events_past, is_events_showlimited=is_events_showlimited, event_forms=event_forms, event_add_form=event_add_form) return render_template("public/home.html", **template_vars)
def data(page): print("*** debug", request) print("*** debug", request.method) #print("*** debug", request.form.viewkeys()) #print("*** debug", request.form.keys()) #print("*** debug", 'upload' in request.form.keys()) #print("*** debug", 'update' in request.form.keys()) # Use basic form for CSRF token form = Form() search_form = SearchForm() bulk_form = BulkDeleteForm() sort_by = Ticker.sort_by(request.args.get('sort', 'created_on'), request.args.get('direction', 'desc')) order_values = '{0} {1}'.format(sort_by[0], sort_by[1]) paginated_tickers = Ticker.query \ .filter(Ticker.user_id == current_user.id) \ .filter(Ticker.search(text(request.args.get('q', '')))) \ .order_by(text(order_values)) \ .paginate(page, 2, True) return render_template('quant/page/data.html', tickers=paginated_tickers, form=form, bulk_form=bulk_form)
def users(): form = Form() # for csrf return render_template("manage.html", form=form, email=g.user.get_username(), environment=app.config.get('ENVIRONMENT'), active_user_user='******')
def switch_delete(switch_id): switch = Switch.q.filter_by(host_id=switch_id).one() if not switch: flash(u"Switch mit ID {} nicht gefunden!".format(switch_id), "error") return redirect(url_for('.switches')) form = Form() if form.validate_on_submit(): delete_switch(switch, current_user) session.session.commit() flash("Die Switch wurde erfolgreich gelöscht.", "success") return redirect(url_for('.switches')) form_args = { 'form': form, 'cancel_to': url_for('.switches'), 'submit_text': 'Löschen', 'actions_offset': 0 } return render_template('generic_form.html', page_title="Switch löschen", form_args=form_args)
def hello_world(): form = Form() package = helloworld.collectTableData() if request.method == 'POST': zip = request.form.to_dict() zip = zip['zipinput'] return redirect(url_for('my_zip', zip=zip)) #my_zip(form.zip) return render_template('somedata.html', package=package)
def index(): name = None form = Form() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=name)
def index(): form = Form() if form.validate_on_submit(): send(dest_ip=form.destination_ip.data, port=form.port.data, src_ip=form.source_ip.data, payload=form.payload.data, count=form.count.data) return "Sent %d packet(s)." % form.count.data return render_template("index.html", form=form)
def delete(title): page = WikiPage.query.filter(WikiPage.title == title).first_or_404() form = Form() if form.validate_on_submit(): db.session.delete(page) db.session.commit() return redirect_for('wiki.index') return render_template('wiki/delete.html', page=page, form=form)
def delete(id): item = Salad.query.get_or_404(id) form = Form() if form.validate_on_submit(): item.delete() db.session.commit() return redirect_for('salad.index') return render_template('salad/delete.html', item=item, form=form)
def delete(id): item = CanonItem.query.get_or_404(id) form = Form() if form.validate_on_submit(): db.session.delete(item) db.session.commit() return redirect_for('canon.index') return render_template('canon/delete.html', item=item, form=form)
def _delete(self, sc_id, transaction, changed_by): where = {"sc_id": sc_id} signoff = self.signoffs_table.select(where, transaction) if not signoff: return Response(status=404, response="{} has no signoff to revoke".format(changed_by)) form = Form(request.args) if not form.validate(): self.log.warning("Bad input: %s", form.errors) return Response(status=400, response=json.dumps(form.errors)) self.signoffs_table.delete(where, changed_by=changed_by, transaction=transaction) return Response(status=200)
def deactivate(user_id): form = Form(request.form) if form.validate_on_submit(): u = User.query.get_or_404(user_id) u.activated = False db.session.commit() newsletter.unsubscribe_all(u) flash( 'User has been deactivated and unsubscribed from all newsletter.') else: flash('Invalid CSRF Token') return redirect_back()
def user_del(user_id): from flask_wtf import Form from lightningwolf_smp.models.user_query import UserQuery uq = UserQuery(db=db) user_object = uq.get_user(user_id) if user_object is None: abort(404) form = Form() if form.validate_on_submit(): user_object.delete() else: flash(u'An error occurred while deleting the user', 'error') return redirect(url_for('user.user_list'))
class PostForm(Form): form = Form({ "content": TextField("hi"), "street": TextField("hi"), "city": TextField("hi"), "state": TextField("hi"), "zip": TextField("hi"), "long": TextField("hi"), "lat": TextField("hi"), "main_category": TextField("hi"), "tags": TextField("hi"), "timestamp": TextField("hi"), "upvotes": TextField("hi"), })
def patch_port_delete(switch_room_id, patch_port_id): switch_room = Room.q.get(switch_room_id) patch_port = PatchPort.q.get(patch_port_id) if not switch_room: flash("Raum mit ID {} nicht gefunden!".format(switch_room_id), "error") return redirect(url_for('.overview')) if not switch_room.is_switch_room: flash("Dieser Raum ist kein Switchraum!", "error") return redirect(url_for('.room_show', room_id=switch_room_id)) if not patch_port: flash("Patch-Port mit ID {} nicht gefunden!".format(patch_port_id), "error") return redirect(url_for('.room_show', room_id=switch_room_id)) if not patch_port.switch_room == switch_room: flash("Patch-Port ist nicht im Switchraum!".format(patch_port_id), "error") return redirect(url_for('.room_show', room_id=switch_room_id)) form = Form() if form.validate_on_submit(): delete_patch_port(patch_port, current_user) session.session.commit() flash("Der Patch-Port wurde erfolgreich gelöscht.", "success") return redirect( url_for('.room_show', room_id=switch_room_id, _anchor="patchpanel")) form_args = { 'form': form, 'cancel_to': url_for('.room_show', room_id=switch_room_id, _anchor="patchpanel"), 'submit_text': 'Löschen', 'actions_offset': 0 } return render_template('generic_form.html', page_title="Patch-Port löschen", form_args=form_args)
def get_list_object_actions(self, call_object=None): actions = self.list_configuration.get('object_actions', []) for action in actions: pre = action.copy() if pre['type'] == self.URL_INTERNAL: pre['url'] = url_for(pre['url']) if pre['key'] == 'delete': pre['form'] = Form() if pre['call'] and call_object is not None: pre['type'] = self.URL_CALL pre = getattr(call_object, pre['call'])(pre) yield pre
def deleteProduct(product_id): currentUser = getCurrentUser() product = session.query(Product).filter(Product.id == product_id).one() # Only all product deletion if the seller is the current user if matchesLoginUser(product.seller): form = Form() if form.validate_on_submit(): session.delete(product) session.commit() return redirect(url_for('userProfile', user_id=product.seller.id)) else: return render_template('delete-product.html', currentUser=currentUser, form=form, product=product) else: return redirect(url_for('home'))
def get_gi_vars(): """Gets gallery item variables.""" gallery_limit = app.config['GALLERY_LIMIT'] if app.config.get('USE_SESSIONSTORE_NOT_DB'): gallery_count = len(session.get('gallery_item', [])) else: gallery_count = (GalleryItem.query.filter_by(active=True).count()) if not gallery_count: default_gallery_items = get_default_gallery_items() gallery_count = len(default_gallery_items) is_gallery_showmore = request.args.get('gallery_showmore', None) == '1' is_gallery_showlimited = ((not current_user.is_authenticated()) and (not is_gallery_showmore) and (gallery_count > gallery_limit)) gallery_items = get_gallery_items() if is_gallery_showlimited: if app.config.get('USE_SESSIONSTORE_NOT_DB'): gallery_items = gallery_items[:gallery_limit] else: gallery_items = gallery_items.limit(gallery_limit) if not app.config.get('USE_SESSIONSTORE_NOT_DB'): gallery_items = gallery_items.all() gallery_forms = {} if current_user.is_authenticated(): for gi in gallery_items: gallery_forms[gi.id] = { 'title': TextEditForm(content=gi.title), 'image': ImageEditForm(image=gi.image), 'content': LongTextEditForm(content=gi.content), 'date_taken': TextEditForm(content=gi.date_taken) } if current_user.is_authenticated(): gallery_forms[gi.id]['delete'] = Form() return (gallery_items, is_gallery_showlimited, gallery_forms)
def deleteReview(product_id, review_id): currentUser = getCurrentUser() product = session.query(Product).filter(Product.id == product_id).one() review = session.query(Review).filter(Review.id == review_id).one() # Only allow review deletion if reviers is the current user if matchesLoginUser(review.user): form = Form() if form.validate_on_submit(): session.delete(review) session.commit() return redirect(url_for('product', product_id=product_id)) else: return render_template('delete-review.html', currentUser=currentUser, form=form, product=product, review=review) else: return redirect(url_for('home'))
def url_tools(): # use global config variables global cfg_itop_cr, cfg_mysql_cr, cfg_agent, cfg_crontab, cfg_logfile # Request data toolForm = Form(csrf_enabled=False) # Check for SCAN Button if request.method == 'POST' and not request.form.get( 'retrieve') is None and toolForm.validate: # Info print('tsk_ctrl: tool->update', file=sys.stdout) # BUILD RETRIEVE COMMAND cmd = ('./tsk_logi.py ./tsk_cron.py agent' + '&') print('tsk_ctrl: UPDATE CMD ', cmd) sys.stdout.flush() sys.stderr.flush() os.system(cmd) print('tsk_ctrl: UPDATE CMD running', cmd) # Check for QUERY Button if request.method == 'POST' and not request.form.get( 'cleanLog') is None and toolForm.validate: # Info print('tsk_ctrl: tool->clean', file=sys.stdout) # Get current time and date. now = datetime.datetime.today() # CleanUp of HTML/XML Log File Directory # lib_logs.delOldLogFiles(now, path_HTML, 'html', cfg_logfile['number'], cfg_logfile['age']) # lib_logs.delOldLogFiles(now, path_XML, 'xml', cfg_logfile['number'], cfg_logfile['age']) # CleanUp old files lib_logs.delOldFiles(path_XML, None, cfg_logfile['number'], cfg_logfile['age']) lib_logs.delOldFiles(path_HTML, None, cfg_logfile['number'], cfg_logfile['age']) lib_logs.delOldFiles(path_INBOX, None, cfg_logfile['number'], cfg_logfile['age']) lib_logs.delOldFiles(path_ARCHIVE, None, cfg_logfile['number'], cfg_logfile['age']) return render_template("site/tools/index.html", form=toolForm)
def post_view(slug): q = filter_by_user(Post.query.filter(Post.slug==slug)) post = q.one_or_none() if post is None: return render_page_template( context={"post": None}, template="site/blog/post.html" ) form = Form() if post.enable_comments and current_settings.enable_comments: form = create_comment_form() if form.validate_on_submit(): post.comments.append(Comment(**form.data)) db.session.commit() flash("Your comment was sent") return redirect(url_for('canella-blog.post', slug=post.slug)) return render_page_template( context={"post": post, 'comment_form':form}, template="site/blog/post.html" )
def register(): # 2.实例化表单类对象 form = Form() print form.validate_on_submit() # 表单验证+csrf if form.validate_on_submit(): # 获取表单数据 user = form.user.data # wtf 表单获取form.user.data form.表单对象的字段.data ps = form.pswd.data ps2 = form.pswd2.data print("*" * 50) print user, ps, ps2 print("*" * 50) else: if request.method == 'POST': print(u'验证失败!!') flash(u'验证失败!!') flash(u'验证成功!!') flash(u'验证成功2!!') flash(u'验证成功23!!') return render_template('register.html', form=form) # 3.传表单对象给模板视图 WTF表单
def deleteUser(user_id): user = session.query(User).filter(User.id == user_id).one() # Only delete user if it matches the current user if matchesLoginUser(user): products = session.query(Product).filter(Product.seller == user).all() form = Form() if form.validate_on_submit(): session.delete(user) if 'user_id' in login_session: del login_session['user_id'] session.commit() return redirect(url_for('home')) else: return render_template('delete-user.html', currentUser=user, form=form, user=user, products=products) else: return redirect(render_template('home'))
def reports(): start = None end = None files = dict() report = Reports() # if request.method == 'POST': # start = datetime.strptime(request.form['start'], '%d.%m.%Y') # end = datetime.strptime(request.form['end'], '%d.%m.%Y') data = report.get_bills(_config('lpu_infis_code')) for bill in data: files[bill.id] = get_files(DOWNLOADS_DIR, str(bill.id)) try: current_app.jinja_env.filters['datetimeformat'] = datetimeformat return render_template('{0}/reports/index.html'.format(module.name), data=data, files=files, form=Form()) except TemplateNotFound: abort(404)
def switch_port_delete(switch_id, switch_port_id): switch = Switch.q.get(switch_id) switch_port = SwitchPort.q.get(switch_port_id) if not switch: flash(u"Switch mit ID {} nicht gefunden!".format(switch_id), "error") return redirect(url_for('.switches')) if not switch_port: flash(u"SwitchPort mit ID {} nicht gefunden!".format(switch_port_id), "error") return redirect(url_for('.switch_show', switch_id=switch_id)) if switch_port.switch != switch: flash( u"SwitchPort mit ID {} gehört nicht zu {}!".format( switch_port_id, switch.host.name), "error") return redirect(url_for('.switch_show', switch_id=switch_id)) form = Form() if form.validate_on_submit(): delete_switch_port(switch_port, current_user) session.session.commit() flash("Der Switch-Port wurde erfolgreich gelöscht.", "success") return redirect( url_for('.switch_show', switch_id=switch_port.switch_id)) form_args = { 'form': form, 'cancel_to': url_for('.switch_show', switch_id=switch_port.switch_id), 'submit_text': 'Löschen', 'actions_offset': 0 } return render_template('generic_form.html', page_title="Switch-Port löschen", form_args=form_args)
def activate(user_id): ''' Activates the user account and sends a welcome message ''' form = Form(request.form) if form.validate_on_submit(): u = User.query.get_or_404(user_id) u.activated = True db.session.commit() msg = Message("Welcome to the QFin Club!", recipients=[u.email]) msg.html = render_template('members/email_welcome.html', user=u) mail.send(msg) # Subscribe to mailinglists newsletter.subscribe_all(u) flash( 'User has been activated, a welcome message has been sent and he has been subscribed to all newsletters.' ) else: flash('Invalid CSRF Token') return redirect_back()
def user_filter(): from lightningwolf_smp.models.user_pager import UserPager from lightningwolf_smp.blueprints.configs.user import configuration pager = UserPager(page=1) pager.initialize(configuration=configuration) action = request.args.get('action', '') if action == '_reset': from flask_wtf import Form form = Form() else: from lightningwolf_smp.forms.user import FormUsernameFilter form = FormUsernameFilter() if form.validate_on_submit(): if action == '_reset': pager.reset_filter_data() else: pager.set_filter_data({'username': form.data['username']}) else: flash(u'An error occurred in filter form', 'error') return redirect(url_for('user.user_list'))
def get_csrf_headers(): # Instantiating a Form makes sure there's a CSRF token available # and puts an hmac key in the session. form = Form() return {'X-CSRF-Token': form.csrf_token._value()}
def delete_func(model_name, model_identifier, is_bootbox=False): try: model_identifier_int = int(model_identifier) except ValueError: abort(404) try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not (('is_deleteable' in v) and v['is_deleteable']): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError( ('No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: identifier_field_name = v['identifier_field'] except KeyError: raise ValueError( ('No identifier field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError( ('No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) model_class = get_model_class(model_classpath, model_name) filter_by_kwargs = { identifier_field_name: model_identifier_int, 'active': True } model = None if app.config.get('USE_SESSIONSTORE_NOT_DB'): model_dict = ( (session.get(model_name, []) and len(session[model_name]) >= (model_identifier_int + 1)) and session[model_name][model_identifier_int] or None) if model_dict: model = model_class(**model_dict) else: model = (model_class.query.filter_by(**filter_by_kwargs).first()) if not model: abort(404) form = Form() if form.validate_on_submit(): title = getattr(model, title_field_name) model_name_friendly = model_name.replace('_', ' ').title() try: if app.config.get('USE_SESSIONSTORE_NOT_DB'): del session[model_name][model_identifier_int] else: model.delete() app.logger.info('{0} deleted: {1}; user: {2}'.format( model_name_friendly, title, current_user)) if is_bootbox: return Response('OK') else: flash("{0} has been deleted.".format(title), 'success') except IntegrityError: db.session.rollback() if is_bootbox: return Response('ERROR') else: flash("Error deleting {0}.".format(title), 'danger') else: if is_bootbox: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))
def add_func(model_name, is_autosave=False): try: v = app.config['EDITABLE_MODELS'][model_name] except KeyError: abort(404) if not (('is_createable' in v) and v['is_createable']): abort(404) try: model_classpath = v['classpath'] except KeyError: raise ValueError( ('No class path defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: title_field_name = v['title_field'] except KeyError: raise ValueError( ('No title field defined in app config\'s ' 'EDITABLE_MODELS for model name "{0}"').format(model_name)) try: weight_field_name = v['weight_field'] except KeyError: weight_field_name = None model_class = get_model_class(model_classpath, model_name) form = Form() if form.validate_on_submit(): model_name_friendly = model_name.replace('_', ' ').title() model = model_class.new_item() if ('image_fields' in v) and v['image_fields']: for k in v['image_fields']: setattr(model, k, placeholder_or_random_sample_image()) if ('long_text_fields' in v) and v['long_text_fields']: for k in v['long_text_fields']: setattr(model, k, placeholder_or_random_sample_text()) if (((not app.config.get('USE_SESSIONSTORE_NOT_DB')) and weight_field_name)): max_weight = model_class.max_weight() setattr(model, weight_field_name, (max_weight is not None and (max_weight + 1) or 0)) try: if app.config.get('USE_SESSIONSTORE_NOT_DB'): if not session.get(model_name, None): session[model_name] = [] fields_to_save = [] for k in ('text_fields', 'long_text_fields', 'image_fields'): if (k in v) and v[k]: fields_to_save.extend(v[k]) values_to_save = {} for k in fields_to_save: values_to_save[k] = getattr(model, k) if ('date_fields' in v) and v['date_fields']: for k in v['date_fields']: val = getattr(model, k, '') if val: val = val.strftime('%Y-%m-%d') values_to_save[k] = val if ('time_fields' in v) and v['time_fields']: for k in v['time_fields']: val = getattr(model, k, '') if val: val = val.strftime('%H:%M:%S') values_to_save[k] = val session[model_name].append(values_to_save) else: model.save() app.logger.info('{0} added: {1}; user: {2}'.format( model_name_friendly, model, current_user)) if is_autosave: return Response('OK') else: flash( '"{0}" has been added.'.format( getattr(model, title_field_name)), 'success') except IntegrityError as e: db.session.rollback() if is_autosave: return Response('ERROR') else: msg = (('violates unique constraint' in e.message) and (('Error: a {0} with title "{1}" ' 'already exists.').format( model_name_friendly, getattr(model, title_field_name))) or "Error adding {0}.".format( getattr(model, title_field_name))) flash(msg, 'danger') else: if is_autosave: return Response('ERROR') else: flash_errors(form) return redirect(url_for("public.home"))