def index(): """ Main landing page of the kitchen-cloud application """ # Sign up form that appears on the landing page user = Signup(request.form) # get method handling if request.method == 'GET': return render_template('index.html',form=user) # Post method with valid form # Im not sure but I think a lock on the database is required here # to prevent creation of a user between verification and this other # creation. elif request.method == 'POST' and user.validate(): # Save the user to the database and redirect him to is profile. # TODO: figure out how to make a custum validator that # resurns false if that user already exists. db.user_create_signup(user.username.data, user.password.data, user.email.data) # Authenticate and log the user in. auth_and_login(user.username.data) # Send him to is profile now. return redirect(url_for('profile')) # Post method with invalid form, display the template with it's errors else: return render_template('index.html', form=user)
def add_tv(): edit_tv = False if request.method == 'POST': form = request.form cn_name = form.get('cn_name').strip() url_name = form.get('url_name').strip() origin_name = form.get('origin_name').strip() aka_name = list_item(form, 'aka_name') directors = list_item(form, 'directors') casts = list_item(form, 'casts') writers = list_item(form, 'writers') languages = list_item(form, 'languages') countries = list_item(form, 'countries') summary = form.get('summary').strip() is_ended = int(form.get('is_ended', 0)) if not cn_name: error = '请填写剧集中文名称' return render_template('add_edit.html', **locals()) if not url_name: error = '请填写剧集唯一URL' return render_template('add_edit.html', **locals()) TV.addTV(cn_name=cn_name, url_name=url_name, origin_name=origin_name, aka_name=aka_name, directors=directors, casts=casts, writers=writers, languages=languages, countries=countries, summary=summary, is_ended=is_ended) return render_template('add_succ.html', **locals()) return render_template('add_edit.html', **locals())
def checkblogs(): try: urllib2.urlopen("http://foss.rit.edu", timeout=15) except: return render_template('ohno.mak', name='mako') else: student_data = [] for fname in glob.glob(yaml_dir + "*.yaml"): with open(fname) as students: contents = yaml.load(students) if not isinstance(contents, list): raise ValueError("%r is borked" % fname) student_data.extend(contents) student_posts = {} student_quizes = {} student_litreview1 = {} target = datetime(2013, 8, 25) for student in student_data: when = [] if student.get('feed'): print('Checking %s' % student['irc']) feed = feedparser.parse(student['feed']) for item in feed.entries: publish_time = datetime.fromtimestamp(time.mktime (item.updated_parsed)) if publish_time < target: continue when.append(item.updated) else: print('No feed listed for %s!' % student['irc']) student_posts[student['irc']] = len(when) if student.get('quiz1'): print('Checking %s' % student['quiz1']) student_quizes[student['irc']] = student['quiz1'] if student.get('litreview1'): print('Checking %s' % student['litreview1']) student_litreview1[student['irc']] = student['litreview1'] average = sum(student_posts.values()) / float(len(student_posts)) assignments = ['quiz1', 'litreview1'] target_number = int((datetime.today() - target).total_seconds() / timedelta(weeks=1).total_seconds() + 1 + len(assignments)) return render_template('blogs.mak', name='mako', student_data=student_data, student_posts=student_posts, gravatar=gravatar, average=average, target_number=target_number, student_quizes=student_quizes, student_litreview1=student_litreview1)
def add_link(): if request.method == 'POST': url = request.form['link'] from homeland.utils.crawl_douban import crawl_douban res = crawl_douban(url) return render_template('add_link.html', res=res) else: return render_template('add_link.html')
def inner(*args, **kwargs): try: return func(*args, **kwargs) except TemplateError as exc: app.logger.error(u"Caught exception:\n{0}".format(exc.text)) return render_template("error.mako", traceback=exc.text) except Exception: app.logger.exception(u"Caught exception:") return render_template("error.mako", traceback=format_exc())
def checkblogs(): try: urllib2.urlopen("http://foss.rit.edu", timeout=15) except: return render_template("ohno.mak", name="mako") else: student_data = [] for fname in glob.glob(yaml_dir + "*.yaml"): with open(fname) as students: contents = yaml.load(students) if not isinstance(contents, list): raise ValueError("%r is borked" % fname) student_data.extend(contents) student_posts = {} student_names = {} target = datetime(2013, 9, 05) for student in student_data: when = [] if student.get("feed"): print("Checking %s" % student["irc"]) feed = feedparser.parse(student["feed"]) for item in feed.entries: publish_time = datetime.fromtimestamp(time.mktime(item.updated_parsed)) if publish_time < target: continue when.append(item.updated) else: print("No feed listed for %s!" % student["irc"]) student_posts[student["irc"]] = len(when) if student.get("name"): print("Checking %s" % student["name"]) student_names[student["irc"]] = student["name"] average = sum(student_posts.values()) / float(len(student_posts)) target_number = int((datetime.today() - target).total_seconds() / timedelta(weeks=1).total_seconds() + 1 - 2) return render_template( "blogs.mak", name="mako", student_data=student_data, student_posts=student_posts, gravatar=gravatar, average=average, student_names=student_names, target_number=target_number, )
def create_blog(): if request.method == 'GET': return render_template("edit.html") if request.method == 'POST': C = { 'title': request.form.get('title', None), 'content': request.form.get('content', None), } #print C, request.form.items() return render_template("edit.html", C=C) abort(404)
def page_to_render(page_name): """ Returns name of page to render """ try: if page_name not in pages_list: raise exceptions.TopLevelLookupException(page_name) else: return render_template('{}.html'.format(page_name)) except exceptions.TopLevelLookupException: return render_template('{}.html'.format('page_not_found')) return render_template('{}.html'.format(page_name))
def index(): if current_user.is_authenticated(): forms = {} forms['create_household'] = CreateHousehold(csrf_enabled=True) forms['join_household'] = CreateHousehold(csrf_enabled=True) households = Household.query.join(HouseholdMembers).filter_by(user_id=current_user.id).all() return render_template('authenticated.html', current_user=current_user, forms=forms, households=households) else: return render_template('anonymous.html', current_user=current_user)
def admin(): if request.method == 'POST': hashed_pw = crypt(request.form['password'], g.player.password) if hashed_pw != g.player.password: return render_template('admin_login.mako', **{ 'bad_pass': True }) current_app.logger.info('Player: %d logged in as admin' % g.player.id) session['auth_time'] = datetime.now() return redirect(url_for('admin')) if not g.admin_authed: # this admin has yet to log in return render_template('admin_login.mako') # we're golden like jarate return render_template('admin.mako')
def index(): client = EvernoteClient(token=dev_token) userStore = client.get_user_store() user = userStore.getUser() print user.username return render_template('index.mak', name='mako', consumer_key=consumer_key, consumer_secret=consumer_secret)
def test_standard_variables(self): """ Tests that the variables generally available to Flask Jinja templates are also available to Mako templates. """ self._add_template("vars", """ ${config['MAKO_INPUT_ENCODING']} ${request.args} ${session.new} ${url_for('test')} ${get_flashed_messages()} ${injected()} """) with self.test_renderer() as (app, mako): @app.route('/test') def test(): return "test" @app.context_processor def inject(): return {"injected": lambda: "injected"} result = render_template("vars")
def syllabus(): """ Render the syllabus page. """ return render_template("syllabus.mak", name="mako")
def show_entity(group, name): entity = Entity.query.filter(Entity.group == group, Entity.name == name).first() if not entity: return make_response("The specified entity could not be found.", 404) if entity.person: return redirect(url_for('show_person', id=entity.person.id)) query = db.session.query(distinct(Document.id))\ .join(DocumentEntity)\ .filter(DocumentEntity.entity_id == entity.id)\ .order_by(Document.published_at.desc()) pagination = paginate(query, int(request.args.get('page', 1)), 50) doc_ids = [r[0] for r in pagination.items] docs = Document.query\ .options(subqueryload(Document.utterances))\ .filter(Document.id.in_(doc_ids))\ .order_by(Document.published_at.desc())\ .all() return render_template('entities/show.haml', entity=entity, docs=docs, pagination=pagination)
def hello(): if request.method == 'POST': uploadedFile = request.files['file'] w = request.form.get('w') h = request.form.get('h') # text file treat as binary file. # if user wanna post a text file, they would use pastebin / gist. if not uploadedFile: return abort(400) if w and h: pasteFile = PasteFile.create_file_after_crop(uploadedFile, w, h) else: pasteFile = PasteFile.create_by_uploadFile(uploadedFile) db.session.add(pasteFile) db.session.commit() if is_command_line_request(request): return pasteFile.url_i return jsonify({ "url_d" : pasteFile.url_d, "url_i" : pasteFile.url_i, "url_s" : pasteFile.url_s, "url_p" : pasteFile.url_p, "filename" : pasteFile.filename, "size" : pasteFile.size_humanize, "time" : str(pasteFile.uploadTime), "type" : pasteFile.type, }) return render_template('index.html', **locals())
def hello_world(): C = {} content = ur"""使用了Django-pygments组件使内容中的代码块高亮显示. 需要使用`<pre><code></code></pre>`标签把代码块包起来 效果如下: <pre><code> @requires_authorization def somefunc(param1='', param2=0): r'''A docstring''' if param1 > param2: # interesting print 'Gre\'ater' return (param2 - param1 + 1) or None class SomeClass: pass >>> message = '''interpreter ... prompt''' </code></pre> """ # C['text'] = mkdown(content) C['text'] = content return render_template("index.html", **C)
def activity_taxonomies(): form = ActivityForm(request.args) taxonomies = DocumentTaxonomy.summary_for_docs(form.document_ids()) return render_template('dashboard/taxonomies.haml', taxonomies=taxonomies, form=form)
def gen_entry_page(self, file_info, prev_file=None, next_file=None): is_public = file_info.get('public') if is_public and is_public[0].lower() == 'no': return False name = file_info.get('file_name') title = file_info.get('title') content = file_info.get('content') tags = file_info.get('tags') created_at = file_info.get('created_at') is_comment = file_info.get('is_comment') if prev_file: prev_title = prev_file.get('title') prev_link = prev_file.get('link') if next_file: next_title = next_file.get('title') next_link = next_file.get('link') l = locals() l.pop('self') html_content = render_template('entry.html', **l) path = urllib.quote_plus(name) + '.html' if not exists(self.output_path): makedirs(self.output_path) gen = open(join(self.output_path, path), 'wb') gen.write(html_content) gen.close() print 'Gen %s OK.' % name
def participant_page(year, term, username): """ Render a page that shows some stats about the selected participant """ participant_data = {} #{Year: {Term: {Username: pathToYaml}}} yaml_dir = 'scripts/people/' for dirpath, dirnames, files in os.walk(yaml_dir): for student in files: path = dirpath.split('/') student_term = path[len(path) - 1] student_year = path[len(path) - 2] if student_year not in participant_data: participant_data[student_year] = {} if student_term not in participant_data[student_year]: participant_data[student_year][student_term] = {} participant_data[student_year][student_term][student.split('.yaml')[0]] = dirpath + '/' + student if year in participant_data and term in participant_data[year] and username in participant_data[year][term]: with open(participant_data[year][term][username]) as participant_data: participant_data = yaml.load(participant_data) else: abort(404) return render_template( 'participant.mak', name='make', participant_data=participant_data, gravatar=gravatar )
def logout(): """ Logout current user. If success redirects to /logout-success/ and renders logout_success.html template. """ logout_user() return render_template('logout_success.html')
def index(): countries = stats.countries() themes = stats.themes() return render_template('index.slim', countries=countries, themes=themes)
def santa_form(): url = "https://docs.google.com/forms/d/1g4_yI1z1I183OXaUqe1EyMiXW7vtDovZgVQCTHGib1Y/viewform" parameters = { 'title': 'Secret Santa', 'url': url, 'relative_location': relative_location} return render_template('external_form.mako', **parameters)
def oer(): resources = dict() resources['Decks'] = os.listdir(os.path.join(base_dir, 'static', 'decks')) resources['Books'] = os.listdir(os.path.join(base_dir, 'static', 'books')) resources['Challenges'] = os.listdir(os.path.join(base_dir, 'static', 'challenges')) return render_template('oer.mak', name='mako', resources=resources)
def edit_article(id): doc = Document.query.get_or_404(id) if not doc.can_user_edit(current_user): flash("You're not allowed to edit this article.", 'error') return redirect(url_for('show_article', id=id)) form = DocumentForm(obj=doc) author_form = AuthorForm(prefix='author', csrf_enabled=False, obj=doc.author) if request.method == 'POST': if author_form.validate(): # link author form.author_id.data = author_form.get_or_create_author().id if form.validate(): form.populate_obj(doc, request.form.getlist('attachments')) doc.normalise_text() db.session.commit() flash('Article updated.') return redirect(url_for('show_article', id=id)) else: author_form.person_race_id.data = doc.author.person.race.id if doc.author.person and doc.author.person.race else None author_form.person_gender_id.data = doc.author.person.gender.id if doc.author.person and doc.author.person.gender else None return render_template('articles/edit.haml', document=doc, form=form, author_form=author_form)
def home(name=None): """ Really, the main index. Returns a list of (the first three) card widgets for the template to render. The rest are acquired as needed via ajax calls to the /card path. """ if not name: name = m.Package.random(ft.SESSION).name flask.redirect(name) packages = [None] * 4 if name: try: packages[1] = m.Package.by_name(ft.SESSION, name) except m.NoResultFound: packages[1] = m.Package() cards = [ CardWidget(package=packages[i], session=ft.SESSION) for i in range(4) ] cards[1].css_class = 'card center' return render_template('tagger.mak', cards=cards, title=cards[1].package.name)
def index(): if current_user.is_authenticated(): forms = {} forms['create_household'] = CreateHousehold(csrf_enabled=True) forms['join_household'] = CreateHousehold(csrf_enabled=True) households = Household.query.join(HouseholdMembers).filter_by( user_id=current_user.id).all() return render_template('authenticated.html', current_user=current_user, forms=forms, households=households) else: return render_template('anonymous.html', current_user=current_user)
def settings(): status = process_settings() if request.method == "POST" else None update_sites() default = cache.bot.wiki.get_site() kwargs = {"status": status, "default_lang": default.lang, "default_project": default.project} return render_template("settings.mako", **kwargs)
def show_entity(group, name): entity = Entity.query.filter(Entity.group == group, Entity.name == name).first() if not entity: return make_response("The specified entity could not be found.", 404) if entity.person: return redirect(url_for("show_person", id=entity.person.id)) query = ( db.session.query(distinct(Document.id)) .join(DocumentEntity) .filter(DocumentEntity.entity_id == entity.id) .order_by(Document.published_at.desc()) ) pagination = paginate(query, int(request.args.get("page", 1)), 50) doc_ids = [r[0] for r in pagination.items] docs = ( Document.query.options(subqueryload(Document.utterances)) .filter(Document.id.in_(doc_ids)) .order_by(Document.published_at.desc()) .all() ) return render_template("entities/show.haml", entity=entity, docs=docs, pagination=pagination)
def index(): user = isLoggedIn() if user: if not user.group: return redirect(url_for('groups')) return redirect(url_for('menu')) registrationError = None loginError = None if request.method == 'POST': name = request.form.get('name', default = "").lower() email = request.form.get('email').lower() password = request.form.get('password') if request.form.get('register'): # Registration try: return register(name, email, password) except Exception as e: registrationError = e elif request.form.get('login'): # Login try: return login(email, password) except Exception as e: loginError = e return render_template('login.html', registrationError = registrationError, loginError = loginError)
def index(): begin_time = datetime.date(2014, 1, 5) interval = request.args.get('interval', 'day') count = request.args.get('count', None) if interval == "week": days = 7 else: days = 1 if not count: today = datetime.date.today() if interval == "week": count = (today - begin_time).days / 7 else: count = (today - begin_time).days else: count = int(count) start_time = datetime.date(2014, 1, 5) + datetime.timedelta(days=count*days) end_time = start_time + datetime.timedelta(days=days) links = TopLink.range(start_time, end_time)[:30] is_first_page = (count <= 1) return render_template( 'links.html', links=links, start_time=start_time, interval=interval, count=count, is_first_page=is_first_page )
def participants(): """ Render the participants page, which shows a directory of all the students with their forge links, blog posts, assignment links, and etc. """ yaml_dir = 'scripts/people/' student_data = [] for fname in glob.glob(yaml_dir + "*.yaml"): with open(fname) as students: contents = yaml.load(students) if not isinstance(contents, list): raise ValueError("%r is borked" % fname) student_data.extend(contents) assignments = ['litreview1'] target_number = int((datetime.today() - COURSE_START).total_seconds() / timedelta(weeks=1).total_seconds() + 1 + len(assignments)) return render_template( 'blogs.mak', name='mako', student_data=student_data, gravatar=gravatar, target_number=target_number )
def resources(): res = dict() oer_links = [] oer_yaml = app_path("oer.yaml") with open(oer_yaml) as oer_data: oer_links = yaml.safe_load(oer_data) res["links"] = {} res["Decks"] = [] res["Books"] = [] res["Videos"] = [] if os.path.exists(app_path("static", "decks")): res["Decks"] = os.listdir(app_path("static", "decks")) if "decks" in oer_links: res["links"]["decks"] = oer_links["decks"] if os.path.exists(app_path("static", "books")): res["Books"] = os.listdir(app_path("static", "books")) if "books" in oer_links: res["links"]["books"] = oer_links["books"] if os.path.exists(app_path("static", "videos")): res["Videos"] = os.listdir(app_path("static", "videos")) if "videos" in oer_links: res["links"]["videos"] = oer_links["videos"] return render_template("resources.mak", name="mako", resources=res)
def show_article(id): document = Document.query.get_or_404(id) if request.args.get('format') == 'places-json': return jsonify(DocumentPlace.summary_for_docs([document])) return render_template('articles/show.haml', document=document)
def upload_file(): if request.method == 'POST': file = request.files['file'] eassy = file.read() if not eassy: return render_template('index.html') if eassy[:3] == codecs.BOM_UTF8: eassy = eassy[3:] check_result = check_essay(eassy) print(check_result) try: return render_template('demo.html', **check_result) except Exception as e: print(e.text) return render_template('index.html')