def get(self,imagename): if imagename!="": q = Screengrabs.all() if len(imagename) == 6: q.filter("imagename =",imagename[1:]) else: q.filter("imagename =", imagename) screengrabs = q.fetch(1) for screengrab in screengrabs: if screengrab.imgdata: self.response.headers['Content-Type'] = "image/jpeg" if len(imagename)==6: self.response.out.write(screengrab.thumbdata) else: self.response.out.write(screengrab.imgdata) return #except: # pass # render banner page if users.is_current_user_admin(): self.redirect("/home") user = users.get_current_user() values = { 'login_url': users.create_login_url(self.request.uri) } values.update( {'is_not_logged_in': user == None} ) values.update( {'is_admin':False} ) if user: values.update( {'nick':user.nickname()} ) helpers.render(self, 'index.html', values)
def write_form(self, topic_btn = '/login', link1='/login', text1 ='Log In', status = 'status red', link2 = 'signup', text2 = 'Sign Up', username=''): cursor = Post.query() render(self, 'home_page.html', cursor = cursor, status = status, link1 = link1, text1 = text1, link2 = link2, text2 = text2, username = username, new_topic_btn = topic_btn)
def login(self, username=None, password=None, action=None, endpoint=None, new_user=None): """ prompts the user to login, creates the user if it doesn't exist """ # see if they are trying to login / create user if action or username or password: # if they didn't provide both username and password bounch them if not password or not username: error(403) add_flash("error", "Your missing something!") # if they gave us a username and a password then they are # trying to login if not login_user(username, password): # fail ! error(403) add_flash("error", "Your login has failed!") else: # yay, success. push them to their next point if endpoint: redirect(endpoint) # or home else: redirect("/") return render("/login_front.html", username=username)
def upload(): """アップロード""" if 'POST' != request.method: return render('upload.html') file = request.files['Filedata'] if not file: return render_text(u'error_nofile', status=400) try: source = file.stream.read() except AttributeError: source = file.stream.getvalue() #最大サイズ if 1024 * 512 < len(source): return render_text(u'error_size', status=413) author = request.remote_addr #データ登録 try: model.Match.get_or_insert(source, author=author) except model.ParseError, ex: logger.warn(ex) return render_text(u'error_data', status=415)
def search (request): if not request.GET.has_key('q'): payload = {} else: query_term = "" for term in request.GET['q']: query_term += term try: start = request.GET['start'] except: start = 0 start = int(start) end = int(start) + 10 results_data = get_search_results('YLPjx2rV34F4hXcTnJYqYJUj9tANeqax76Ip2vADl9kKuByRNHgC4qafbATFoQ', query_term, site = site, start = start) if start < int(results_data['totalResultsAvailable']) - 1: next_page = start + 10 next_page_url = '/?%s' % urllib.urlencode({'q':query_term, 'start':next_page}) if start > 0: prev_page = max(0, start - 10) prev_page_url = '/?%s' % urllib.urlencode({'q':query_term, 'start':prev_page}) results = results_data['Result'] payload = locals()#{'results':results, 'results_data':results_data,'query_term':query_term} return render(request, payload, 'news/search.html')
def write_form(self, post_id): post = Post.get_by_id(int(post_id)) qry1 = Comment.query() cursor = qry1.filter(Comment.post_id == int(post_id)) username = self.request.cookies.get('username') if username: render(self, 'post_page.html', post = post, post_id = int(post_id), username = username, cursor = cursor) else: render(self, 'post_page_2.html', post = post, post_id = int(post_id), cursor = cursor)
def index(self,search=None): """ returns page w/ media embedded + comments """ frontpage_media = m.Media.query. \ order_by(m.Media.created_at.desc()). \ limit(10).all() return render('/media/index.html',frontpage_media=frontpage_media)
def get(self): user = users.GetCurrentUser() if (user): # user has already logged in self.redirect ('/home') else: # The user has not logged in yet, show the landig page tValues = { 'page_title': 'Lenny.in - lennified notifications for gmail' } self.response.out.write(helpers.render ("down.html",tValues))
def get(self, command=None): user = users.GetCurrentUser() if (user): if (command=='/done'): self.setSMSdone() self.redirect('/home/control') return #TODO: only if SMS if ('/control' in command and self.hasSeenSMS()): if ('/dm_store' in command): self.enableDMStore() return if ('/dm_destroy' in command): self.disableDMStore() return if ('/enable' in command): self.enableAlert() return if ('/disable' in command): self.disableAlert() return self.showControlPanel() return # The user is already logged in, decide her fate depending on the extent to which # registration has been completed. -> step1, step2, control panel view={} view['user_email'] = users.GetCurrentUser() view['logout_url'] = users.create_logout_url("/") page="control.html" state = self.getUserState() if (state == 1): ''' user has not OAuthed Gmail, as her to ''' view['page_title'] = 'Step 1 - Gmail Authentication - Lenny.in' page = "step1.html" if (state == 2): ''' user has not OAuthed Gmail, as her to ''' view['page_title'] = 'Step 2 - Twitter Authentication - Lenny.in' page = "step2.html" if (state == 3): ''' user has not OAuthed Gmail, as her to ''' view['page_title'] = 'Step 2 - Twitter Authentication - Lenny.in' page = "step3.html" if (self.hasSeenSMS()): self.redirect ("/home/control") self.response.out.write(helpers.render (page,view)) else: self.redirect (users.create_login_url("/home"))
def post(self): # Not implemented. Pass error. error = 'Traditional login not implemented. Please use Twitter \ OAuth.' values = { 'title': 'Log-in' } if error: values['error'] = error self.response.out.write(render('login.html', values))
def get(self): values = { 'error': '<strong>Warning:</strong> OAuth ' 'login did not complete.', 'message': 'OAuth is not yet implemented correctly. This ' 'is a placeholder for the appropriate handler.' } self.response.out.write(render('error.html', values)) return
def save_down(self, html=None, txt=None): """ will save down a file to disk """ # determine the path save_path = self.get_save_path() # render it if html: out = render("/htmlnode.html", source=html, node=self) if txt: out = render("/textnode.html", source=txt, node=self) # write it to disk with codec.open(save_path, "w") as fh: fh.write(out) self.saved_down = True return save_path
def login(self,username=None,password=None,action=None,endpoint=None, new_user=None): """ prompts the user to login, creates the user if it doesn't exist """ # see if they are trying to login / create user if action or username or password: # if they didn't provide a password than we need to # either create a new user or prompt them for pass if one exists if not password: user = m.User.get_by(handle=username) if user: return render('/login_password.html',username=username) else: return render('/login_new_user.html',username=username) # if we are creating a new user, do so if new_user == 'true': user = m.User(handle=username) user.password = password m.session.commit() # if they gave us a username and a password then they are # trying to login if not login_user(username,password): # fail ! add_flash('error','Your login has failed!') else: # yay, success. push them to their next point if endpoint: redirect(endpoint) # or home else: redirect('/') return render('/login_front.html',username=username)
def save_down(self): """ save down the body as a html file """ html = render( "/feedentrysavedown.html", source=self.source, title=self.title, body=self.body, timestamp=self.timestamp ) path = self.get_save_path() print "saving: %s" % path with open(path, "w") as fh: fh.write(html) self.saved_down = True return path
def save_down(self): """ save down a txt file """ html = render( "/commentsavedown.txt", title=self.title, comment=self.comment, author=self.get_author().get_user().handle ) path = self.get_save_path() print "saving: %s" % path with open(path, "w") as fh: fh.write(html) self.saved_down = True return path
def index(): """ホーム""" #新着のリプレイ matches = model.Match.all(limit=10) #TODO: 1ヶ月以内のStatistics #キャラ別の使用数、勝率? game_servers = fetch_game_servers() or '' return render('index.html', matches=matches, game_servers=game_servers)
def display(key,value,Max=False): if(len(key) == len(value)): if(Max): maxindex = 0 match = max(value) maxs = [] for i in range(len(value)): if(value[i]>=match): maxindex = i maxs.append(maxindex) # returns list of maximum's indexes return maxs else: Sum = 0 for j in range(len(value)): Sum = Sum + value[j] maxs = display(key,value,True) for i in range(len(key)): perc = (value[i]*100.0/Sum) result = square*int(perc) _perc_ = "(" +str(perc)[:4]+ "%)" # highlights maximum's if i in maxs: to_show = "%s %s %s"%(render(key[i]),render(_perc_),render(result)) else: to_show = "%s %s %s"%(key[i],_perc_,result) if(value[i]!=0): to_show = "%s [%d %s]"%(to_show,value[i],grammer(value[i])) print to_show else: print to_show else: print "you messed up.."
def home(): post_id = get_post_id_for_session(session) if request.method == 'POST': file1 = request.files['file1'] file2 = request.files['file2'] if file1 and allowed_file(file1.filename): filename = secure_filename(file1.filename) full_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) file1.save(full_path) key = upload_to_s3(app.config, full_path) #else: return render('home.html')
def get(self, path): if path == '/people': at = int(self.request.get('at') or 0) by = int(self.request.get('by') or 10) if at: query = TwitterAccount.all().order('screen_name') query = query.filter('__key__ >', at) else: query = TwitterAccount.all().order('screen_name') query = query.fetch(by) values = { 'people': [p for p in query], 'title': 'List of people' } self.response.out.write(render('list-people.html', values)) else: values = { 'error': '<strong>Warning:</strong> page unavailable.', 'message': 'This list page is not yet implemented.' } self.response.out.write(render('error.html', values))
def search(): """検索""" params = dict( char=request.args.get('char') or None, win_lose=request.args.get('win_lose') or None, stage=request.args.get('stage') or None, span=request.args.get('span') or None, version=request.args.get('version') or None, ) matches = None if len(request.args): matches = model.Match.search( page=int(request.args.get('page') or 1), **params) return render('search.html', matches=matches, params=params)
def default(self,*args,**kwargs): # TODO: support multiple albums @ a time albums = [] for arg in args: # we'll assume it's an id for now found = m.Album.get(arg) if found: albums.append(found) if not albums: add_flash('error','album not found!') cherrypy.session['current_albums'] = [i.id for i in albums] return render('/albums/single.html',album=albums[0])
def resent_activation_email(): """ resent activate email to user :return: """ user = current_identity if user.authenticate_status is False: context = { "active_url": flask.url_for("active_user", payload=url_serializer.dumps(user.session_id), _external=True), "name": user.username } html_rendered = render("confirm.html", context) send_local_mail([user.email], "*****@*****.**", "Ohlife Confirmation", html_rendered , username=credential["smtp_username"], password=credential["smtp_password"], server=credential["smtp_server"], files=[]) return "200" else: return flask.abort(404)
def register(): """ register user using restuful api :return: """ request = flask.request.get_json() user_email = request["email"] user_password = request["password"] user = User(username=user_email, password=user_password, email=user_email) context = { "active_url": flask.url_for("active_user", payload=url_serializer.dumps(user.session_id), _external=True), "name": user.username } html_rendered = render("confirm.html", context) send_local_mail([user.email], "*****@*****.**", "Ohlife Confirmation", html_rendered , username=credential["smtp_username"], password=credential["smtp_password"], server=credential["smtp_server"], files=[]) db.session.add(user) db.session.commit() return "OK"
def get(self, id, values): values["show_form"] = True m = get_m(self.request) if m == messages.UNKNOWN_ACTION: values["show_form"] = False self.response.status = 400 elif id: student = Student.get_by_id(long(id)) if student: values["student"] = student values["id"] = id else: m = messages.STUDENT_ID_NOT_FOUND values["show_form"] = False update_m(values, m) self.response.write(render("templates/aluno.html", values))
def send_mail(users_text_list): """ traverse user list and send emails :param users_text_list: """ today = arrow.now().format('YYYY-MM-DD') # subject = u"今天是 %s - 你今天过得怎么样啊?" % today subject = gnu_translations.gettext("Today is %s - How's everything going ?") % today for user in users_text_list: if users_text_list[user] is not None: time_ago = users_text_list[user]["days_ago_str"] data = users_text_list[user]["text"] file_name = users_text_list[user]["file_name"] if file_name != "": file_extension = file_name.split(".")[1].strip() with open(file_name, "rb") as fp: pic_encoded = '"' + "data:image/" + file_extension + ";base64," + bytes.decode( base64.b64encode(fp.read())) + '"' else: pic_encoded = '""' replaceable = get_replacable(today) context = { "data": data, "time_ago": time_ago, "replaceable": replaceable, "save_key": bytes.decode(save_signer.sign(user.session_id)), "name": user.username, "pic_encoded": pic_encoded } html_rendered = render("sender.html", context) receiver = user.username + "<" + user.email + ">" sender = "OhLife<" + credential["smtp_server"] + ">" # send_local_mail([receiver], sender, subject, html_rendered, []) send_local_mail(mail_to=[receiver], mail_from=sender, subject=subject, text=html_rendered, files=[], username=credential["smtp_username"] , password=credential["smtp_password"], server=credential["smtp_server"])
def showControlPanel(self): view={} view['logout_url'] = users.create_logout_url("/") view['user_email'] = users.GetCurrentUser() view['page_title'] = 'Control Panel - Lenny.in' page = "control.html" t = lenny.OAuthToken.all() t.filter("user ="******"scope =", lenny.SCOPE) t.filter("type =", 'access') results = t.fetch(1) for r in results: view['monitor_email'] =r.email t = tweetapp.OAuthAccessToken.all() t.filter("user ="******"background:#888;" if (r.dm_store == None or r.dm_store == 'false'): view['dm_url']='/home/control/dm_store' view['save_or_dont']="preserve" else: view['dm_url']='/home/control/dm_destroy' view['save_or_dont']="don't store" self.response.out.write(helpers.render (page,view))
def search(request): if not request.GET.has_key('q'): payload = {} else: query_term = "" for term in request.GET['q']: query_term += term try: start = request.GET['start'] except: start = 0 start = int(start) end = int(start) + 10 results_data = get_search_results( 'YLPjx2rV34F4hXcTnJYqYJUj9tANeqax76Ip2vADl9kKuByRNHgC4qafbATFoQ', query_term, site=site, start=start) if start < int(results_data['totalResultsAvailable']) - 1: next_page = start + 10 next_page_url = '/?%s' % urllib.urlencode({ 'q': query_term, 'start': next_page }) if start > 0: prev_page = max(0, start - 10) prev_page_url = '/?%s' % urllib.urlencode({ 'q': query_term, 'start': prev_page }) results = results_data['Result'] payload = locals( ) #{'results':results, 'results_data':results_data,'query_term':query_term} return render(request, payload, 'news/search.html')
def buttons(request): return render(request, {}, 'news/buttons.html')
def get(self): values = { 'title': 'Log-in' } self.response.out.write(render('login.html', values))
def aboutus(request): return render(request, {}, 'news/aboutus.html')
#!/usr/local/bin/python3 import cgi print("Content-type: text/html") import helpers print(helpers.render('header', {'title': "UP DevCamp"})) print(''' <ul><a href="tracks.py">Tracks</ul> <ul><a href="resources.py">Resources</ul> ''') print(helpers.render('footer'))
def match(id): match = model.Match.get_by_id(id) abort_if(not match) return render('match.html', match=match)
def default(self,id): user = m.User.get(id) if not user: add_flash('error',"Can't find user") return render('/users/single.html',user=user)
def train(self, epochs, learning_rate, content_layer, content_weight, style_layers, style_weight, tv_weight, retrain=False): # Check if there is training data available and initialize generator network self.__check_for_examples() # Initialize and process images and placeholders to be used for our descriptors art, art_shape = helpers.load_img_to(self.paths['style_file'], height=self.train_height, width=self.train_width) art_shape = [1] + art_shape art = art.reshape(art_shape).astype(np.float32) # Generator Network ops variable_placeholder = tf.placeholder(dtype=tf.float32, shape=art_shape) self.net.build(variable_placeholder) variable_img = self.net.output # VGG Network ops with tf.name_scope('vgg_style'): style_model = vgg16.Vgg16() style_model.build(art, shape=art_shape[1:]) with tf.name_scope('vgg_content'): content_placeholder = tf.placeholder(dtype=tf.float32, shape=art_shape) content_model = vgg16.Vgg16() content_model.build(content_placeholder, shape=art_shape[1:]) with tf.name_scope('vgg_variable'): variable_model = vgg16.Vgg16() variable_model.build(variable_img, shape=art_shape[1:]) # Continue from a pretrained model if retrain: print("tryue") name = os.path.basename(self.paths['style_file']).replace('.jpg', '') saver = tf.train.Saver() saver.restore(self.session, "%s/%s/%s" % (self.paths['trained_generators_dir'], name, name)) # Loss ops with tf.name_scope('loss'): if content_weight is 0: content_loss = tf.constant(0.) else: content_loss = helpers.get_content_loss(variable_model, content_model, content_layer) * content_weight if style_weight is 0: style_loss = tf.constant(0.) else: style_loss = helpers.get_style_loss(variable_model, style_model, style_layers) * style_weight if tv_weight is 0: tv_loss = tf.constant(0.) else: tv_loss = helpers.get_total_variation(variable_img, art_shape) * tv_weight total_loss = content_loss + style_loss + tv_loss # Optimization ops with tf.name_scope('optimization'): optimizer = tf.train.AdamOptimizer(learning_rate) trainable_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope="generator") grads = optimizer.compute_gradients(total_loss, trainable_vars) update_weights = optimizer.apply_gradients(grads) # Populate the training data logging.info("Initializing session and loading training images..") example = self.__next_example(height=art_shape[1], width=art_shape[2]) self.session.run(tf.local_variables_initializer()) self.session.run(tf.global_variables_initializer()) # Initialize threads and begin training logging.info("Begining training..") coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) start_time = time.time() for i in range(epochs): self.net.is_training = True # Get next training image from batch and reshape it to include a batch size of 1 training_img = self.session.run(example) / 255. training_img = training_img.reshape([1] + list(training_img.shape)).astype(np.float32) # Initialize new feed dict for the training iteration and invoke the update op feed_dict = {variable_placeholder: training_img, content_placeholder: training_img} _, loss = self.session.run([update_weights, total_loss], feed_dict=feed_dict) if self.print_training_status and i % self.train_n == 0: logging.info("Epoch %06d | Loss %.06f" % (i, loss)) in_path = self.current_path + '/../lib/images/content/nyc.jpg' input_img, input_shape = helpers.load_img_to(in_path, height=self.train_height, width=self.train_width) input_img = input_img.reshape([1] + input_shape).astype(np.float32) path_out = self.current_path + '/../output/' + str(start_time) + '.jpg' img = self.session.run(variable_img, feed_dict={variable_placeholder: input_img}) helpers.render(img, path_out=path_out) # Alert that training has been completed and print the run time elapsed = time.time() - start_time logging.info("Training complete. The session took %.2f seconds to complete." % elapsed) coord.request_stop() coord.join(threads) self.__save_model(trainable_vars)
with tf.Session() as sess: # Check if there is a model trained on the given style if not os.path.isdir(TRAINED_MODELS_PATH + STYLE): print("No trained model with the style '%s' was found." % STYLE) list_styles() exit(1) # Load and initialize the image to be stlylized input_img, _ = helpers.load_img(INPUT_PATH) input_img = tf.convert_to_tensor(input_img, dtype=tf.float32) input_img = tf.expand_dims(input_img, axis=0) # Initialize new generative net with tf.variable_scope('generator'): gen = generator.Generator() gen.build(tf.convert_to_tensor(input_img)) sess.run(tf.global_variables_initializer()) # Restore previously trained model ckpt_dir = TRAINED_MODELS_PATH + STYLE saved_path = ckpt_dir + "/{}".format(STYLE) saver = tf.train.Saver() saver.restore(sess, saved_path) # Generate stylized image img = sess.run(gen.output) # Save the generated image and close the tf session helpers.render(img, path_out=OUT_PATH) sess.close()
def get(self): self.response.out.write(render('home.html'))
def get(self, values): settings = Settings.get_instance() for category in settings: values[category] = sorted(settings[category].values.items()) self.response.write(render("templates/configuracoes.html", values))
def write_form(self, err_msg=''): render(self, 'log_in.html', err_msg = err_msg)
def generate(self): config = get_config() # Download data from Google docs etc response = requests.get(config['riskAssessmentCsvUrl']) risk_assessments_file = open('%s/risk-assessments.csv' % config['dataDir'], 'w') risk_assessments_file.write(response.text) risk_assessments_file.close() # Load risk assessments from CSV risk_assessments = [] with open('%s/risk-assessments.csv' % config['dataDir']) as csv_file: assessments_csv = csv.DictReader(csv_file) for item in assessments_csv: risk_assessment = models.RiskAssessment() risk_assessment.employer = csv_string(item['employer']) risk_assessment.employer_address = csv_string(item['employer address']) risk_assessment.employer_website_url = csv_string(item['employer website url']) risk_assessment.workplace = csv_string(item['workplace']) risk_assessment.workplace_address = csv_string(item['workplace address']) risk_assessment.workplace_website_url = csv_string(item['workplace website url']) risk_assessment.workplace_approximate_number_of_workers = csv_int(item['workplace approximate number of workers']) risk_assessment.risk_assessment_status = csv_string(item['risk assessment status']) risk_assessment.risk_assessment_url = csv_string(item['risk assessment url']) risk_assessment.risk_assessment_title = csv_string(item['risk assessment title']) risk_assessment.risk_assessment_date = csv_date(item['risk assessment date']) risk_assessment.additional_information_url = csv_string(item['additional information url']) risk_assessment.public_visit = csv_boolean(item['public visit']) risk_assessment.union_presence = csv_boolean(item['union presence']) risk_assessment.sic_codes = csv_list(item['sic codes']) risk_assessment.company_number = csv_int(item['company number']) if risk_assessment.is_valid(): risk_assessments.append(risk_assessment) else: print("Invalid risk assessment %s" % ", ".join(risk_assessment._validation_errors)) # mailchimp mailchimp_api_key = os.environ['MAILCHIMP_API_KEY'] mailchimp_username = os.environ['MAILCHIMP_USERNAME'] mailchimp_audience_id = os.environ['MAILCHIMP_AUDIENCE_ID'] mailchimp_client = MailChimp(mc_api=mailchimp_api_key, mc_user=mailchimp_username) mailchimp_list = mailchimp_client.lists.get(mailchimp_audience_id) # Stats stats = {'risk_assessments': 0, 'volunteers': 0, 'risk_assessments_public': 0, 'risk_assessments_private': 0, 'risk_assessments_onrequest': 0, 'risk_assessments_unknown': 0} stats['risk_assessments'] = len(risk_assessments) stats['volunteers'] = mailchimp_list['stats']['member_count'] # output directory create_directory(config['outputDir']) create_directory("%s/assets" % config['outputDir']) # Risk assessments create_directory("%s/risk-assessments" % config['outputDir']) for risk_assessment in risk_assessments: if risk_assessment.risk_assessment_status == 'public': stats['risk_assessments_public'] += 1 elif risk_assessment.risk_assessment_status == 'private': stats['risk_assessments_private'] += 1 elif risk_assessment.risk_assessment_status == 'on request': stats['risk_assessments_onrequest'] += 1 elif risk_assessment.risk_assessment_status == None: stats['risk_assessments_unknown'] += 1 #html render("%s/risk-assessments/%s.html" % (config['outputDir'], risk_assessment.get_slug()), "risk-assessment.html", risk_assessment=risk_assessment) # #json # create_file("%s/risk-assessments/%s.json" % (config['outputDir'], risk_assessment.get_slug()), risk_assessment.to_json()) # Risk assessment index render("%s/%s" % (config['outputDir'], "risk-assessments/index.html"), "risk-assessments.html", risk_assessments=risk_assessments, stats=stats) # index page render("%s/index.html" % config['outputDir'], "index.html", stats=stats) # volunteers create_directory("%s/monitors" % config['outputDir']) render("%s/monitors/index.html" % config['outputDir'], "volunteer.html") render("%s/monitors/check-email.html" % config['outputDir'], "volunteer-check-email.html") render("%s/monitors/confirmed.html" % config['outputDir'], "volunteer-confirmed.html") # Report render("%s/report.html" % config['outputDir'], "report.html") # static pages for path in glob.glob('%s/static/*.md' % config['dataDir']): page = frontmatter.load(path) #replaces any config variables in markdown parsed_content = Template(page.content) page.content = parsed_content.render(config=get_config()) file_name = os.path.basename(path).replace('.md', '.html') render("%s/%s" % (config['outputDir'], file_name), "static.html", page=page) # reports and guides create_directory("%s/reports" % config['outputDir']) for path in glob.glob('%s/reports/*.md' % config['dataDir']): page = frontmatter.load(path) parsed_content = Template(page.content) page.content = parsed_content.render(config=get_config()) file_name = os.path.basename(path).replace('.md', '.html') template_name = "analysis.html" if file_name == "index.html": template_name = "static.html" render("%s/reports/%s" % (config['outputDir'], file_name), template_name, page=page) #assets path = "assets/CNAME" file_name = os.path.basename(path) copyfile(path, "%s/CNAME" % config['outputDir']) for path in glob.glob('%s/*.js' % config['assetsDir']): file_name = os.path.basename(path) copyfile(path, "%s/assets/%s" % (config['outputDir'], file_name)) for path in glob.glob('%s/*.png' % config['assetsDir']): file_name = os.path.basename(path) copyfile(path, "%s/assets/%s" % (config['outputDir'], file_name)) for path in glob.glob('%s/*.jpg' % config['assetsDir']): file_name = os.path.basename(path) copyfile(path, "%s/assets/%s" % (config['outputDir'], file_name)) for path in glob.glob('%s/*.svg' % config['assetsDir']): file_name = os.path.basename(path) copyfile(path, "%s/assets/%s" % (config['outputDir'], file_name)) path = "node_modules/govuk-frontend/govuk/all.js" file_name = os.path.basename(path) copyfile(path, "%s/assets/govuk.js" % config['outputDir']) sass.compile(dirname=('assets', 'docs/assets'), output_style='compressed')
def get(self, pagename=None): if not users.is_current_user_admin(): self.redirect("/") values={} values.update( {'logout_url':users.create_logout_url("/")} ) if pagename in ['','/', None]: # --------------------------------------------------------------- # Overview Page # --------------------------------------------------------------- slide_stat = SlideStats.all().fetch(1)[0] values.update( {'total_size':slide_stat.total_size} ) # storage stats total_micro = int((float(values['total_size']) / 1024**2)*100) values.update( {'total_micro': range(total_micro)} ) values.update( {'remaining_micro': range(100-total_micro)} ) # misc over stats values.update( {'total_snaps': slide_stat.total_snaps} ) try: date_start = Screengrabs.all().order('date').fetch(1)[0].date except: pass try: date_stop = Screengrabs.all().order('-date').fetch(1)[0].date except: pass try: date_diff = date_stop-date_start values.update( {'total_days':date_diff.days}) values.update( {'total_hours':date_diff.seconds/3600}) values.update( {'total_minutes':(date_diff.seconds/60)%60}) values.update( {'date_start':date_start.strftime('%F %H:%M:%S')} ) values.update( {'date_stop':date_stop.strftime('%F %H:%M:%S')} ) except: values.update( {'date_stop':'a time unknown'} ) values.update( {'date_start':'a time never known'} ) helpers.render(self, "overview.html",values) return if pagename in ['/machines','/machines/']: # --------------------------------------------------------------- # Machines Page # --------------------------------------------------------------- total_machines = Machines.all().count() values.update ( {'total_machines': total_machines} ) if total_machines>0: values.update({'machines_start':Machines.all().order('created').fetch(1)[0].created}) values.update( {'machines':Machines.all().fetch(1000)} ) else: values.update({'machines_start':'a time unknown'}) helpers.render(self, "machines.html",values) return if pagename in ['/machines/delete/','/machines/delete']: # # Machines_delete # _key=self.request.get('key') machine = db.get(_key) machine.delete() self.redirect("/home/machines") if pagename in ['/machines/disable/','/machines/disable']: # # Machines_disable # _key=self.request.get('key') machine = db.get(_key) machine.enabled=False db.put(machine) self.redirect("/home/machines") if pagename in ['/machines/enable/','/machines/enable']: # # Machines_enable # _key=self.request.get('key') machine = db.get(_key) machine.enabled=True machine.put() self.redirect("/home/machines") if pagename in ['/history','/history/']: # --------------------------------------------------------------- # History Page # --------------------------------------------------------------- slide_count=100 try: slide_count = int(self.request.get('count')) except ValueError: self.redirect ('/home/history?count=100') if slide_count<1: self.redirect ('/home/history?count=100') screengrabs = Screengrabs.all().order('-date').fetch(slide_count) if len(screengrabs) < slide_count: slide_count = len(screengrabs) values.update ( {'screengrabs':screengrabs} ) values.update ( {'slide_count':slide_count} ) helpers.render(self, "history.html",values) return
def handler_404(request, response, exception): response.write(render("templates/404.html")) response.set_status(404)
user.handle = handle if email: cherrypy.log('email:%s' % email) user.email_address = email if password1: if password1 != password2: raise e.ValidationException('Passwords do not match') user.password = password1 # save our changes m.session.commit() # take a look redirect('/user/%s' % user.id) except e.ValidationException, ex: add_flash('error','%s' % ex) return render('/users/edit.html',user=user) @cherrypy.expose def delete(self,**kwargs): return 'delete' @cherrypy.expose def default(self,id): user = m.User.get(id) if not user: add_flash('error',"Can't find user") return render('/users/single.html',user=user)
def get(self): values = { 'header': 'Test page'} self.response.out.write(render('test.html', values))
def index(self): users = m.User.query.order_by(m.User.handle).all() return render('/users/index.html',users=users)
def get(self, values): values["students"] = Student.query().fetch() update_m(values, get_m(self.request)) self.response.write(render("templates/alunos.html", values))
def get(self): values = { "active": "turmas", } self.response.write(render("templates/alunos.html", values))
def help(request): return render(request, {}, 'news/help.html')
def get(self, values): self.response.write(render("templates/home.html", values))
def handler_500(request, response, exception): logging.exception(exception) values = {"stack_trace": traceback.format_exc().strip()} response.write(render("templates/500.html", values)) response.set_status(500)
def get(self, id): values = { "active": "professores", } self.response.write(render("templates/aluno.html", values))
def default(self, *args, **kwargs): return render("/node.html")