def rest_passwd(): """ 通过email取回密码 """ if request.method == 'GET': form = RecoverPasswordForm(next=request.args.get('next', None)) else: form = RecoverPasswordForm(next=request.args.get('next', None)) if form.validate_on_submit(): # 获取指定的表单数据 email = request.form.get('email', None) username, new_pwd = UserService.rest_pwd_by_email(email) if username and new_pwd: send_new_pwd(username, email, new_pwd) return render_template("account/rest_passwd_success.html", email=email, username=username, form=form) else: print "error: %s %s" % (username, new_pwd) flash(_("Cause an error"), "failed") elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") return render_template("account/rest_passwd.html", form=form)
def copyright(): ''' Muestra el formulario para reportar enlaces ''' g.cache_code = "S" g.category = False g.page_description = _("torrentsfm_desc") g.keywords.clear() g.keywords.update(["torrents search engine popular largest copyright"]) g.title.append(_("Copyright form")) form = ComplaintForm(request.form) if request.method=='POST': if "file_id" in request.form: try: file_id = request.form["file_id"] file_name = request.form.get("file_name",None) data = torrents_data(get_file_metadata(url2mid(file_id), file_name)) if data: form.urlreported.data=url_for("files.download",file_id=file_id,file_name=file_name,_external=True, _secure=False) form.linkreported.data=data['view']["sources"]["tmagnet"]["urls"][0] if "tmagnet" in data['view']["sources"] else data['view']["sources"]["download"]["urls"][0] if "download" in data['view']["sources"] else data['view']["sources"]["download_ind"]["urls"][0] except BaseException as e: logging.exception(e) elif form.validate(): pagesdb.create_complaint(dict([("ip",request.remote_addr)]+[(field.name,field.data) for field in form])) return empty_redirect(url_for('.home', _anchor="sent")) return render_template('copyright.html',form=form)
def order_complete(order_id): if not current_user.rank == 1: return abort(403) order = Order.query.get(order_id) if order is None: return abort(404) if (not order.driver == current_user) or (not order.status == 1): return abort(403) key_enabled = Settings.query.get('key').value if key_enabled == '0': order.status = 2 db.session.add(order) db.session.commit() flash(_('Order has been successfully completed'), 'success') return redirect(url_for('driver_module.orders', t='active')) elif request.method == 'POST': if str(request.form['key']).upper() == order.key: order.status = 2 db.session.add(order) db.session.commit() flash(_('Order has been successfully completed'), 'success') else: flash(_('The key is incorrect'), 'error') return redirect(url_for('driver_module.orders', t='active')) return render_template('driver/complete.html', order=order)
def template_edit(path): # http://127.0.0.1:5000/template/layout.html print path path = os.path.join(current_app.root_path, 'templates', "%s.html" % path) print path html = "" try: f = open(path) html = f.read() f.close() except Exception as ex: flash(_("Template file does not exists"), "error") print html form = TemplateForm(html=html.decode('utf8')) if form.validate_on_submit(): f = open(path, 'w') f.write(form.html.data.encode('utf8')) f.close() flash(_("Saving success"), "success") return redirect(url_for("portal.index")) return render_template("misc/template_edit.html", form=form, path=path)
def edit(username): """ 编辑 users """ user = UserService.get_by_username(username) if not user: abort(404) if request.method == 'GET': form = PeopleEditForm(next=request.args.get('next', None), id=id, obj=user) else: form = PeopleEditForm(next=request.args.get('next', None), id=id) if form.validate_on_submit(): # 获取指定的表单数据 form.populate_obj(user) # 保存数据 UserService.update(user) flash(_("Modify success"), "success") next_url = form.next.data if not next_url or next_url == request.path: next_url = url_for('people.show', username=username) return redirect(next_url) elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") statistic = EntryService.get_statistic_by_author_id(user.id) return render_template("people/edit.html", form=form, people=user, statistic=statistic, form_id=user.id)
def delete_product(product_id): id = int(product_id) result = {} matching = [d for d in session['bag'] if d['pid'] == id] if matching: qty = matching[0]['qty'] img = matching[0]['img'] name = matching[0]['name'] price = matching[0]['price'] session['bag'].remove(matching[0]) session['last'] = matching[0] session['total']['price'] -= qty * price session['total']['counts'] -= qty result['result'] = 'success' else: result['result'] = 'false' session['paidcats'] = get_categories_by_cart(session['bag']) session['total']['delivery'] = 0 for i in session['paidcats']: session['total']['delivery'] = session['total']['delivery'] + i['cost'] result['last'] = session['last'] result['total'] = session['total'] result['success'] = '<a href="/pid' + str(id) + '">' + session['last'][ 'name'] + '</a> ' + _('removed from ') + '<a href="/cart">' + _( 'shopping cart ') + '</a>' result['cartheader'] = ngettext( '%(num)d item', '%(num)d items', session['total']['counts']) % { 'num': session['total']['counts'] } + ' - ' + str(session['total']['price'] + session['total']['delivery']) + ' ' + _('rub.') return json.dumps(result)
class TemplateForm(Form): html = TextAreaField(_("HTML"), validators=[ required(message=_("HTML required"))]) submit = SubmitField(_("Save")) cancel = SubmitField(_("Cancel"))
class LoginForm(Form): email = TextField( u'Email', [validators.Length(min=4, max=50), validators.Required()]) password = PasswordField( _(u'New Password'), [validators.Length(max=250), validators.Required()]) remember_me = BooleanField(_(u'Remember Me')) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.user = None self.email.label.text = _(u'Email') self.password.label.text = _(u'Password') self.remember_me.label.text = _(u'Remember Me') def validate_on_submit(self): rv = Form.validate(self) if not rv: return False m = hashlib.md5() m.update(self.password.data) m = m.hexdigest() user = User.query.filter_by(email=self.email.data, password=m[:-len(m) + 250]).first() if user is None: self.email.errors.append(_(u'Email or Password is invalid.')) return False self.user = user return True
class SoftwareForm(ModelForm): class Meta: model = Software exclude = [ 'created_ip', 'upward_time', 'category_id', 'published_id', 'entry_type', 'slug', 'recommend', 'comment_status', 'view_status', 'entry_status', 'be_modified', 'num_favorites', 'num_retweet', 'num_views', 'num_comments', 'published_time', 'ranking', 'data_version', 'creater_id', 'modifier_id', 'source_type', 'num_uninterested', 'logo' ] # # field_args = { # 'category_name': {'label': _('category name'), 'description': '栏目的名称,必填的哦'} # } @classmethod def get_session(cls): return db.session publish = SubmitField(_("Publish")) draft = SubmitField(_("Draft")) preview = SubmitField(_("Preview")) next = HiddenField()
class RedirectAdmin(sqla.ModelView): column_searchable_list = ('old_path', 'new_path') form_overrides = dict(note=TextAreaField) column_labels = dict( old_path=_('Old Path'), new_path=_('New Path'), note=_('Note'), ) form_widget_args = { 'old_path': { 'style': 'width:320px;' }, 'new_path': { 'style': 'width:320px;' }, 'note': { 'style': 'width:480px; height:80px;' }, } def is_accessible(self): return current_user.is_administrator()
class LabelAdmin(sqla.ModelView): column_list = ('slug', 'title') column_searchable_list = ('slug', 'title') form_overrides = dict(html=TextAreaField) column_labels = dict( slug=_('Slug'), title=_('Title'), html=_('Html Code'), ) form_widget_args = { 'slug': { 'style': 'width:480px;' }, 'title': { 'style': 'width:480px;' }, 'html': { 'style': 'width:640px; height:320px;' }, } def is_accessible(self): return current_user.is_administrator()
class ContactsForm(Form): name = TextField( _(u'Name'), [validators.Length(min=2, max=250), validators.Required()]) reply = TextAreaField( _(u'Reply Text'), [validators.Length(min=2, max=1000), validators.Required()]) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.contacts = None self.name.label.text = _(u'Name') self.reply.label.text = _(u'Reply Text') def upgrade(self, contacts): r1 = self.name.validate(self) r2 = self.reply.validate(self) if r1 and r2: contacts.name = self.name.data contacts.reply = self.reply.data db.session.add(contacts) db.session.commit() self.contacts = contacts return True return False
def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.category = None self.name.label.text = _(u'Category Name') self.num.label.text = _(u'Position') self.visible.label.text = _(u'Visible') self.img.label.text = _(u'Icon')
def confirm(token): if current_user.confirmed: return redirect(url_for('main.index')) if current_user.confirm(token): flash(_('You have confirmed your account. Thanks!')) else: flash(_('The confirmation link is invalid or has expired.')) return redirect(url_for('main.index'))
class UploadLogoForm(Form): img = FileField( _(u'Image'), validators=[FileRequired(), FileAllowed(['png'], _(u'Images only'))]) def validate_img(self): return self.img.validate(self)
class BatchFakeAcountAttachedForm(Form): """ 批量假用户 """ email_list = TextAreaField( _("Your email address"), validators=[required(message=_("email list is required"))]) submit = SubmitField(_("Bacth attached"))
def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.key.label.text = _(u'Confirmation code') self.emoney.label.text = _(u'Payment cards') self.pdel.label.text = _(u'Driver paid') self.phone.label.text = _(u'Phone') self.email.label.text = u'Email' self.link.label.text = u'ВКонтакте' self.pdelcost.label.text = _(u'Cost of order')
def user_validate_rank(form, field): b = True for rank in app.config['RANKS']: if rank[0] == field.data: b = False if current_user.rank < rank[2]: raise ValidationError(_(u'You do not have enough rights.')) if b: raise ValidationError(_(u'No rank with id ') + field.data)
def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) self.product = None self.name.label.text = _(u'Product Name') self.memo.label.text = _(u'Memo') self.img.label.text = _(u'Image') self.price.label.text = _(u'Price') self.category.label.text = _(u'Category') self.category.choices = [(h.id, h.name) for h in Category.query.all()]
class UploadAboutForm(Form): img = FileField(_(u'Image'), validators=[ FileRequired(), FileAllowed(app.config['IMAGES'], _(u'Images only')) ]) def validate_img(self): return self.img.validate(self)
def vote(vtype): g.must_cache = 0 result = {} # don't allow bots to access this feature if g.search_bot: logging.warn("Bot is trying to access to file information.") return abort(404) # check referrer's domain matches this request's domain referrer = urllib2.unquote(request.referrer).decode("utf-8") if not referrer.startswith(request.url_root): logging.warn("Don't allows votes from %s."%referrer) return abort(404) # get data from request try: # get file id from referrer url filemid = fileurl2mid(referrer) # get user's ip and calculates a unique id for this file and user ip = (request.headers.getlist("X-Forwarded-For") or [request.remote_addr])[0] userid = hashlib.sha1(str(filemid)+"_"+ip).hexdigest()[:10] except BaseException as e: logging.warn("Error parsing information from request.") return jsonify(result) if not vtype in VOTES: logging.warn("Wrong vote type: %s."%unicode(vtype)) return jsonify(result) try: # save user vote updated_votes = torrentsdb.save_vote(filemid, userid, vtype) filesdb.update_file({"_id":filemid, "vs.u":Counter(updated_votes.itervalues())}) result["user"] = vtype result["ret"] = ["report", _("Your report has been registered."), "info"] except BaseException as e: logging.warn("Error registering vote.") return jsonify(result) try: f = filesdb.get_file(filemid, "1") rate = rate_torrent(f) result["votes"] = (rate["votes"].get(VERIFIED_VOTE,0), sum(value for vtype, value in rate["votes"].iteritems() if vtype!=VERIFIED_VOTE)) if "flag" in rate: result["flag"] = rate["flag"] result['flag'][1] = _(result['flag'][1]) # translate flag text result["rating"] = int(round(rate["rating"]*5)) except BaseException as e: logging.error("Error retrieving file information: %s."%str(filemid)) return jsonify(result)
def change_password(): form = ChangePasswordForm() if form.validate_on_submit(): if current_user.verify_password(form.old_password.data): current_user.password = form.password.data db.session.add(current_user) flash(_('Your password has been updated.')) return redirect(url_for('main.index')) else: flash(_('Invalid password.')) return render_template("auth/change_password.html", form=form)
class OperatorLogView(MongoSafeView): column_filters = ('admin_user',) column_default_sort = ('action_time', True) column_searchable_list = ('admin_user', 'detail') column_labels = dict(admin_user=_('Admin User'), action_time=_('Action Time'), detail=_('Detail'),) column_formatters = dict( action_time=MongoSafeView._time_formatter, )
class FlatpageAdmin(sqla.ModelView): create_template = "admin/model/a_create.html" edit_template = "admin/model/a_edit.html" column_list = ('title', 'slug', 'seotitle', 'view_on_site') column_searchable_list = ( 'slug', 'title', ) column_formatters = dict(view_on_site=view_on_site) form_excluded_columns = ('body_html', ) form_overrides = dict(seodesc=TextAreaField, body=EDITOR_WIDGET) column_labels = dict( slug=_('Slug'), title=_('Title'), seotitle=_('SEOTitle'), body=_('Body'), seokey=_('SEO Keyword'), seodesc=_('SEO Description'), thumbnail=_('Thumbnail'), template=_('Template'), view_on_site=_('View on Site'), ) form_widget_args = { 'title': { 'style': 'width:480px;' }, 'slug': { 'style': 'width:320px;' }, 'seotitle': { 'style': 'width:480px;' }, 'seokey': { 'style': 'width:480px;' }, 'seodesc': { 'style': 'width:480px; height:80px;' }, 'template': { 'style': 'width:480px;' }, } def is_accessible(self): return current_user.is_administrator() def on_model_change(self, form, model, is_created): pass def after_model_change(self, form, model, is_created): cache_delete(model.shortlink)
def unfollow(username): user = User.query.filter_by(username=username).first() if user is None: flash('Invalid user.') return redirect(url_for('.index')) if not current_user.is_following(user): flash(_('You are not following this user.')) return redirect(url_for('.user', username=username)) current_user.unfollow(user) flash(_('You are not following %s anymore.') % username) return redirect(url_for('.user', username=username))
def follow(username): user = User.query.filter_by(username=username).first() if user is None: flash(_('Invalid user.')) return redirect(url_for('.index')) if current_user.is_following(user): flash(_('You are already following this user.')) return redirect(url_for('.user', username=username)) current_user.follow(user) flash(_('You are now following %s.') % username) return redirect(url_for('.user', username=username))
def captcha(form, field): ''' Validador para controlar que la coinciden la imagen y el texto enviado por el usuario ''' captcha_id = request.form["%s_id" % field.name] cache_data = cache.get("captcha/" + captcha_id) if cache_data is None: raise ValidationError(_('captcha_wrong')) code, consumed = cache_data if field.data != code or not consumed: raise ValidationError(_('captcha_wrong')) cache.delete("captcha/" + captcha_id)
def user_sitemap(): structure = [ [("Home page", url_for(".home"), []), ("Copyright", url_for(".copyright"), [])] + [("Popular searches", None, [(info[-1], url_for(".popular_searches", interval=interval)) for interval, info in POPULAR_SEARCHES_INTERVALS.iteritems()])] + [("Popular torrents", None, [(info[-1], url_for(".popular_torrents", interval=interval)) for interval, info in POPULAR_TORRENTS_INTERVALS.iteritems()])] ] + [ [(category.title, url_for(".browse_category", category=category.url), [(_("popular_category", category=_(singular_filter(category.title)).lower(), categorys=_(category.title).lower()), url_for(".category", category=category.url))] + [(subcategory, url_for(".category", category=category.url, subcategory=clean_query(subcategory)), "%s_subcat_%d"%(category.url, index)) for index, subcategory in enumerate(category.subcategories)])] for category in g.categories ] return render_template('sitemap.html', canonical=url_for("files.user_sitemap", _external=True, _secure=False), structure=structure, column_count=4, column_width=5)
def login(): """ 用户登录 """ # print request.user_agent form = LoginForm(login=request.args.get('login', None), next=request.args.get('next', None)) if 'need_verify' not in session: session['need_verify'] = 0 if form.validate_on_submit(): account_name = form.login.data.strip() password = form.password.data.strip() id, username, nickname, email, authenticated, user_status = UserService.authenticate(account_name, password) if authenticated: if user_status == UserStatus.normal: session.permanent = form.remember.data identity_changed.send(current_app._get_current_object(), identity=Identity(id)) flash(_("Welcome back, %(name)s", name=nickname), "success") # 判断有些错误,暂时先转用户页 # next_url = form.next.data # if not next_url or next_url == request.path \ # or next_url == url_for('account.active_prompt', username=username, email=email)\ # or next_url == url_for('account.banned_prompt', username=username): next_url = url_for('people.index', username=username) session['need_verify'] = 0 return redirect(next_url) elif user_status == UserStatus.inactive: # 跳转到激活提示页面 config_value = int(SystemConfigService.get_by_key('register_validation')) next_url = url_for('account.active_prompt', username=username, email=email, active_type=config_value) return redirect(next_url) elif user_status == UserStatus.banned: # 跳转到禁止页面 next_url = url_for('account.banned_prompt', username=username) return redirect(next_url) else: session['need_verify'] = 1 flash(_("Sorry, invalid login"), "error") return render_template("account/login.html", form=form)
def new(): if not check_rank(3): return abort(403) form = UserForm(request.form) if request.method == 'POST': rv = form.create_new() if rv: flash(_('User successfully created'), 'success') return redirect(url_for('user_module.edit', user_id=form.user.id)) else: flash(_('User creation failed'), 'error') return render_template('user/new.html', form=form)
def submit_link(): ''' Muestra el formulario para agregar enlaces ''' form = SubmitLinkForm(request.form) if request.method=='POST' and form.validate(): feedbackdb.create_links({"links":[link for link in form.urls.data.splitlines()],"ip":request.remote_addr}) flash("link_sent") return redirect(url_for('index.home')) g.title+=_("submit_links") return render_template('pages/submit_link.html',page_title=_("submit_links"),pagination=["translate","translate",1,2],form=form,pname="submitlink")
def signup(): form = SignupForm(next=request.args.get('next', None)) if form.validate_on_submit(): # 获取指定的表单数据 user = User() form.populate_obj(user) user.joined_ip = get_remote_ip() user.homepage = ''#url_for('people.index', username=user.username) # 保存数据 id = UserService.signup(user) if not id: flash(_("Internal error"), "failed") return render_template("account/signup.html", form=form) # identity_changed.send(current_app._get_current_object(), # identity=Identity(id)) # # flash(_("Welcome, %(name)s", name=user['nickname']), "success") # # next_url = form.next.data # # if not next_url or next_url == request.path: # next_url = url_for('people.index', username=user['username']) config_value = int(SystemConfigService.get_by_key('register_validation')) if user.user_status == UserStatus.inactive: if config_value==1: # 发送激活邮件 send_activation_key(user.username, user.email, user.activation_key) else: # 转人工审核提示页面 pass # 跳转到激活页面 next_url = url_for('account.active_prompt', username=user.username, email=user.email, active_type=config_value) else: identity_changed.send(current_app._get_current_object(), identity=Identity(id)) next_url = url_for('people.index', username=user.username) return redirect(next_url) # form.code.errors.append(_("Code is not allowed")) elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") return render_template("account/signup.html", form=form)
def create(): """ 创建新的文章 @param category_id: @return: """ # int_value_verify(category_id) # # category = CategoryService.get_by_id(category_id) # # if not category: # abort(404) # # if category.show_role: # if not g.user or category.show_role > g.user.role: # abort(404) # # new_templates = category.create_template new_templates = '/create.html' form = PostNewForm(next=request.args.get('next', None), entry_type=1) if form.validate_on_submit(): # 获取指定的表单数据 entry = Entry() form.populate_obj(entry) category = CategoryService.get_by_id(int(entry.category_id)) is_draft = False if form.draft.data: is_draft = True if not EntryService.add_or_update(category, entry, is_draft, True): flash(_("Internal error"), "failed") return render_template(new_templates, form=form, category=category, current_category=category) flash(_("Create success"), "success") next_url = form.next.data # todo wqq: 这里能否不做跳转,送回json数据返回ID号,由前端去做处理 if not next_url or next_url == request.path: next_url = url_for('portal.entry', slug=entry.slug) return jsonify(success="true", next_url=next_url) elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") return render_template(new_templates, form=form)
def validate_slug(self, field): # unique if len(field.data) > 50: raise ValidationError, _("Slug must be less than 50 characters") # slug = slugify(field.data) if field.data else slugify(self.title.data)[:50] # posts = Posts.query.filter_by(slug=slug) # if self.posts: # posts = posts.filter(db.not_(Posts.id==self.posts.id)) # if posts.count(): # error = gettext("This slug is taken") if field.data else gettext("Slug is required") # raise ValidationError, error pass
def unsubscribe(): email = request.form['subscribe_email'] if not re.match('(\w+[.|\w])*@(\w+[.])*\w+', email): result = {'error': _('Incorrect Email')} return json.dumps(result) email_isset = Subscribe.query.filter_by(email=email).limit(1) if email_isset.count() == 1: db.session.delete(email_isset[0]) db.session.commit() result = {'success': _('You have unsubscribed from our newsletter')} else: result = {'success': _('You already unsubscribed')} return json.dumps(result)
class TimelineView(MongoSafeView): column_filters = ('action', 'resource', 'admin_user') column_default_sort = ('action_time', True) column_searchable_list = ('action', 'resource', 'admin_user') column_labels = dict(admin_user=_('Admin User'), action_time=_('Action Time'), action=_('Action'), resource=_('Resource'), detail=_('Detail'),) column_formatters = dict( action_time=MongoSafeView._time_formatter, )
def change_passwd(username): """ 改变密码 """ user = UserService.get_by_username(username) if not user: abort(404) statistic = EntryService.get_statistic_by_author_id(user.id) if request.method == 'GET': form = ChangePasswordForm(next=request.args.get('next', None), id=user.id, obj=user) else: form = ChangePasswordForm(next=request.args.get('next', None), id=user.id) if form.validate_on_submit(): # 获取指定的表单数据 form.populate_obj(user) # 保存数据 result = UserService.update_pwd_by_id(user.id, user.password) if result: flash(_("Modify success"), "success") else: flash(_("This old password is error"), "failed") return render_template("people/change_passwd.html", people=user, statistic=statistic, form=form, form_id=user.id) return render_template("people/change_passwd_success.html", people=user, statistic=statistic, form=form, form_id=user.id) elif form.errors: for error_name, error_value in form.errors.iteritems(): print "error: %s %s" % (error_name, error_value) flash(_("Cause an error"), "failed") return render_template("people/change_passwd.html", people=user, statistic=statistic, form=form, form_id=user.id)
class TagAdmin(sqla.ModelView): create_template = "admin/model/a_create.html" edit_template = "admin/model/a_edit.html" column_list = ('name', 'seotitle', 'seokey', 'view_on_site') column_searchable_list = ('name',) form_excluded_columns = ('articles', 'body_html') form_overrides = dict(seodesc=TextAreaField, body=EDITOR_WIDGET) column_formatters = dict(view_on_site=view_on_site) column_labels = dict( slug=_('Slug'), name=_('Name'), seotitle=_('SEOTitle'), body=_('Body'), seokey=_('SEO Keyword'), seodesc=_('SEO Description'), thumbnail=_('Thumbnail'), template=_('Template'), view_on_site=_('View on Site'), ) form_widget_args = { 'slug': {'style': 'width:320px;'}, 'name': {'style': 'width:320px;'}, 'thumbnail': {'style': 'width:480px;'}, 'seotitle': {'style': 'width:480px;'}, 'seokey': {'style': 'width:480px;'}, 'seodesc': {'style': 'width:480px; height:80px;'}, 'template': {'style': 'width:480px;'}, } # Model handlers def on_model_change(self, form, model, is_created): if not model.id: t = Tag.query.filter_by(name=model.name).first() if t: raise Exception('Tag "%s" already exist' % t.name) if not model.seotitle: model.seotitle = model.name if not model.seokey: model.seokey = model.name def after_model_change(self, form, model, is_created): # 中文的路径特别需要注意 cache_delete(model.shortlink) def is_accessible(self): return current_user.is_administrator()
class CommentNewForm(Form): """ 新建 Comment 的表单 """ slug = TextField( _("comment.slug"), description=u'固定地址', validators=[length(min=4, max=50, message=_("Length range: 4 - 50"))]) author_id = HiddenField(_("comment.author_id"), description=u'作者ID', validators=[ required(message=_("author_id is required")), ]) comment = TextAreaField(_("comment.comment"), description=u'回复内容', validators=[ required(message=_("comment is required")), ]) def validate_slug(self, field): # unique pass next = HiddenField() submit = SubmitField(_("Add comment")) cancel = SubmitField(_("Cancel"))
def followers(username): user = User.query.filter_by(username=username).first() if user is None: flash(_('Invalid user.')) return redirect(url_for('.index')) page = request.args.get('page', 1, type=int) pagination = user.followers.paginate( page, per_page=current_app.config['NIBATECH_FOLLOWERS_PER_PAGE'], error_out=False) follows = [{'user': item.follower, 'timestamp': item.timestamp} for item in pagination.items] return render_template('followers.html', user=user, title=_("Followers of"), endpoint='.followers', pagination=pagination, follows=follows)
def configure(manager): accounts_name_i18 = _("Accounts") entries_name_i18 = _("Entries") system_name_i18 = _("System") manager.register(User, UserAdmin, sql.db.session, _("User"), category=accounts_name_i18) manager.register(Role, RoleAdmin, sql.db.session, _("Role"), category=accounts_name_i18) manager.register(Category, CategoryAdmin, sql.db.session, _("Category"), category=entries_name_i18) manager.register(Tag, TagAdmin, sql.db.session, _("Tag"), category=entries_name_i18) manager.register(SystemConfig, SystemConfigAdmin, sql.db.session, _("SystemConfig"), category=system_name_i18)
def change_email_request(): form = ChangeEmailForm() if form.validate_on_submit(): if current_user.verify_password(form.password.data): new_email = form.email.data token = current_user.generate_email_change_token(new_email) send_email(new_email, _('Confirm your email address'), 'auth/email/change_email', user=current_user, token=token) flash(_('An email with instructions to confirm your new email address has been sent to you.')) return redirect(url_for('main.index')) else: flash(_('Invalid email or password.')) return render_template("auth/change_email.html", form=form)
class FavoritesEditForm(Form): """ 编辑 Favorites 的表单 """ title = TextField(_("favorites.title"), description=u'标题', validators=[ required(message=_("title is required")), length(min=1, max=100, message=_("Length range: 1 - 100")) ]) tags = TextField(_("favorites.tags"), description=u'标签', validators=[ length(min=1, max=512, message=_("Length range: 1 - 512")) ]) description = TextField(_("favorites.description"), description=u'描述', validators=[ required(message=_("description is required")), ]) id = HiddenField() next = HiddenField() submit = SubmitField(_("Submit"))
def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() token = user.generate_confirmation_token() send_email(user.email, _('Confirm Your Account'), 'auth/email/confirm', user=user, token=token) flash(_('A confirmation email has been sent to you by email.')) return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form)
def browse_category(category): ''' Renderiza la página de navegacion de categoria ''' g.cache_code = "B" get_query_info(None, category) g.must_cache = 7200 g.title.append(_(singular_filter(g.category.title) + " torrents")) pop_searches = torrentsdb.get_ranking(category)["final_ranking"] g.page_description = _("popular_category_desc", category=_(singular_filter(g.category.title)).lower(), categorys=_(g.category.title).lower()).capitalize() return render_template('browse_category.html', pop_searches = pop_searches)
class LoginForm(Form): """ 登录表单 """ login = TextField(_("Email address"), validators=[ required(message=_("You must provide an email")), email(message=_("A valid email address is required")) ]) password = PasswordField( _("Password"), validators=[required(message=_("You must provide an password"))]) recaptcha = TextField( _("Recaptcha"), validators=[]) # required(message=_("You must provide an captcha")) remember = BooleanField(_("Remember me")) next = HiddenField() def validate_recaptcha(self, field): if 'need_verify' not in session or not session['need_verify']: return if 'verify' not in session or session['verify'] != str( field.data).upper(): raise ValidationError, gettext("This captcha is not matching") submit = SubmitField(_("Login"))
def validate_filename(form, field): data = field.data.readlines() linenum = 1 for line in data: if not len(line.split(',')) == 2: msg = _('CSV file is broken, line %(linenum)s', linenum=linenum) raise ValidationError(msg) elif not line[0].isdigit(): raise ValidationError(_( 'The first column does not contain phone ' 'number, line %(linenum)s', linenum=linenum)) linenum += 1 field.data.seek(0)
def order_message(order): return ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Aviator | '''+_('Order code')+'''</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400,600,700' rel='stylesheet' type='text/css'> </head> <body style="min-width:500px;height:225px;width:100%;background:#DDD;padding-top:50px;"> <div style="font-size:14px;font-family:'Open Sans', sans-serif;padding:10px 25px 30px 25px;width:400px;margin:0px auto;border-radius:3px;background:#FFF;"> <h3 style="font-size:16px;margin-bottom:-7px;">'''+_('Dear')+' '+order.name+'''</h3> <p style="margin-bottom:5px;">'''+_('It\'s your order code')+''': <span style="font-size:15px;font-family: Tahoma, Georgia, sans-serif;background:#777;color:#FFF;padding:3px 5px;border-radius:3px;">'''+order.key+'''</span></p> <span style="font-size:14px;">'''+_('Thank you for your order!')+'''</span> <a style="font-size:14px;color:#777;text-decoration:none;" href="'''+app.config['SITE_URL']+'''">'''+app.config['SITE_NAME']+'''</a>
def reply_message(reply): return ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>'''+_('Thanks for your feedback')+''' | '''+app.config['SITE_NAME']+'''</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400,600,700' rel='stylesheet' type='text/css'> </head> <body style="min-width:500px;width:100%;background:#DDD;padding-top:50px;padding-bottom:50px;"> <div style="font-size:14px;font-family:'Open Sans', sans-serif;padding:10px 25px 30px 25px;width:400px;margin:0px auto;border-radius:3px;background:#FFF;"> <h3 style="font-size:16px;margin-bottom:-7px;">'''+_('Dear')+' '+reply.name+''',</h3> <p style="margin-bottom:5px;">'''+reply.reply+'''</p> <span style="font-size:14px;">'''+_('Thanks for your feedback')+'''</span> <a style="font-size:14px;color:#777;text-decoration:none;" href="'''+app.config['SITE_URL']+'''">'''+app.config['SITE_NAME']+'''</a>
def ekklesia_logged_in(blueprint, token): auth_title = app.config["EKKLESIA_TITLE"] if not token: flash(_("login_fail_with", auth_title=auth_title)) return # ekklesia users have an unique auid, try to find an existing user in our database by auid res_auid = ekklesia.session.get("user/auid/") if res_auid.ok: auid = res_auid.json()["auid"] user = User.query.join(EkklesiaUserInfo).filter_by(auid=auid).scalar() # get user profile for more info res_profile = ekklesia.session.get("user/profile/") res_membership = ekklesia.session.get("user/membership/") if res_profile.ok and res_membership.ok: profile = res_profile.json() membership = res_membership.json() display_name = profile["username"] if user is None: user = User(login_name=auid, display_name=display_name) user.ekklesia_info = EkklesiaUserInfo(auid=auid, user=user) db.session.add(user) logg.info("creating user with auid %s", auid) else: # just update user data logg.info("updating user with auid %s", auid) user.ekklesia_info.update( user_type=membership["type"], verified=membership["verified"], all_nested_group_ids=membership["all_nested_groups"], nested_group_ids=membership["nested_groups"] ) db.session.commit() login_user(user) flash(_("login_success_with", auth_title=auth_title)) next_url = request.args.get('next') redirect(next_url or url_for('questions')) else: flash("Failed to fetch user profile from Ekklesia ID Server", category="error") else: flash("Failed to fetch user id from Ekklesia ID Server", category="error")
def validate_urls(form, field): ''' Validador de los enlaces ''' for link in re.split(r'^.*\\n', form.urls.data): if link[:7] not in form._permited_links: raise ValidationError(_("no_valid_url"))
def upgrade(self, product): r1 = self.name.validate(self) r2 = self.memo.validate(self) r3 = self.img.validate(self) r4 = self.price.validate(self) if r1 and r2 and r3 and r4: category = Category.query.get(self.category.data) if category is None: self.category.errors.append(_(u'Category not found')) return False product.category = category product.name = self.name.data product.memo = self.memo.data if not self.img.data == '' and not self.img.data is None: if check_img(self.img.data): if not product.img == self.img.data: remove_img(product.img) i = Upload.query.filter_by(url=self.img.data).first() db.session.delete(i) product.img = self.img.data product.price = self.price.data db.session.add(product) db.session.commit() self.product = product return True return False