def update_profile(): form = UpdateProfileForm(obj=current_user) form.set_locales(current_app.config['LOCALES']) form.populate_obj(current_user) if request.method == 'GET': title_msg = "Update your profile: %s" % current_user.fullname return render_template('account/update.html', title=title_msg, form=form) else: form = UpdateProfileForm(request.form) form.set_locales(current_app.config['LOCALES']) if form.validate(): new_profile = model.User(id=form.id.data, fullname=form.fullname.data, name=form.name.data, email_addr=form.email_addr.data, locale=form.locale.data, ckan_api=form.ckan_api.data) db.session.query(model.User)\ .filter(model.User.id == current_user.id)\ .first() db.session.merge(new_profile) db.session.commit() flash(gettext('Your profile has been updated!'), 'success') return redirect(url_for('.profile')) else: flash(gettext('Please correct the errors'), 'error') title_msg = 'Update your profile: %s' % current_user.fullname return render_template('/account/update.html', form=form, title=title_msg)
def refresh(): R = request.cookies.get('R') if not R: flash(gettext('refresh_token does not exists'), 'error') return redirect(url_for('index')) try: # get tokens params = {"refresh_token": R, 'grant_type': 'refresh_token'} token = api_req(config.get('oauth', 'api_oauth2_token'), params=params, method="POST", authorization="Basic") logging.debug(token) resp = app.make_response(redirect(url_for("index"))) # access_token resp.set_cookie('A', value=token.get('access_token'), max_age=token.get('expires_in')) # refresh_token resp.set_cookie('R', value=token.get('refresh_token'), max_age=60*60*24) flash(gettext('signin succeeded'), 'success') return resp except: logging.error(traceback.format_exc()) flash(gettext('failed to refresh tokens'), 'error') return redirect(url_for('index'))
def users(user_id=None): """Manage users of PyBossa""" try: form = SearchForm(request.form) users = db.session.query(model.User)\ .filter(model.User.admin == True)\ .filter(model.User.id != current_user.id)\ .all() if request.method == 'POST' and form.user.data: query = '%' + form.user.data.lower() + '%' found = db.session.query(model.User)\ .filter(or_(func.lower(model.User.name).like(query), func.lower(model.User.fullname).like(query)))\ .filter(model.User.id != current_user.id)\ .all() require.user.update(found) if not found: flash("<strong>Ooops!</strong> We didn't find a user " "matching your query: <strong>%s</strong>" % form.user.data) return render_template('/admin/users.html', found=found, users=users, title=gettext("Manage Admin Users"), form=form) return render_template('/admin/users.html', found=[], users=users, title=gettext("Manage Admin Users"), form=form) except HTTPException: return abort(403) except Exception as e: current_app.logger.error(e) return abort(500)
def del_category(id): """Deletes a category""" try: category = db.session.query(model.Category).get(id) if category: if len(cached_cat.get_all()) > 1: require.category.delete(category) if request.method == 'GET': return render_template('admin/del_category.html', title=gettext('Delete Category'), category=category) if request.method == 'POST': db.session.delete(category) db.session.commit() msg = gettext("Category deleted") flash(msg, 'success') cached_cat.reset() return redirect(url_for(".categories")) else: msg = gettext('Sorry, it is not possible to delete the only \ available category. You can modify it, click the \ edit button') flash(msg, 'warning') return redirect(url_for('.categories')) else: return abort(404) except HTTPException: return abort(403) except Exception as e: current_app.logger.error(e) return abort(500)
def reset_password(): key = request.args.get('key') if key is None: abort(403) userdict = {} try: userdict = signer.loads(key, max_age=3600, salt='password-reset') except BadData: abort(403) username = userdict.get('user') if not username or not userdict.get('password'): abort(403) user = model.User.query.filter_by(name=username).first_or_404() if user.passwd_hash != userdict.get('password'): abort(403) form = ChangePasswordForm(request.form) if form.validate_on_submit(): user.set_password(form.new_password.data) db.session.add(user) db.session.commit() login_user(user) flash(gettext('You reset your password successfully!'), 'success') return redirect(url_for('.profile')) if request.method == 'POST' and not form.validate(): flash(gettext('Please correct the errors'), 'error') return render_template('/account/password_reset.html', form=form)
def search(): """search -- returns result only if minimum one of the fields was changed """ used = False if request.method == 'POST': result = bib.pubs if request.form['q_title']: used = True result1 = bib.search_by_title(request.form['q_title'], bib.pubs) result = bib.search_by_keyword(request.form['q_title'], bib.pubs) result = result + result1 if request.form['q_author']: used = True lastname, firstname = request.form['q_author'].split(',') result = bib.search_by_author(lastname, firstname, result) if request.form['q_year']: used = True result = bib.search_by_year(request.form.getlist('q_year'), result) if used and request.form['format']: if request.form['format'] == 'html': return render_template('list.html', entries=result, title=gettext("Search results")) if request.form['format'] == 'bibtex': return render_template('bib.html', title=gettext("Search results"), entries=result, navi_search=True) return render_template('search.html', years= bib.get_years_list(), current=staff.get_staff_list(), former=staff.get_staff_list(current=False), navi_search=True)
def sign_in(): if request.is_xhr is True: form2 = Sign_inform() data = request.form["data"] dict = {} for i in data.split("&"): dict[i.split("=")[0]] = i.split("=")[1] (form2.username.data, form2.password.data) = (dict["username"], dict["password"]) if form2.validate(): if models.User().sign_in(dict["username"], dict["password"]): session["username"] = dict["username"] return jsonify(res="success") else: return jsonify(res=gettext("Wrong username or password"), op="sign_in") else: for field_name, field_errors in form2.errors.items(): for error in field_errors: return jsonify(res=error, op="sign_in") form2 = Sign_inform(request.form) if request.is_xhr is False and form2.validate(): if models.User().sign_in(form2.username.data, form2.password.data): session["username"] = form2.username.data return redirect(url_for("index")) else: flash(gettext(u"Wrong username or password"), "sign_in") return redirect(url_for("submit")) else: for field_name, field_errors in form2.errors.items(): for error in field_errors: flash(error, "sign_in") return redirect(url_for("submit"))
def timesince(dt, default=None): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. """ if default is None: default = gettext("just now") now = datetime.utcnow() diff = now - dt years = diff.days / 365 months = diff.days / 30 weeks = diff.days / 7 days = diff.days hours = diff.seconds / 3600 minutes = diff.seconds / 60 seconds = diff.seconds periods = ( (years, ngettext("%(num)s year", "%(num)s years", num=years)), (months, ngettext("%(num)s month", "%(num)s months", num=months)), (weeks, ngettext("%(num)s week", "%(num)s weeks", num=weeks)), (days, ngettext("%(num)s day", "%(num)s days", num=days)), (hours, ngettext("%(num)s hour", "%(num)s hours", num=hours)), (minutes, ngettext("%(num)s minute", "%(num)s minutes", num=minutes)), (seconds, ngettext("%(num)s second", "%(num)s seconds", num=seconds)), ) for period, trans in periods: if period: return gettext("%(period)s ago", period=trans) return default
def send_email(): if 'username' in session: return redirect(url_for("index")) if request.method == "GET": form = Passwordform(request.form) form1 = Sign_upform(request.form) form2 = Sign_inform(request.form) return render_template("anonymous/send_email.html", form=form, form1=form1, form2=form2) form = Passwordform() form.username.data = request.form["data"] if request.method == "POST" and request.is_xhr is True and form.validate(): userdoc = models.User().fetch_userdoc(form.username.data) if not userdoc or not userdoc["email"]: # 未登録のユーザとemailが未登録のユーザーはエラー分岐 return jsonify(res="error", message=gettext("this user don't use email")) # 外部のメールサーバーとソケット通信します keyforreset = client.connectExtServer(userdoc["username"], userdoc["email"]) models.User().add_keyforreset(userdoc["username"], keyforreset) return jsonify( res="success", message=gettext( "an email will be sent to that account's address shortly")) else: return jsonify(res="error", message=gettext("this user don't use email"))
def respond_csv(ty): # Export Task(/Runs) to CSV types = { "task": ( model.Task, handle_task, (lambda x: True), gettext( "Oops, the application does not have tasks to \ export, if you are the owner add some tasks")), "task_run": ( model.TaskRun, handle_task_run, (lambda x: type(x.info) == dict), gettext( "Oops, there are no Task Runs yet to export, invite \ some users to participate"))} try: table, handle_row, test, msg = types[ty] except KeyError: return abort(404) out = StringIO() writer = UnicodeWriter(out) t = db.session.query(table)\ .filter_by(app_id=app.id)\ .first() if t is not None: if test(t): writer.writerow(t.info.keys()) return Response(get_csv(out, writer, table, handle_row), mimetype='text/csv') else: flash(msg, 'info') return respond()
def extension_include(extension_name): file_name = 'extensions/' + extension_name + '/extension.py' if os.path.exists(file_name): execfile(file_name) print gettext(u'[Success] %(extension)s has been correctly included', extension=extension_name) else: print gettext(u'[Error] %(extension)s couldn\'t be included. "extension.py" file is missing.', extension=extension_name)
def search(): """search -- returns result only if minimum one of the fields was changed """ used = False if request.method == 'POST': result = bib.pubs if request.form['q_title']: used = True result1 = bib.search_by_title(request.form['q_title'], bib.pubs) result = bib.search_by_keyword(request.form['q_title'], bib.pubs) result = result + result1 if request.form['q_author']: used = True lastname, firstname = request.form['q_author'].split(',') result = bib.search_by_author(lastname, firstname, result) if request.form['q_year']: used = True result = bib.search_by_year(request.form.getlist('q_year'), result) if used and request.form['format']: if request.form['format'] == 'html': return render_template('list.html', entries=result, title=gettext("Search results")) if request.form['format'] == 'bibtex': return render_template('bib.html', title=gettext("Search results"), entries=result, navi_search=True) return render_template('search.html', years=bib.get_years_list(), current=staff.get_staff_list(), former=staff.get_staff_list(current=False), navi_search=True)
def validate_username(self, field): user = User.query.filter(db.and_( User.username.like(field.data), db.not_(User.id==self.user.id))).first() if user: raise ValidationError, gettext("This username is taken")
def timebefore(dt, default=None): if default is None: default = gettext("passed") now = datetime.utcnow() diff = dt - now years = diff.days / 365 months = diff.days / 30 weeks = diff.days / 7 days = diff.days hours = diff.seconds / 3600 minutes = diff.seconds / 60 seconds = diff.seconds periods = ( (years, ngettext("%(num)s year", "%(num)s years", num=years)), (months, ngettext("%(num)s month", "%(num)s months", num=months)), (weeks, ngettext("%(num)s week", "%(num)s weeks", num=weeks)), (days, ngettext("%(num)s day", "%(num)s days", num=days)), (hours, ngettext("%(num)s hour", "%(num)s hours", num=hours)), (minutes, ngettext("%(num)s minute", "%(num)s minutes", num=minutes)), (seconds, ngettext("%(num)s second", "%(num)s seconds", num=seconds)), ) for period, trans in periods: if period and diff.days >= 0: return gettext("%(period)s", period=trans) return default
def task_n_answers(short_name): app = app_by_shortname(short_name) title = app_title(app, gettext('Redundancy')) form = TaskRedundancyForm() try: require.app.read(app) require.app.update(app) if request.method == 'GET': return render_template('/applications/task_n_answers.html', title=title, form=form, app=app) elif request.method == 'POST' and form.validate(): sql = text('''UPDATE task SET n_answers=:n_answers WHERE app_id=:app_id''') db.engine.execute(sql, n_answers=form.n_answers.data, app_id=app.id) msg = gettext('Redundancy of Tasks updated!') flash(msg, 'success') return redirect(url_for('.tasks', short_name=app.short_name)) else: flash(gettext('Please correct the errors'), 'error') return render_template('/applications/task_n_answers.html', title=title, form=form, app=app) except: return abort(403)
def _import_task(app, handler, form, render_forms): try: empty = True n = 0 n_data = 0 for task_data in handler.tasks(form): n_data += 1 task = model.Task(app_id=app.id) [setattr(task, k, v) for k, v in task_data.iteritems()] data = db.session.query(model.Task).filter_by(app_id=app.id).filter_by(info=task.info).first() if data is None: db.session.add(task) db.session.commit() n += 1 empty = False if empty and n_data == 0: raise importer.BulkImportException( gettext('Oops! It looks like the file is empty.')) if empty and n_data > 0: flash(gettext('Oops! It looks like there are no new records to import.'), 'warning') msg = str(n) + " " + gettext('Tasks imported successfully!') if n == 1: msg = str(n) + " " + gettext('Task imported successfully!') flash(msg, 'success') return redirect(url_for('.tasks', short_name=app.short_name)) except importer.BulkImportException, err_msg: flash(err_msg, 'error')
def validate_number(self, field): """ 验证唯一性 """ res = db.base.find_one({"number": field.data }) if res is not None > 0: raise ValidationError, gettext(u"这个可以不重复的,在该一该吧!")
def validate_number(self, field): """ 验证唯一性 """ res = db.base.find_one({"number": field.data }) print res if res is None: raise ValidationError, gettext(u"请更新存在的记录")
def sign_up(): if request.is_xhr == True: form1 = Sign_upform() data = request.form["data"] dict = {} for i in data.split("&"): dict[i.split("=")[0]] = i.split("=")[1] (form1.username.data, form1.password.data) = (dict["username"], dict["password"]) if dict["email"]: # 以下4行Emailの@のreplace r = re.compile("(%40)") form1.email.data = r.sub("@", dict["email"]) else: form1.email.data = "" if form1.validate(): judge = models.User().sign_up(email=form1.email.data, username=form1.username.data, password=form1.password.data) if not judge: judge = form1.validate_banned_username() if not judge: # 登録成功の分岐 session["username"] = form1.username.data return jsonify(res="success") else: message = gettext(u"This username is used" ) if judge == "username" else gettext( u"This email is used") return jsonify(res=message, op="sign_up") else: for field_name, field_errors in form1.errors.items(): for error in field_errors: return jsonify(res=error, op="sign_up") form1 = Sign_upform(request.form) if request.is_xhr == False and form1.validate(): judge = models.User().sign_up(email=form1.email.data, username=form1.username.data, password=form1.password.data) if not judge: judge = form1.validate_banned_username() if not judge: # 登録成功の分岐 session["username"] = form1.username.data return redirect(url_for("index")) else: message = gettext( u"This username is used") if judge == "username" else gettext( u"This email is used") flash(message, 'sign_up') return redirect(url_for("submit")) else: for field_name, field_errors in form1.errors.items(): for error in field_errors: flash(error, 'sign_up') return redirect(url_for("submit"))
def test_as_default(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') domain = babel.Domain(domain='test') with app.test_request_context(): assert babel.gettext('first') == 'first' domain.as_default() assert babel.gettext('first') == 'erste'
def test_as_default(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale="de_DE") domain = babel.Domain(domain="test") with app.test_request_context(): assert babel.gettext("first") == "first" domain.as_default() assert babel.gettext("first") == "erste"
def get_epicollect_data_from_request(self, r): if r.status_code == 403: msg = "Oops! It looks like you don't have permission to access" \ " the EpiCollect Plus project" raise BulkImportException(gettext(msg), 'error') if not 'application/json' in r.headers['content-type']: msg = "Oops! That project and form do not look like the right one." raise BulkImportException(gettext(msg), 'error') return self.import_epicollect_tasks(json.loads(r.text))
def set_locales(self, locales): """Fill the locale.choices""" choices = [] for locale in locales: if locale == 'en': lang = gettext("English") if locale == 'es': lang = gettext("Spanish") choices.append((locale, lang)) self.locale.choices = choices
def naturalday(value): today = datetime.utcnow().date() delta = value - today if delta.days == 0: return gettext(u"bugün") elif delta.days == -1: return gettext(u"dün") elif delta.days < -1: return gettext(u"%(days)d gün önce", days=abs(delta.days)) return value
def validate_slug(self, field): if len(field.data) > 50: raise ValidationError, gettext("Slug must be less than 50 characters") slug = slugify(field.data) if field.data else slugify(self.title.data)[:50] posts = Post.query.filter_by(slug=slug) if self.post: posts = posts.filter(db.not_(Post.id==self.post.id)) if posts.count(): error = gettext("This slug is taken") if field.data else gettext("Slug is required") raise ValidationError, error
def task_presenter(short_name, task_id): app = app_by_shortname(short_name) task = Task.query.filter_by(id=task_id).first_or_404() if current_user.is_anonymous(): if not app.allow_anonymous_contributors: msg = ("Oops! You have to sign in to participate in " "<strong>%s</strong>" "application" % app.name) flash(gettext(msg), 'warning') return redirect(url_for('account.signin', next=url_for('.presenter', short_name=app.short_name))) else: msg_1 = gettext( "Ooops! You are an anonymous user and will not " "get any credit" " for your contributions.") next_url = url_for( 'app.task_presenter', short_name=short_name, task_id=task_id) url = url_for( 'account.signin', next=next_url) flash(msg_1 + "<a href=\"" + url + "\">Sign in now!</a>", "warning") title = app_title(app, "Contribute") template_args = {"app": app, "title": title} def respond(tmpl): return render_template(tmpl, **template_args) if not (task.app_id == app.id): return respond('/applications/task/wrong.html') #return render_template('/applications/presenter.html', app = app) # Check if the user has submitted a task before tr_search = db.session.query(model.TaskRun)\ .filter(model.TaskRun.task_id == task_id)\ .filter(model.TaskRun.app_id == app.id) if current_user.is_anonymous(): remote_addr = request.remote_addr or "127.0.0.1" tr = tr_search.filter(model.TaskRun.user_ip == remote_addr) else: tr = tr_search.filter(model.TaskRun.user_id == current_user.id) tr_first = tr.first() if tr_first is None: return respond('/applications/presenter.html') else: return respond('/applications/task/done.html')
def list_year(year=None): if year: entries = bib.search_by_year(year) title = gettext("All Publications in %(value)s", value=year) else: entries = bib.pubs title = gettext("All Publications") return render_template('list.html', entries=entries, year=year, title=title, navi_all=True)
def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, lambda n: ngettext('year', 'years', n)), (60 * 60 * 24 * 30, lambda n: ngettext('month', 'months', n)), (60 * 60 * 24 * 7, lambda n: ngettext('week', 'weeks', n)), (60 * 60 * 24, lambda n: ngettext('day', 'days', n)), (60 * 60, lambda n: ngettext('hour', 'hours', n)), (60, lambda n: ngettext('minute', 'minutes', n)) ) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: if d.tzinfo: now = to_user_timezone(datetime.datetime.now()) else: now = datetime.datetime.now() # ignore microsecond part of 'd' since we removed it from 'now' delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return u'0 ' + gettext('minutes') for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break s = gettext('%(number)d %(type)s', number=count, type=name(count)) if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: s += gettext(', %(number)d %(type)s', number=count2, type=name2(count2)) return s
def validate_slug(self, field): if len(field.data) > 50: raise ValidationError, gettext( "Slug must be less than 50 characters") slug = slugify(field.data) if field.data else slugify( self.title.data)[:50] posts = Post.query.filter_by(slug=slug) if self.post: posts = posts.filter(db.not_(Post.id == self.post.id)) if posts.count(): error = gettext("This slug is taken") if field.data else gettext( "Slug is required") raise ValidationError, error
def nodes(): """ API documentation for `api.views.nodes` """ data = { 'uri': '{0}/<organization>/nodes/<account>/<provider>/<region>/'.format(g.api_url_prefix), 'info': gettext('Returns nodes in the region of the provider for the account in the specified organization'), 'parameters': { 'id': gettext('Node ID to use as a filter'), } } return data
def get_csv_data_from_request(self, r): if r.status_code == 403: msg = "Oops! It looks like you don't have permission to access" \ " that file" raise BulkImportException(gettext(msg), 'error') if ((not 'text/plain' in r.headers['content-type']) and (not 'text/csv' in r.headers['content-type'])): msg = gettext("Oops! That file doesn't look like the right file.") raise BulkImportException(msg, 'error') csvcontent = StringIO(r.text) csvreader = unicode_csv_reader(csvcontent) return self.import_csv_tasks(csvreader)
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') # without context assert gettext(u'Hello %(name)s!', name='Peter') == u'Hello Peter!' assert gettext(u'Hello %(name)s!') == 'Hello %(name)s!' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Apples' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apple' with app.test_request_context(): assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!' assert gettext(u'Hello %(name)s!') == 'Hallo %(name)s!' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
def new(): if not require.app.create(): abort(403) form = AppForm(request.form) categories = db.session.query(model.Category).all() form.category_id.choices = [(c.id, c.name) for c in categories] def respond(errors): return render_template('applications/new.html', title=gettext("Create an Application"), form=form, errors=errors) if request.method != 'POST': return respond(False) if not form.validate(): flash(gettext('Please correct the errors'), 'error') return respond(True) info = {} # Add the info items if form.thumbnail.data: info['thumbnail'] = form.thumbnail.data app = model.App(name=form.name.data, short_name=form.short_name.data, description=form.description.data, long_description=form.long_description.data, category_id=form.category_id.data, allow_anonymous_contributors=form.allow_anonymous_contributors.data, hidden=int(form.hidden.data), owner_id=current_user.id, info=info,) cached_apps.reset() db.session.add(app) db.session.commit() # Clean cache msg_1 = gettext('Application created!') flash('<i class="icon-ok"></i> ' + msg_1, 'success') flash('<i class="icon-bullhorn"></i> ' + gettext('You can check the ') + '<strong><a href="https://docs.pybossa.com">' + gettext('Guide and Documentation') + '</a></strong> ' + gettext('for adding tasks, a thumbnail, using PyBossa.JS, etc.'), 'info') return redirect(url_for('.settings', short_name=app.short_name))
def setting(): form = Settingform(request.form) userdoc = models.User().fetch_userdoc(session["username"]) if request.method == "GET": (form.email.data, form.aboutuser.data) = (userdoc["email"], userdoc["aboutuser"]) return render_template("setting.html", form=form, sign_in_username=session['username']) if request.method == "POST" and form.validate(): # サインインしているユーザー以外のメルアドが入力されたらエラー分岐されます if models.User().update_email(username=session["username"], email=form.email.data, aboutuser=form.aboutuser.data): return render_template("setting.html", form=form, sign_in_username=session['username'], update_email_error=gettext( u"This email belongs to another user")) return redirect(url_for("userboards", username=session["username"])) else: return render_template("setting.html", form=form, sign_in_username=session['username'])
def timesince(dt, default=None): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. """ if default is None: default = gettext("just now") now = datetime.utcnow() diff = now - dt periods = ( (diff.days / 365, "year", "years"), (diff.days / 30, "month", "months"), (diff.days / 7, "week", "weeks"), (diff.days, "day", "days"), (diff.seconds / 3600, "hour", "hours"), (diff.seconds / 60, "minute", "minutes"), (diff.seconds, "second", "seconds"), ) for period, singular, plural in periods: if not period: continue singular = u"%%(num)d %s ago" % singular plural = u"%%(num)d %s ago" % plural return ngettext(singular, plural, num=period) return default
def create_board(): form = CreateBoardform(request.form) if request.method == "GET": return render_template("createboard.html", form=form, sign_in_username=session["username"]) if request.method == "POST" and form.validate(): userdoc = models.User().fetch_userdoc(session["username"]) boardli = models.Board().fetch_boardli_from_boardids( userdoc["boardids"] ) # UserCollectionで管理中のBoardのIDにリストを引数にBoardのリストをBoardCollから(ry for board in boardli: # 既に同一ネームのボードが存在した時、templateにエラー出力 if board == form.board.data: return render_template( "createboard.html", form=form, create_board_error=gettext(u"This boardname is created"), sign_in_username=session["username"]) boardid = models.Board().add(form.board.data, form.description.data, session["username"]) userdoc['boardids'].append( boardid) # 新規登録されたボードのIDをUser Collectionでボードfieldに追加 models.User().save(userdoc) return redirect(url_for("userboards", username=session["username"])) else: return render_template("createboard.html", form=form, sign_in_username=session["username"])
def upload_file(): if not session.get('has_cookies', 0) == 1: app.logger.debug("No cookie found") return Response('<html><body><span id="cookies">' + gettext('Please activate cookies ' 'so your uploads can be linked to you.') + '</span></body></html>') if 'file' in request.files and request.files['file']: app.logger.info("Upload form is valid") upload = Upload() # save original name upload.store_file(request.files['file']) Upload.add(upload) Upload.commit() # link to session file_ids = session.get('file_ids', []) file_ids.append(upload.id) session['file_ids'] = file_ids app.logger.info("Saved upload: %s" % upload) else: app.logger.error("No file specified") return redirect(url_for('main'))
def html(self, **kwargs): """ Returns a HTML form posing a randomly chosen question. INPUT: - ``kwargs`` - a dictionary of keyword arguments OUTPUT: - a string; the HTML form TESTS:: sage: from sagenb.notebook.challenge import SimpleChallenge sage: tmp = tmp_dir() + '.sagenb' sage: import sagenb.notebook.notebook as n sage: nb = n.Notebook(tmp) sage: chal = SimpleChallenge(nb.conf()) sage: chal.html() # random '...What is the largest prime factor of 1001?...' """ question = random.choice([q for q in QUESTIONS]) return SIMPLE_TEMPLATE % { 'question': gettext(question), 'untranslated_question': question }
def add_user(): from sagenb.notebook.misc import is_valid_username template_dict = {'admin': g.notebook.user_manager().user(g.username).is_admin(), 'username': g.username} if 'username' in request.values: username = request.values['username'] if not is_valid_username(username): return render_template(os.path.join('html', 'settings', 'admin_add_user.html'), error='username_invalid', username=username, **template_dict) from random import choice import string chara = string.letters + string.digits password = ''.join([choice(chara) for i in range(8)]) if username in g.notebook.user_manager().usernames(): return render_template(os.path.join('html', 'settings', 'admin_add_user.html'), error='username_taken', username_input=username, **template_dict) g.notebook.user_manager().add_user(username, password, '', force=True) message = gettext('The temporary password for the new user <em>%(username)s</em> is <em>%(password)s</em>', username=username, password=password) return current_app.message(message, cont='/adduser', title=_('New User')) else: return render_template(os.path.join('html', 'settings', 'admin_add_user.html'), **template_dict)
def upload_file(): if not session.get('has_cookies', 0) == 1: app.logger.debug("No cookie found") return Response('<html><body><span id="cookies">' + gettext('Please activate cookies ' 'so your uploads can be linked to you.') + '</span></body></html>') if 'file' in request.files and request.files['file']: app.logger.info("Upload form is valid") app.logger.info("request.files is %s" % request.files) upload = Upload() # save original name upload.store_file(request.files['file']) Upload.add(upload) Upload.commit() # link to session file_ids = session.get('file_ids', []) file_ids.append(upload.id) session['file_ids'] = file_ids app.logger.info("Saved upload: %s" % upload) else: app.logger.error("No file specified") return redirect(url_for('main'))
def task_results(job_id=None, key=None): job_status = db.get_job_status(job_id) res = db.get_results(key) if res: res = _convert_ansi(res) else: res = gettext('Waiting for task to start...') # check for failed status if job_status == 'failed': res = gettext('Task failed. Please check logs.') data = { 'key': key, 'results': res, 'status': job_status, } return generate_json_response(data)
def get_fabric_log(result_key=None): log_file = os.path.join(getattr(config, 'LOG_DIR'), '{0}.log'.format(result_key)) try: log = open(log_file, 'r').read() except: log = gettext('Unable to read log file.') return log
def extract_title(html_page): #XXX: This might be better as a regex h = html_page.lower() i = h.find('<title>') if i == -1: return gettext("Untitled") j = h.find('</title>') return html_page[i + len('<title>'):j]
def new_worksheet(): if g.notebook.readonly_user(g.username): return current_app.message(_("Account is in read-only mode"), cont=url_for('worksheet_listing.home', username=g.username)) W = g.notebook.create_new_worksheet(gettext("Untitled"), g.username) return redirect(url_for_worksheet(W))
def test_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') with app.test_request_context(): assert gettext(u'Hello %(name)s!', name='Peter') == 'Hallo Peter!' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 3) == u'3 Äpfel' assert ngettext(u'%(num)s Apple', u'%(num)s Apples', 1) == u'1 Apfel'
def is_valid_response(self, req_args={}, **kwargs): """ Returns the status of a user's answer to the challenge question. INPUT: - ``req_args`` - a string:list dictionary; the arguments of the remote client's HTTP POST request - ``kwargs`` - a dictionary of extra keyword arguments OUTPUT: - a :class:`ChallengeResponse` instance TESTS:: sage: from sagenb.notebook.challenge import SimpleChallenge sage: tmp = tmp_dir() + '.sagenb' sage: import sagenb.notebook.notebook as n sage: nb = n.Notebook(tmp) sage: chal = SimpleChallenge(nb.conf()) sage: req = {} sage: chal.is_valid_response(req).is_valid sage: chal.is_valid_response(req).error_code '' sage: from sagenb.notebook.challenge import QUESTIONS sage: ques, ans = sorted(QUESTIONS.items())[0] sage: ans = ans.split('|')[0] sage: print ques How many bits are in one byte? sage: print ans 8 sage: req['simple_response_field'] = [ans] sage: chal.is_valid_response(req).is_valid False sage: chal.is_valid_response(req).error_code '' sage: req['simple_challenge_field'] = [ques] sage: chal.is_valid_response(req).is_valid True sage: chal.is_valid_response(req).error_code '' """ response_field = req_args.get('simple_response_field', [None])[0] if not (response_field and len(response_field)): return ChallengeResponse(None, '') challenge_field = req_args.get('simple_challenge_field', [None])[0] if not (challenge_field and len(challenge_field)): return ChallengeResponse(False, '') if agree(response_field, gettext(QUESTIONS[challenge_field])): return ChallengeResponse(True, '') else: return ChallengeResponse(False, '')
def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ if not d: return 'Never' if d < datetime.datetime.now() - datetime.timedelta(days=5): return d.date() chunks = ((60 * 60 * 24 * 365, lambda n: ngettext('year', 'years', n)), (60 * 60 * 24 * 30, lambda n: ngettext('month', 'months', n)), (60 * 60 * 24 * 7, lambda n: ngettext('week', 'weeks', n)), (60 * 60 * 24, lambda n: ngettext('day', 'days', n)), (60 * 60, lambda n: ngettext('hour', 'hours', n)), (60, lambda n: ngettext('minute', 'minutes', n))) # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) if not now: if d.tzinfo: now = datetime.datetime.now(d.tzinfo) else: now = datetime.datetime.now() # ignore microsecond part of 'd' since we removed it from 'now' delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return d.date() for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break s = gettext('%(number)d %(type)s', number=count, type=name(count)) if s == '0 minutes': return 'Just now' if s == '1 day': return 'Yesterday' return s + ' ago'
def author_byname(lastname, firstname): """ show all bib entries of one author as <pre> with download links for all bib entries """ return render_template('list.html', title=gettext("Bibliography of %(ln)s, %(fn)s", ln=lastname, fn=firstname), lastname=lastname, firstname=firstname, entries=bib.search_by_author(lastname, firstname), navi_authors=True)
def contact_page(): errors = [] sent_success = False if request.method == 'POST': first_name = request.form['first_name'] last_name = request.form['last_name'] email = request.form['email'] organization = request.form['organization'] phone = request.form['phone'] route = request.form['route'] message = request.form['message'] if not first_name: errors.append(gettext('The name is empty')) if not last_name: errors.append(gettext('The family name is empty')) if not email: errors.append(gettext('The email is empty')) if not route: errors.append(gettext('The reason to contact is empty')) if not message: errors.append(gettext('The message is empty')) if not errors: msg = Message( sender=CSSMATIC_SENDER_EMAIL, recipients=CSSMATIC_ADMIN_EMAILS, body= u'The user %s %s (%s) from %s with phone number %s said:\n\n%s' % (first_name, last_name, email, organization, phone, message), subject='Message from a CSSmatic user') mail.send(msg) sent_success = True return render_template('contact.html', page_id='contact', page_plugins=page_plugins, errors=errors, sent_success=sent_success)
def test_multiple_apps(self): app1 = flask.Flask(__name__) b1 = babel.Babel(app1, default_locale='de_DE') app2 = flask.Flask(__name__) b2 = babel.Babel(app2, default_locale='de_DE') with app1.test_request_context(): assert babel.gettext('Yes') == 'Ja' assert 'de_DE' in b1._default_domain.cache with app2.test_request_context(): assert 'de_DE' not in b2._default_domain.cache
def template(filename, **user_context): """ Returns HTML, CSS, etc., for a template file rendered in the given context. INPUT: - ``filename`` - a string; the filename of the template relative to ``sagenb/data/templates`` - ``user_context`` - a dictionary; the context in which to evaluate the file's template variables OUTPUT: - a string - the rendered HTML, CSS, etc. EXAMPLES:: sage: from sagenb.notebook.template import template sage: s = template(os.path.join('html', 'yes_no.html')); type(s) <type 'unicode'> sage: 'Yes' in s True sage: u = unicode('Are Gröbner bases awesome?','utf-8') sage: s = template(os.path.join('html', 'yes_no.html'), message=u) sage: 'Gr\xc3\xb6bner' in s.encode('utf-8') True """ from sagenb.notebook.notebook import MATHJAX, JEDITABLE_TINYMCE from misc import notebook #A dictionary containing the default context default_context = { 'sitename': gettext('Sage Notebook'), 'sage_version': SAGE_VERSION, 'MATHJAX': MATHJAX, 'gettext': gettext, 'JEDITABLE_TINYMCE': JEDITABLE_TINYMCE, 'conf': notebook.conf() if notebook else None } try: tmpl = env.get_template(filename) except jinja2.exceptions.TemplateNotFound: return "Notebook Bug -- missing template %s" % filename context = dict(default_context) context.update(user_context) r = tmpl.render(**context) return r
def edit_userboard(username, board): boarddoc = models.Board().fetch_boarddoc(username, board) form = EditBoardform(request.form) if boarddoc['username'] != session['username']: return abort(404) # ボードの管理ページに非管理者ユーザーが接続してきた場合404へ if request.method == "GET": return render_template("edit_userboard.html", form=form, boarddoc=boarddoc, sign_in_username=session["username"], placeho_board=boarddoc['board'], placeho_description=boarddoc['description']) if request.method == "POST" and form.validate(): (existing_boards, existing_ids) = models.User().fetch_boards(username, edit="edit") for (existing_board, existing_id) in zip(existing_boards, existing_ids): # 既に存在しているボード名の場合の条件分岐 if existing_board == form.board.data and existing_id != str( boarddoc["_id"]): return render_template( "edit_userboard.html", form=form, boarddoc=boarddoc, placeho_board=boarddoc['board'], sign_in_username=session["username"], placeho_description=boarddoc['description'], edit_board_error=gettext(u"This boardname is created")) models.Board().change_board( username=username, oldboard=board, newboard=form.board.data, description=form.description.data) # Board Collectionの該当docをUpdate models.Img().change_board( username=username, oldboard=board, newboard=form.board.data) # Img Collectionの該当docsをUpdate return redirect( url_for("userboard", username=username, board=form.board.data)) else: return render_template("edit_userboard.html", form=form, boarddoc=boarddoc, sign_in_username=session["username"], placeho_board=boarddoc['board'], placeho_description=boarddoc['description'])
def update_from_form(self, form): D = self.defaults() DS = self.defaults_descriptions() C = self.confs keys = list(set(C.keys() + D.keys())) updated = {} for key in keys: try: typ = DS[key][TYPE] except KeyError: # We skip this setting. Perhaps defaults_descriptions # is not in sync with defaults, someone has tampered # with the request arguments, etc. continue val = form.get(key, '') if typ == T_BOOL: if val: val = True else: val = False elif typ == T_INTEGER: try: val = int(val) except ValueError: val = self[key] elif typ == T_REAL: try: val = float(val) except ValueError: val = self[key] elif typ == T_LIST: val = val.strip() if val == '' or val == 'None': val = None else: val = val.split(',') if typ != T_INFO and self[key] != val: self[key] = val updated[key] = ('updated', gettext('Updated')) return updated