Exemple #1
0
 def get(self):
     html = template.render('templates/header.html', {'titel': 'Mögliche Sichtung melden'})
     html = html + template.render('templates/form_anfang.html', {})
     html = html + str(SichtungForm())
     html = html + template.render('templates/form_ende.html', {'untertitel': 'Sichtung senden'})
     html = html + template.render('templates/footer.html', {'links': ''})
     self.response.out.write(html)
Exemple #2
0
    def get(self):
        thingquery = getString(20)
        query = Thing.gql('WHERE thingid = :1 LIMIT 1', thingquery)
	if query.count() == 1:
            qrcode_link = '<img src="http://chart.apis.google.com/chart?cht=qr&chs=150x150&chld=M&chl='+ THING_URL_BASE + 'thing/' + thingquery + '" />'
            thing_link = THING_URL_BASE + 'thing/' + thingquery
          
            self.response.out.write(
                template.render(tpl('generate.html'), {
                    'qrimg': qrcode_link,
                    'thing_link': thing_link,
    	            'loginurl':	users.create_login_url('/'),
    	            'logouturl': users.create_logout_url('/')
                     })
            )
          
        else:
          thing = Thing()
          thing.thingid = thingquery
          thing.put()
          
          qrcode_link = '<img src="http://chart.apis.google.com/chart?cht=qr&chs=150x150&chld=M&chl='+ THING_URL_BASE + 'thing/' + thingquery + '" />'
          thing_link = THING_URL_BASE + 'thing/' + thingquery

          
          self.response.out.write(
              template.render(tpl('generate.html'), {
                  'qrimg': qrcode_link,
                  'thing_link': thing_link,
    	            'loginurl':	users.create_login_url('/'),
    	            'logouturl': users.create_logout_url('/')
                   })
          )
Exemple #3
0
    def post(self):

        email = self.request.get("email")
        password = self.request.get("password")
        if email.find("@") == -1:
            email_message = "Incorrect Email Format, Please input something like [email protected]"
            html = template.render("templates/signin.html", {"email_message": email_message})
            self.response.write(html)
        else:
            user_exist = UserDB.all().filter("email =", email).filter("verified =", True).fetch(1)
            if user_exist == []:
                web_message = (
                    "Your email is either not registered or not verified. Please register or verify your email first."
                )
                html = template.render("templates/signin.html", {"web_message": web_message})
                self.response.write(html)
            else:
                if user_exist[0].password == password:
                    self.session["user_key"] = str(user_exist[0].key())
                    logging.info(str(self.session["user_key"]))
                    self.redirect("/")
                else:
                    password_message = "Your password is incorrect."
                    html = template.render("templates/signin.html", {"password_message": password_message})
                    self.response.write(html)
Exemple #4
0
    def get(self):

        user = users.get_current_user()

        # if the user is logged
        if user:

            # search for date
            if not self.request.get("date"):
                # note_date=datetime.date.today()
                # note_date= datetime.datetime.utcnow().date()
                self.redirect("/today")
                return

            # we get the date parameter
            try:
                note_date = datetime.datetime.strptime(self.request.get("date"), "%Y-%m-%d").date()
            except ValueError:
                self.redirect("/today")
                return

            # search for note
            note = Note.all().filter("author =", user).filter("date =", note_date).get()

            # if we don't find the note create new note
            if not note:
                note = Note()
                note.author = user
                note.date = note_date

            # logout link
            url = users.create_logout_url(self.request.uri)
            url_linktext = "Logout"

            # values for templates
            template_values = {
                "user": user,
                "note": note,
                "datestring": note.date.strftime("%B %d, %Y"),
                "url": url,
                "url_linktext": url_linktext,
            }

            # write the page
            path = os.path.join(__view__, "note.html")
            self.response.out.write(template.render(path, template_values))

        # if isn't logged
        else:

            # url login
            url = users.create_login_url(self.request.uri)
            url_linktext = "Login"

            # values for templates
            template_values = {"url": url, "url_linktext": url_linktext}

            # write the page
            path = os.path.join(__view__, "home.html")
            self.response.out.write(template.render(path, template_values))
	def get(self,page):
		# Remove trailing slashes, if they exist
		if self.request.uri[-1] == '/':
			self.redirect(self.request.uri[:-1])
			return
		
		if not page:
			page = ''
		else:
			page = page[1:] # Remove the initial slash

		
		docPath = 'templates/docs/' + page + '.html'
		
		if not os.path.exists(os.path.join(os.path.dirname(__file__), docPath)):
			# Perhaps the “page” was a directory?
			# Check for an index.html
			docPath = docPath[:-5] + '/index.html'
			if not os.path.exists(os.path.join(os.path.dirname(__file__), docPath)):
				# Still not found?  404.
				docPath = 'templates/404.html'
		
		path = os.path.join(os.path.dirname(__file__), 'templates/head.html')
		self.response.out.write(template.render(path, {'title':'Documentation'}))
		path = os.path.join(os.path.dirname(__file__), docPath)
		self.response.out.write(template.render(path, {'baseURL':self.request.host_url}))
		path = os.path.join(os.path.dirname(__file__), 'templates/foot.html')
		self.response.out.write(template.render(path, {}))
Exemple #6
0
 def get(self):
   self.response.headers["Content-Type"] = "text/json"
   album_key = ndb.Key(urlsafe=self.request.get("album_key"))
   songlist_html = memcache.get("songlist_html_%s" % album_key.urlsafe())
   if songlist_html:
     self.response.out.write(json.dumps({
           'songListHtml': songlist_html,
           'generated': 'memcache',
           }))
     return
   album = Album.get(album_key, one_key=True)
   self.response.headers["Content-Type"] = "text/json"
   if not album:
     self.response.out.write(json.dumps({
           'err': ("An error occurred and the specified album could "
                   "not be found.  Please try again.")
           }))
     return
   songlist_html = template.render(get_path("ajax_songlist.html"), {
       'songList': Song.get(album.tracklist),
       })
   memcache.set("songlist_html_%s"%album_key.urlsafe(), songlist_html)
   self.response.out.write(json.dumps({
         'songListHtml': template.render(get_path("ajax_songlist.html"), {
             'songList': Song.get(album.tracklist),
             }),
         'generated': 'generated',
         }))
Exemple #7
0
    def get(self,var):
        path = os.path.join(os.path.dirname(__file__), "oauth.html")
        try:
            event = Locations.get(var)
        except BadKeyError:
            errorMessage="Problem with location: could not find !!"
            template_values = {
            'errorMess': errorMessage,
            'url' : '/geo',
            'errorNo': 500,
            }
            path = os.path.join(os.path.dirname(__file__), 'exception.html')
            self.response.out.write(template.render(path, template_values))
            return

        user_dict = []
        the_user = self.current_user
        if the_user:
            user_checked_in_event = EventCheck.gql('where check_in = :1 and id = :2 and event = :3',date.today(),the_user.id,var)
            if user_checked_in_event.count() > 0:
                logging.info('user checked in')
            else:
                store_event = EventCheck(key_name=the_user.id, id=the_user.id,event=var)
                store_event.put()
            all_users = EventCheck.gql('where check_in = :1 and event = :2',date.today(),var)

            for user in all_users:
                user_dict.append(User.get_by_key_name(user.id))
            args = dict(current_user=the_user,event_id=var,event_name=event,users=user_dict)
            self.response.out.write(template.render(path, args))
        else:
            self.redirect("/geo")
	def get(self):
		template_params={}
		user = None
		if self.request.cookies.get('our_token'):    #the cookie that should contain the access token!
			user = User.checkToken(self.request.cookies.get('our_token'))
		if not user:
			html = template.render("web/templates/index.html", {})
			self.response.write(html)
			return
		#newlinks
		linkslist=Link.getAllLinksPerUser(user)	
		newurls = []
		template_params = {}
		if linkslist:
			for link in linkslist:
				url = link.url_link
				des = link.description
				fromlink=link.from_link
				if fromlink is not None:
					urlandlink =[url,des,fromlink]
					newurls.append(urlandlink)
			template_params['newurls'] = newurls
		#newlinks
		template_params['useremail'] = user.email
		contactlist= Contact.getAllContactsPerUser(user)
		contacts= []
		if contactlist:
			for contact in contactlist:
				contact_email= contact.contact_user_email
				contact_nickname= contact.nick_name
				email_and_nickname= [contact_email, contact_nickname]
				contacts.append(email_and_nickname)
			template_params['contacts']=contacts
		html = template.render("web/templates/contactspage.html", template_params)
		self.response.write(html)
Exemple #9
0
def render_template(handler, page_name, params={}, trigger_template=None):
    from google.appengine.ext.webapp import template
    
    #Add params used in the templates
    params["root"] = handler.request.host_url
    params["js"] = params["css"] = ""
    params["page_name"] = page_name
    params["is_dev"] = IS_DEV

    #Add another navbar dropdown on the development server
    #for easy access to the SDK console and dataviewer
    if IS_DEV:
        params["admin_root"] = secrets.DEV_ADMIN_ROOT

    if trigger_template is not None:
        trigger_path = HTML_FILE.format("triggers/%s" % trigger_template)
        trigger_render = template.render(trigger_path, params)

        params["trigger_fields"] = trigger_render

    #Render the page
    page_path = HTML_FILE.format(page_name)
    page_render = template.render(page_path, params)

    #Render the template
    template_path = HTML_FILE.format("template")
    template_render = template.render(template_path, params)
    
    #Combine the renderings and output
    handler.response.out.write(template_render.replace("[PAGE]", page_render))

    return
Exemple #10
0
 def get(self):
     site = GetSite()
     template_values = {}
     template_values['site'] = site
     username = self.request.get('username')
     if username:
         one = GetMemberByUsername(username)
         if one is not False:
             if one.avatar_mini_url:
                 if (one.avatar_mini_url[0:1] == '/'):
                     one.avatar_mini_url = 'http://' + site.domain + one.avatar_mini_url
                     one.avatar_normal_url = 'http://' +  site.domain + one.avatar_normal_url
                     one.avatar_large_url = 'http://' + site.domain + one.avatar_large_url
             template_values['member'] = one
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'members_show.json')
             output = template.render(path, template_values)
             self.write(output)
         else:
             template_values['message'] = "Member not found"
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
             output = template.render(path, template_values)
             self.response.set_status(400, 'Bad Request')
             self.write(output)
     else:
         template_values['message'] = "Required parameter username is missing"
         path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
         output = template.render(path, template_values)
         self.response.set_status(400, 'Bad Request')
         self.write(output)
Exemple #11
0
 def get(self):
     site = GetSite()
     template_values = {}
     template_values['site'] = site
     method_determined = False
     parameter_id = self.request.get('id')
     if parameter_id:
         method_determined = True
     if method_determined is not True:
         parameter_name = self.request.get('name')
         if parameter_name:
             method_determined = True
     if method_determined is True:
         if parameter_id:
             node = GetKindByNum('Node', int(parameter_id))
         else:
             node = GetKindByName('Node', str(parameter_name))
         if node is not False:
             template_values['node'] = node
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'nodes_show.json')
             output = template.render(path, template_values)
             self.write(output)
         else:
             template_values['message'] = 'Node not found'
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
             output = template.render(path, template_values)
             self.write(output)
     else:
         template_values['message'] = "Required parameter id or name is missing"
         path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
         output = template.render(path, template_values)
         self.write(output)
Exemple #12
0
 def get(self):
     if users.get_current_user():
         if users.is_current_user_admin():
             if self.request.arguments():
                 if self.request.get(u'mode')=='delete':
                     c=get_content(self.request.get(u'target'))
                     if c:
                         c.delete()
                     self.redirect(LIST_PATH)
                     return
                 elif self.request.get(u'mode')=='modify':
                     c=get_content(self.request.get(u'target'))
                     if c:
                         if c.entitytype=='file':
                             self.redirect(UPLOAD_PATH+'?target='+self.request.get('target'))
                             return
                         elif c.entitytype=='alias':
                             self.redirect(ALIAS_PATH+'?target='+self.request.get('target'))
                             return
                     errormsg=self.request.get(u'errormsg')
                     path=os.path.join(os.path.dirname(__file__), 'template_admin.html')
                     self.response.out.write(template.render(path, {'CURRENT_PATH':EDIT_PATH,'LIST_PATH':LIST_PATH,'EDIT_PATH':EDIT_PATH,'UPLOAD_PATH':UPLOAD_PATH,'ALIAS_PATH':ALIAS_PATH,'SETTING_PATH':SETTING_PATH,'modify':c,'errormsg':errormsg}))
                     return
             path=os.path.join(os.path.dirname(__file__), 'template_admin.html')
             q=Content.all()
             q.order('__key__')
             self.response.out.write(template.render(path, {'CURRENT_PATH':EDIT_PATH,'LIST_PATH':LIST_PATH,'EDIT_PATH':EDIT_PATH,'UPLOAD_PATH':UPLOAD_PATH,'ALIAS_PATH':ALIAS_PATH,'SETTING_PATH':SETTING_PATH}))
             return
     self.redirect(users.create_login_url(self.request.uri))
Exemple #13
0
    def get(self):
        site = GetSite()
        template_values = {}
        template_values['site'] = site
        method_determined = False
        topic_id = self.request.get('topic_id')
        page = self.request.get('page', 1)
        page_size = TOPIC_PAGE_SIZE

        if topic_id:
            page_start = (int(page) - 1) * page_size
            replies = db.GqlQuery("SELECT * FROM Reply WHERE topic_num = :1 ORDER BY created ASC LIMIT " + str(page_start) + "," + str(page_size), int(topic_id))

            if replies:
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'replies_show.json')
                template_values['replies'] = replies
                output = template.render(path, template_values)
                self.write(output)
            else:
                template_values['message'] = "Failed to get replies"
                path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
                output = template.render(path, template_values)
                self.response.set_status(400, 'Bad Request')
                self.write(output)
        else:
            template_values['message'] = "Required parameter topic_id is missing"
            path = os.path.join(os.path.dirname(__file__), 'tpl', 'api', 'error.json')
            output = template.render(path, template_values)
            self.response.set_status(400, 'Bad Request')
            self.write(output)
Exemple #14
0
 def post(self):
   user = users.get_current_user()
   if not user:
       self.redirect(users.create_login_url('/key'))
       return
   account = Membership.all().filter('username ='******'templates/error.html', locals()))
         return
   rfid_tag = self.request.get('rfid_tag').strip()
   description = self.request.get('description').strip()
   if rfid_tag.isdigit():
     if Membership.all().filter('rfid_tag =', rfid_tag).get():
       error = "<p>That RFID tag is in use by someone else.</p>"
       self.response.out.write(template.render('templates/error.html', locals()))
       return
     if not description:
       error = "<p>Please enter a reason why you are associating a replacement RFID key.  Please hit BACK and try again.</p>"
       self.response.out.write(template.render('templates/error.html', locals()))
       return
     account.rfid_tag = rfid_tag
     account.put()
     bc = BadgeChange(rfid_tag = rfid_tag, username=account.username, description=description)
     bc.put()
     self.response.out.write(template.render('templates/key_ok.html', locals()))
     return
   else:
     error = "<p>That RFID ID seemed invalid. Hit back and try again.</p>"
     self.response.out.write(template.render('templates/error.html', locals()))
     return
Exemple #15
0
	def post(self):
		context = {}
		if users.get_current_user():
			context['user'] = str(users.get_current_user()) + ': '
			context['login_url'] = users.create_logout_url(self.request.uri)
			context['login_text'] = "Log Out"
		else:
			context['user'] = "******"
			context['login_url'] = users.create_login_url(self.request.uri)
			context['login_text'] = "Log In"
		user = str(users.get_current_user())
		bname = cgi.escape(self.request.get('title'))
		context['bname'] = bname
		context['blink'] = urllib.quote(bname)
		context['owner'] = urllib.quote(user)
		query = Blog.query(Blog.owner == user, Blog.blogname == bname)
		if query.count(limit=1):
			self.response.write(template.render(
			os.path.join(os.path.dirname(__file__), 
			'dupe_blog.html'),
			context))
		else:
			b = Blog()
			b.owner = user
			b.blogname = bname
			b.put()
			self.response.write(template.render(
				os.path.join(os.path.dirname(__file__), 
				'create_blog_success.html'),
				context))
Exemple #16
0
 def post(self):
   import urllib
   import urlparse
   
   gifuri = self.request.get("gifuri") #access the POST parameter
   uri_parts = urlparse.urlparse(gifuri)
   
   query_string = uri_parts.query
   query_parts = query_string.split('&')
   
   output = {}
   for query_part in query_parts:
       key, val = query_part.split('=')
       val = urllib.unquote(val)
       
       if key == 'utmcc':
           cc_parts = val.split(';')
           val = ('<br/>').join(cc_parts)
       
       output[key] = val
       
   self.templateParams['gifuri'] = gifuri
   self.templateParams['output'] = output
   
   print template.render('templates/default.html', self.templateParams)
Exemple #17
0
 def get(self):
   user = users.get_current_user()
   if not user:
       self.redirect(users.create_login_url('/key'))
       return
   else:
       account = Membership.all().filter('username ='******'templates/error.html', locals()))
         return
       if account.status != "active":
         url = "https://spreedly.com/"+SPREEDLY_ACCOUNT+"/subscriber_accounts/"+account.spreedly_token
         error = "<p>Your Spreedly account status does not appear to me marked as active.  This might be a mistake, in which case we apologize. <p>To investigate your account, you may go here: <a href=\""+url+"\">"+url+"</a> <p>If you believe this message is in error, please contact <a href=\"mailto:[email protected]?Subject=Spreedly+account+not+linked+to+hackerdojo+account\">[email protected]</a></p>";
         self.response.out.write(template.render('templates/error.html', locals()))
         return
       delta = datetime.utcnow() - account.created
       if delta.days < DAYS_FOR_KEY:
         error = "<p>You have been a member for "+str(delta.days)+" days.  After "+str(DAYS_FOR_KEY)+" days you qualify for a key.  Check back in "+str(DAYS_FOR_KEY-delta.days)+" days!</p><p>If you believe this message is in error, please contact <a href=\"mailto:[email protected]?Subject=Membership+create+date+not+correct\">[email protected]</a>.</p>";
         self.response.out.write(template.render('templates/error.html', locals()))
         return    
       bc = BadgeChange.all().filter('username ='******'templates/key.html', locals()))
	def get(self, page):
		path = os.path.join(os.path.dirname(__file__), 'templates/head.html')
		self.response.out.write(template.render(path, {'stylesheet':'landing'}))
		path = os.path.join(os.path.dirname(__file__), 'templates/landing.html')
		self.response.out.write(template.render(path, {}))
		path = os.path.join(os.path.dirname(__file__), 'templates/foot.html')
		self.response.out.write(template.render(path, {}))
	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'templates/head.html')
		self.response.out.write(template.render(path, {'title':'About'}))
		path = os.path.join(os.path.dirname(__file__), 'templates/about.html')
		self.response.out.write(template.render(path, {}))
		path = os.path.join(os.path.dirname(__file__), 'templates/foot.html')
		self.response.out.write(template.render(path, {}))
Exemple #20
0
 def get(self):
     user = users.get_current_user()
     if user:
         clients_query = Clients.all()
         clientlist = clients_query.fetch(100)
         url = users.create_logout_url(self.request.uri)
         url_linktext = 'Logout'
         template_values = {
             'clients': clientlist,
             'username': user.nickname(),
             'useremail': user.email(),
             'url': url,
             'url_linktext': url_linktext
         }
         path = os.path.join(os.path.dirname(__file__),
                             'views/clients.html')
         self.response.out.write(template.render(path, template_values))
     else:
         url = users.create_login_url(self.request.uri)
         url_linktext = 'Login'
         template_values = {
             'url': url,
             'url_linktext': url_linktext,
         }
         path = os.path.join(os.path.dirname(__file__), 
                             'views/index.html')
         self.response.out.write(template.render(path, template_values))
Exemple #21
0
    def get(self):
        user = users.get_current_user()
        if user:
            all_clients_query = Clients.all()
            all_clients = all_clients_query.fetch(100)
            services_query = Services.all()
            # TODO: make the filter below work, and 
            # add UI to disable services
            #services_query.filter('active =', 'True')
            services = services_query.fetch(100)
            k = db.Key(self.request.get('clientkey'))
            clients_query = Clients.all()
            clients_query.filter('__key__ = ', k)
            client = clients_query.fetch(1)
            
            time_query = Time.all()
            time_query.filter('client =', k)
            time_query.order('-project')
            times = time_query.fetch(100)

            projects_query = Projects.all()
            projects_query.filter('client =', k)
            projects = projects_query.fetch(100)
            

            statuses = ["draft", "invoiced", "paid", "sent", "deleted"]
            if users.get_current_user():
                url = users.create_logout_url(self.request.uri)
                url_linktext = 'Logout'
            else:
                url = users.create_login_url(self.request.uri)
                url_linktext = 'Login'
            template_values = {
                'statuses': statuses,
                'title': settings.APP['title'],
                'author': settings.APP['author'],
                'times': times,
                'allclients': all_clients,
                'client': client,
                'foo': projects,
                'businessname': client[0].business,
                'services': services,
                'projectkeys': projects,
                'clientname': self.request.get('clientname'),
                'clientkey': self.request.get('clientkey'),
                'url': url,
                'url_linktext': url_linktext,
                }
            path = os.path.join(os.path.dirname(__file__), 
                                'views/projects.html')
            self.response.out.write(template.render(path, template_values))
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'
            template_values = {
                'url': url,
                'url_linktext': url_linktext,
            }
            path = os.path.join(os.path.dirname(__file__), 'views/index.html')
            self.response.out.write(template.render(path, template_values))
Exemple #22
0
	def get(self, value):
		logging.info('value -> ' + str(value))
		if value:
			# get parameters.
			import urllib
			value = urllib.unquote_plus(value)
			eid = self.request.get('eid', '')
			key = str(self.request.get('key', ''))
			# logging parameters.
			logging.info('value unquoted -> ' + str(value))
			logging.info('eid -> ' + str(eid))
			logging.info('key -> ' + str(key))
			# create entities.
			from trial.models import ModelInput2
			e_kname = ModelInput2.get_by_key_name(eid)
			# create resoponse.
			self.response.headers['Content-type'] = 'text/html'
			template_path = os.path.join(APP_ROOT, 'templates/ModelInput2-2.html')
			self.response.out.write(template.render(template_path, {
				'value': value, 'key': key, 'eid': eid,
				'e_kname': e_kname,
			}))
		else:
			from trial.models import ModelInput2
			entities = db.GqlQuery("select * from ModelInput2").fetch(10)
			template_path = os.path.join(APP_ROOT, 'templates/modelinput2.html')
			self.response.headers['Content-type'] = 'text/html'
			self.response.out.write(template.render(template_path, {'entities':entities}))
 def get(self):
     html = template.render('templates/header.html', {'title': 'Provide your birth details'})
     html = html + template.render('templates/form_start.html', {})
     html = html + str(BirthDetailsForm(auto_id=False))     
     html = html + template.render('templates/form_end.html', {'sub_title': 'Submit Details'})
     html = html + template.render('templates/footer.html', {'links': ''})
     self.response.out.write(html)
 def get(self):
   user = self.getAuthentificatedUser()
   forum = self.getForumInstance()
   try:
     id = int(self.request.get('id'))
     #thread = Thread.get(db.Key.from_path('Thread', id))
     thread = self.getThread(id)
   except:
     #thread = Thread.all().order('position').fetch(1)
     thread = self.getThreads().order('position').fetch(1)
     thread = thread[0]
     id = thread.key().id()
   topics = self.getTopics(id).order('-pub_date')
   template_values = {
     'admin': self.checkIfAuthentificatedUserIsAdmin(),
     'url' : users.CreateLogoutURL(self.request.uri),
     'user' : user.nickname(),
     'forum' : forum,
     'thread' : thread,
     'topics' :topics,
   }
   try:
     if self.checkMode(str(self.request.get('mode'))):
       #self.response.headers.add_header('Set-Cookie', 'mode=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' % 'admin')
       path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewThreadAdminMode.htm'))
       self.response.out.write(template.render(path, template_values))
       return
   except:
     pass
   path = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'viewThread.htm'))
   self.response.out.write(template.render(path, template_values))
Exemple #25
0
  def post(self):
    if self.request.get('formId')=='userLog':
        uname=self.request.get('username')
        pwd=self.request.get('pwd')
        if db.check_login(uname, pwd)==1:
            self.session['uid'] = uname
            self.redirect('/userpage.html')
        else:
            self.response.out.write('''<script>alert("Username/Password combo is incorrect.  If you are not a member please register.");</script>''')
            self.response.out.write(template.render('templates/draft2.html', None))
    if self.request.get('formId')=='userReg':
        fname=self.request.get('first')
        lname=self.request.get('last')
        pword=self.request.get('pass')
        uni=self.request.get('uni')
        email=self.request.get('studId')
        regname=email.split('@')[0]

        if db.does_user_exist(regname):
            self.response.out.write('''<script>alert("Username is already taken.  PLease choose another.");</script>''')
            self.response.out.write(template.render('templates/draft2.html', None))
        else:
            db.register_user(pword, email, fname, lname, uni)
            self.session['uid'] = regname
            self.redirect('/userpage.html')
Exemple #26
0
 def render_and_send(self, template_name, additional_template_values):
   DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Dev')
   template_values = {
     'full_width':620,
     'link_style':'style="text-decoration:none;color:#000099;"',
   }
   template_values.update(additional_template_values)
   template_values['host_url'] = ('http://localhost:8080' if DEBUG else 'http://www.admonymous.com')
   path_html = os.path.join(base_dir.base_dir(), 'templates', '_email', template_name+'.html')
   path_txt = os.path.join(base_dir.base_dir(), 'templates', '_email', template_name+'.txt')
   self.html = template.render(path_html, template_values, debug=False)
   self.body = template.render(path_txt, template_values, debug=False)
   if DEBUG:
     logging.info("""
     
     HTML Version:
     
     %s
     
     TXT Version:
     
     %s
     
     """ % (self.html, self.body))
   else:
     self.send()
    def get(self):
        oauth_token = self.request.get("oauth_token", None)
        oauth_verifier = self.request.get("oauth_verifier", None)
        if oauth_token is None:
            # Invalid request!
            self.response.out.write(template.render('templates/error.html', {
                    'message': 'Missing required parameters!'
            }))
            return

        # Lookup the request token
        request_token = OAuthToken.gql("WHERE token_key=:key", key=oauth_token).get()
        if request_token is None:
            # We do not seem to have this request token, show an error.
            self.response.out.write(template.render('templates/error.html', {'message': 'Invalid token!'}))
            return

        # Rebuild the auth handler
        auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_request_token(request_token.token_key, request_token.token_secret)

        # Fetch the access token
        try:
            auth.get_access_token(oauth_verifier)
            username = auth.get_username();
        except tweepy.TweepError, e:
            # Failed to get access token
            self.response.out.write( template.render('templates/error.html', {'message': e}))
            return
Exemple #28
0
    def get(self):
        # List Cities
        citylist = {}
        cities = City.all()
        for city in cities:
            citylist[city.Name] = [abs(hash(city.Name)),[]]
            for station in city.station_set:
                data = {'Name':station.Name}
                query = Query(AQIData)
                query.filter('Station =', station.Code)
                query.order('-Date')
                query.run()
                aqi = query.get()
                data['AQI'] = aqi.AQI
                data['Level'] = aqi.AQILevel
                data['Assess'] = aqi.AQIAssess
                data['Date'] = aqi.Date
                data['Majority'] = aqi.Majority
                citylist[city.Name][1].append(data)
        # logging.info(str(citylist))
        #----generate parameter list----------------------------------------------------------------------
        citytemplate_values = {
            'citylist' : citylist,
            }
        citypath = os.path.join(os.path.dirname(__file__), './/template//citylist.html')
        #----end------------------------------------------------------------------------------------------
        content = template.render(citypath,citytemplate_values)

        template_values = {
            'content': content
            }
        path = os.path.join(os.path.dirname(__file__), './/template//frame.html')
        #----end------------------------------------------------------------------------------------------
        self.response.out.write(template.render(path,template_values))
Exemple #29
0
    def get(self):

        user = users.get_current_user()

        # if the user is logged
        if user:

            # search for notes
            notes = Note.all().filter("author =", user)

            # logout link
            url = users.create_logout_url(self.request.uri)
            url_linktext = "Logout"

            # values for templates
            template_values = {"user": user, "notes": notes, "url": url, "url_linktext": url_linktext}

            # write the page
            path = os.path.join(__view__, "notebook.html")
            self.response.out.write(template.render(path, template_values))

        # if isn't logged
        else:

            # url login
            url = users.create_login_url(self.request.uri)
            url_linktext = "Login"

            # values for templates
            template_values = {"url": url, "url_linktext": url_linktext}

            # write the page
            path = os.path.join(__view__, "home.html")
            self.response.out.write(template.render(path, template_values))
  def testFullBeaconShowerShowsAllAvailable(self):
    """Test that if there are a few results, FullBeaconShower shows them."""
    self.mox.StubOutWithMock(record_results.FullResultRecord, 'all')

    # Object under test:
    results_show_handler = record_results.FullBeaconShower()
    self.SetupRequestHandlerObjs(results_show_handler)

    # Ask for all FullResultRecord datastore records:
    ps_result_query = self.mox.CreateMockAnything()
    record_results.FullResultRecord.all().AndReturn(ps_result_query)

    ps_result_all = self.mox.CreateMockAnything()
    ps_result_query.order('-time_received').AndReturn(ps_result_all)

    # The fetch returns two objects.
    ps_result_all.fetch(mox.IsA(int)).AndReturn([{}, {}])

    # Check that the template is told that there are no results.
    self.mox.StubOutWithMock(template, 'render')
    template.render(mox.IsA(str),  # The path to the template.
                    # Test that the template dictionary has {numresults = 0}
                    mox.And(mox.IsA(dict),
                            mox.In('num_results'),
                            mox.Func(lambda d: d['num_results'] == 2)
                            ),
                    ).AndReturn('Render This String')

    results_show_handler.response.out.write('Render This String')

    self.mox.ReplayAll()
    results_show_handler.get()
    self.mox.VerifyAll()
Exemple #31
0
 def get(self):
     del self.session['successfulLogin']
     del self.session['successfulEmail']
     self.response.out.write(template.render('plogin_ca.html', {}))
Exemple #32
0
 def post(self, topic_num):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     template_values['member'] = member
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     topic_num_str = str(topic_num)
     if len(topic_num_str) > 8:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
         output = template.render(path, template_values)
         self.response.out.write(output)
         return
     if (member):
         topic = False
         q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                         int(topic_num))
         if (q.count() == 1):
             topic = q[0]
             try:
                 topic.hits = topic.hits + 1
                 topic.put()
             except:
                 topic.hits = topic.hits - 1
         template_values['topic'] = topic
         errors = 0
         # Verification: content
         reply_content_error = 0
         reply_content_error_messages = [
             '', u'请输入回复内容', u'回复内容长度不能超过 2000 个字符'
         ]
         reply_content = self.request.get('content').strip()
         if (len(reply_content) == 0):
             errors = errors + 1
             reply_content_error = 1
         else:
             if (len(reply_content) > 2000):
                 errors = errors + 1
                 reply_content_error = 2
         template_values['reply_content'] = reply_content
         template_values['reply_content_error'] = reply_content_error
         template_values[
             'reply_content_error_message'] = reply_content_error_messages[
                 reply_content_error]
         template_values['errors'] = errors
         if (topic and (errors == 0)):
             reply = Reply(parent=topic)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'reply.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'reply.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'reply.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'reply.total'
                 counter2.value = 1
             node = False
             section = False
             if topic:
                 q3 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q3[0]
                 q4 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                                  node.section_num)
                 section = q4[0]
             reply.num = counter.value
             reply.content = reply_content
             reply.topic = topic
             reply.topic_num = topic.num
             reply.member = member
             reply.member_num = member.num
             reply.created_by = member.username
             topic.replies = topic.replies + 1
             topic.node_name = node.name
             topic.node_title = node.title
             topic.last_reply_by = member.username
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone', ua)):
                 reply.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod', ua)):
                 reply.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad', ua)):
                 reply.source = 'iPad'
             if (re.findall('Android', ua)):
                 reply.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 reply.source = 'PS3'
             reply.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.set('Topic_' + str(topic.num), topic, 86400)
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_compressed')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_desc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_asc_rendered_mobile')
             memcache.delete('topic_' + str(topic.num) +
                             '_replies_filtered_rendered_mobile')
             memcache.delete('member::' + str(member.num) +
                             '::participated')
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 link = 'http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num) + '#r' + str(
                         reply.num)
                 link_length = len(link)
                 reply_content_length = len(reply.content)
                 available = 140 - link_length - 1
                 if available > reply_content_length:
                     status = reply.content + ' ' + link
                 else:
                     status = reply.content[0:(available -
                                               4)] + '... ' + link
                 self.response.out.write('Status: ' + status)
                 logging.error('Status: ' + status)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Reply #" +
                                   str(reply.num))
             self.redirect('/t/' + str(topic.num) + '#reply' +
                           str(topic.replies))
         else:
             node = False
             section = False
             if topic:
                 q2 = db.GqlQuery("SELECT * FROM Node WHERE num = :1",
                                  topic.node_num)
                 node = q2[0]
                 q3 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                                  node.section_num)
                 section = q3[0]
             template_values['node'] = node
             template_values['section'] = section
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
Exemple #33
0
 def get(self, topic_num):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['rnd'] = random.randrange(1, 100)
     reply_reversed = self.request.get('r')
     if reply_reversed == '1':
         reply_reversed = True
     else:
         reply_reversed = False
     filter_mode = self.request.get('f')
     if filter_mode == '1':
         filter_mode = True
     else:
         filter_mode = False
     template_values['reply_reversed'] = reply_reversed
     template_values['filter_mode'] = filter_mode
     template_values['system_version'] = SYSTEM_VERSION
     errors = 0
     template_values['errors'] = errors
     member = CheckAuth(self)
     template_values['member'] = member
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     if member is not False:
         try:
             blocked = pickle.loads(member.blocked.encode('utf-8'))
         except:
             blocked = []
         if (len(blocked) > 0):
             template_values['blocked'] = ','.join(map(str, blocked))
         if member.num == 1:
             template_values['is_admin'] = 1
         else:
             template_values['is_admin'] = 0
     topic_num_str = str(topic_num)
     if len(topic_num_str) > 8:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
         output = template.render(path, template_values)
         self.response.out.write(output)
         return
     topic = False
     topic = memcache.get('Topic_' + str(topic_num))
     if topic is None:
         q = db.GqlQuery("SELECT * FROM Topic WHERE num = :1",
                         int(topic_num))
         if (q.count() == 1):
             topic = q[0]
             memcache.set('Topic_' + str(topic_num), topic, 86400)
     if topic:
         taskqueue.add(url='/hit/topic/' + str(topic.key()))
         template_values['page_title'] = site.title + u' › ' + topic.title
         template_values[
             'canonical'] = 'http://' + site.domain + '/t/' + str(topic.num)
         if topic.content_rendered is None:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_content.html')
             output = template.render(path, {'topic': topic})
             topic = db.get(topic.key())
             topic.content_rendered = output.decode('utf-8')
             memcache.delete('Topic_' + str(topic.num))
             topic.put()
     else:
         template_values['page_title'] = site.title + u' › 主题未找到'
     template_values['topic'] = topic
     if member:
         if member.num == 1:
             template_values['can_edit'] = True
         else:
             template_values['can_edit'] = False
     if (topic):
         node = False
         section = False
         node = GetKindByNum('Node', topic.node_num)
         if (node):
             section = GetKindByNum('Section', node.section_num)
         template_values['node'] = node
         template_values['section'] = section
         replies = False
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_replies_mobile.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_replies.html')
         if filter_mode:
             if browser['ios']:
                 r_tag = 'topic_' + str(
                     topic.num) + '_replies_filtered_rendered'
             else:
                 r_tag = 'topic_' + str(
                     topic.num) + '_replies_filtered_rendered_mobile'
             r = memcache.get(r_tag)
             if r is None:
                 replies = memcache.get('topic_' + str(topic.num) +
                                        '_replies_filtered_compressed')
                 if replies is None:
                     q5 = db.GqlQuery(
                         "SELECT * FROM Reply WHERE topic_num = :1 AND member_num = :2 ORDER BY created ASC",
                         topic.num, topic.member.num)
                     replies = q5
                     memcache.set(
                         'topic_' +
                         str(topic.num) + '_replies_filtered_compressed',
                         GetPacked(replies), 7200)
                 else:
                     replies = GetUnpacked(replies)
                 template_values['replies'] = replies
                 r = template.render(path, template_values)
                 memcache.set(r_tag, r, 86400)
         else:
             if reply_reversed:
                 if browser['ios']:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_desc_rendered'
                 else:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_desc_rendered_mobile'
                 r = memcache.get(r_tag)
                 if r is None:
                     replies = memcache.get('topic_' + str(topic.num) +
                                            '_replies_desc_compressed')
                     if replies is None:
                         q4 = db.GqlQuery(
                             "SELECT * FROM Reply WHERE topic_num = :1 ORDER BY created DESC",
                             topic.num)
                         replies = q4
                         memcache.set(
                             'topic_' +
                             str(topic.num) + '_replies_desc_compressed',
                             GetPacked(q4), 86400)
                     else:
                         replies = GetUnpacked(replies)
                     template_values['replies'] = replies
                     r = template.render(path, template_values)
                     memcache.set(r_tag, r, 86400)
             else:
                 if browser['ios']:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_asc_rendered'
                 else:
                     r_tag = 'topic_' + str(
                         topic.num) + '_replies_asc_rendered_mobile'
                 r = memcache.get(r_tag)
                 if r is None:
                     replies = memcache.get('topic_' + str(topic.num) +
                                            '_replies_asc_compressed')
                     if replies is None:
                         q4 = db.GqlQuery(
                             "SELECT * FROM Reply WHERE topic_num = :1 ORDER BY created ASC",
                             topic.num)
                         replies = q4
                         memcache.set(
                             'topic_' +
                             str(topic.num) + '_replies_asc_compressed',
                             GetPacked(q4), 86400)
                     else:
                         replies = GetUnpacked(replies)
                     template_values['replies'] = replies
                     r = template.render(path, template_values)
                     memcache.set(r_tag, r, 86400)
         template_values['r'] = r
         if topic and member:
             if member.hasFavorited(topic):
                 template_values['favorited'] = True
             else:
                 template_values['favorited'] = False
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic.html')
     else:
         if browser['ios']:
             path = os.path.join(os.path.dirname(__file__), 'tpl', 'mobile',
                                 'topic_not_found.html')
         else:
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'desktop', 'topic_not_found.html')
     output = template.render(path, template_values)
     self.response.out.write(output)
Exemple #34
0
 def post(self, node_name):
     site = GetSite()
     browser = detect(self.request)
     template_values = {}
     template_values['site'] = site
     template_values['system_version'] = SYSTEM_VERSION
     member = CheckAuth(self)
     l10n = GetMessages(self, member, site)
     template_values['l10n'] = l10n
     template_values[
         'page_title'] = site.title + u' › ' + l10n.create_new_topic.decode(
             'utf-8')
     if (member):
         template_values['member'] = member
         q = db.GqlQuery("SELECT * FROM Node WHERE name = :1", node_name)
         node = False
         if (q.count() == 1):
             node = q[0]
         template_values['node'] = node
         section = False
         if node:
             q2 = db.GqlQuery("SELECT * FROM Section WHERE num = :1",
                              node.section_num)
             if (q2.count() == 1):
                 section = q2[0]
         template_values['section'] = section
         errors = 0
         # Verification: title
         topic_title_error = 0
         topic_title_error_messages = [
             '', u'请输入主题标题', u'主题标题长度不能超过 120 个字符'
         ]
         topic_title = self.request.get('title').strip()
         if (len(topic_title) == 0):
             errors = errors + 1
             topic_title_error = 1
         else:
             if (len(topic_title) > 120):
                 errors = errors + 1
                 topic_title_error = 2
         template_values['topic_title'] = topic_title
         template_values['topic_title_error'] = topic_title_error
         template_values[
             'topic_title_error_message'] = topic_title_error_messages[
                 topic_title_error]
         # Verification: content
         topic_content_error = 0
         topic_content_error_messages = [
             '', u'请输入主题内容', u'主题内容长度不能超过 2000 个字符'
         ]
         topic_content = self.request.get('content').strip()
         if (len(topic_content) == 0):
             errors = errors + 1
             topic_content_error = 1
         else:
             if (len(topic_content) > 2000):
                 errors = errors + 1
                 topic_content_error = 2
         template_values['topic_content'] = topic_content
         template_values['topic_content_error'] = topic_content_error
         template_values[
             'topic_content_error_message'] = topic_content_error_messages[
                 topic_content_error]
         # Verification: type
         if site.use_topic_types:
             types = site.topic_types.split("\n")
             if len(types) > 0:
                 topic_type = self.request.get('type').strip()
                 try:
                     topic_type = int(topic_type)
                     if topic_type < 0:
                         topic_type = 0
                     if topic_type > len(types):
                         topic_type = 0
                     if topic_type > 0:
                         detail = types[topic_type - 1].split(':')
                         topic_type_label = detail[0]
                         topic_type_color = detail[1]
                 except:
                     topic_type = 0
             else:
                 topic_type = 0
             options = '<option value="0">&nbsp;&nbsp;&nbsp;&nbsp;</option>'
             i = 0
             for a_type in types:
                 i = i + 1
                 detail = a_type.split(':')
                 if topic_type == i:
                     options = options + '<option value="' + str(
                         i
                     ) + '" selected="selected">' + detail[0] + '</option>'
                 else:
                     options = options + '<option value="' + str(
                         i) + '">' + detail[0] + '</option>'
             tt = '<div class="sep5"></div><table cellpadding="5" cellspacing="0" border="0" width="100%"><tr><td width="60" align="right">Topic Type</td><td width="auto" align="left"><select name="type">' + options + '</select></td></tr></table>'
             template_values['tt'] = tt
         else:
             template_values['tt'] = ''
         template_values['errors'] = errors
         if (errors == 0):
             topic = Topic(parent=node)
             q = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                             'topic.max')
             if (q.count() == 1):
                 counter = q[0]
                 counter.value = counter.value + 1
             else:
                 counter = Counter()
                 counter.name = 'topic.max'
                 counter.value = 1
             q2 = db.GqlQuery('SELECT * FROM Counter WHERE name = :1',
                              'topic.total')
             if (q2.count() == 1):
                 counter2 = q2[0]
                 counter2.value = counter2.value + 1
             else:
                 counter2 = Counter()
                 counter2.name = 'topic.total'
                 counter2.value = 1
             topic.num = counter.value
             topic.title = topic_title
             topic.content = topic_content
             path = os.path.join(os.path.dirname(__file__), 'tpl',
                                 'portion', 'topic_content.html')
             output = template.render(path, {'topic': topic})
             topic.content_rendered = output.decode('utf-8')
             topic.node = node
             topic.node_num = node.num
             topic.node_name = node.name
             topic.node_title = node.title
             topic.created_by = member.username
             topic.member = member
             topic.member_num = member.num
             topic.last_touched = datetime.datetime.now()
             ua = self.request.headers['User-Agent']
             if (re.findall('Mozilla\/5.0 \(iPhone;', ua)):
                 topic.source = 'iPhone'
             if (re.findall('Mozilla\/5.0 \(iPod;', ua)):
                 topic.source = 'iPod'
             if (re.findall('Mozilla\/5.0 \(iPad;', ua)):
                 topic.source = 'iPad'
             if (re.findall('Android', ua)):
                 topic.source = 'Android'
             if (re.findall('Mozilla\/5.0 \(PLAYSTATION 3;', ua)):
                 topic.source = 'PS3'
             if site.use_topic_types:
                 if topic_type > 0:
                     topic.type = topic_type_label
                     topic.type_color = topic_type_color
             node.topics = node.topics + 1
             node.put()
             topic.put()
             counter.put()
             counter2.put()
             memcache.delete('feed_index')
             memcache.delete('Node_' + str(topic.node_num))
             memcache.delete('Node::' + str(node.name))
             memcache.delete('home_rendered')
             memcache.delete('home_rendered_mobile')
             taskqueue.add(url='/index/topic/' + str(topic.num))
             # Twitter Sync
             if member.twitter_oauth == 1 and member.twitter_sync == 1:
                 access_token = OAuthToken.from_string(
                     member.twitter_oauth_string)
                 twitter = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,
                                    access_token)
                 status = topic.title + ' #' + topic.node.name + ' http://' + self.request.headers[
                     'Host'] + '/t/' + str(topic.num)
                 try:
                     twitter.PostUpdate(status.encode('utf-8'))
                 except:
                     logging.error("Failed to sync to Twitter for Topic #" +
                                   str(topic.num))
             self.redirect('/t/' + str(topic.num) + '#reply0')
         else:
             if browser['ios']:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'mobile', 'new_topic.html')
             else:
                 path = os.path.join(os.path.dirname(__file__), 'tpl',
                                     'desktop', 'new_topic.html')
             output = template.render(path, template_values)
             self.response.out.write(output)
     else:
         self.redirect('/signin')
Exemple #35
0
 def get(self):
     upload_url = blobstore.create_upload_url('/aboutUs')
     self.response.out.write(
         template.render("templates/aboutUs.html", {}).format(upload_url))
    def get(self):
        self._require_login()
        self._require_registration()

        user = self.user_bundle.account.key
        now = datetime.datetime.now()
        team_favorites_future = Favorite.query(
            Favorite.model_type == ModelType.TEAM,
            ancestor=user).fetch_async()

        live_events = EventHelper.getEventsWithinADay()
        favorite_team_keys = map(lambda f: ndb.Key(Team, f.model_key),
                                 team_favorites_future.get_result())
        favorite_teams_future = ndb.get_multi_async(favorite_team_keys)

        live_eventteams_futures = []
        for event in live_events:
            live_eventteams_futures.append(
                EventTeamsQuery(event.key_name).fetch_async())

        favorite_teams = [
            team_future.get_result() for team_future in favorite_teams_future
        ]

        favorite_teams_events_futures = []
        for team in favorite_teams:
            favorite_teams_events_futures.append(
                TeamYearEventsQuery(team.key_name, now.year).fetch_async())

        live_events_with_teams = EventTeamStatusHelper.buildEventTeamStatus(
            live_events, live_eventteams_futures, favorite_teams)

        future_events_by_event = {}
        for team, events_future in zip(favorite_teams,
                                       favorite_teams_events_futures):
            events = events_future.get_result()
            if not events:
                continue
            EventHelper.sort_events(events)
            next_event = next(
                (e
                 for e in events if e.start_date > now and not e.within_a_day),
                None)
            if next_event:
                if next_event.key_name not in future_events_by_event:
                    future_events_by_event[next_event.key_name] = (next_event,
                                                                   [])
                future_events_by_event[next_event.key_name][1].append(team)

        future_events_with_teams = []
        for event_key, data in future_events_by_event.iteritems():
            future_events_with_teams.append(
                (data[0], TeamHelper.sortTeams(data[1])))
        future_events_with_teams.sort(key=lambda x: x[0].name)
        future_events_with_teams.sort(
            key=lambda x: EventHelper.distantFutureIfNoStartDate(x[0]))
        future_events_with_teams.sort(
            key=lambda x: EventHelper.distantFutureIfNoEndDate(x[0]))

        self.template_values.update({
            'live_events_with_teams':
            live_events_with_teams,
            'future_events_with_teams':
            future_events_with_teams,
        })

        path = os.path.join(os.path.dirname(__file__),
                            '../templates/mytba_live.html')
        self.response.out.write(template.render(path, self.template_values))
Exemple #37
0
 def get(self):
     self.response.out.write(template.render('register_ca.html', {}))
Exemple #38
0
 def get(self):
     template_values = {}
     path = os.path.join(os.path.dirname(__file__), 'index.html')
     self.response.out.write(template.render(path, template_values))
Exemple #39
0
 def get(self):
     rpi = get_rpi()
     # render view
     path = os.path.join(os.path.dirname(__file__), 'views', 'index.html')
     self.response.out.write(template.render(path, {'rpi': rpi}))
Exemple #40
0
 def get(self):
     self.response.out.write(template.render('mapa_eu.html', {}))
 def _render(self, *args, **kw):
     self.template_values['enabled'] = NotificationType.enabled_notifications
     self.template_values['types'] = NotificationType.types
     path = os.path.join(os.path.dirname(__file__), "../templates/webhookdocs.html")
     return template.render(path, self.template_values)
Exemple #42
0
 def get(self):
     path = os.path.join(os.path.dirname(__file__), 'views', 'rpi.json')
     self.response.headers['Content-Type'] = 'application/json'
     self.response.out.write(template.render(path, {'rpi': get_rpi()}))
Exemple #43
0
 def get(self):
     self.response.out.write(
         template.render("templates/updateworkitems.html", None))
Exemple #44
0
 def render_template(self, filename, context={}):
     path = os.path.join(os.path.dirname(__file__), filename)
     self.response.out.write(template.render(path, context))
 def get(self):
     self._require_admin()
     path = os.path.join(os.path.dirname(__file__), '../../templates/admin/tasks.html')
     self.response.out.write(template.render(path, self.template_values))
 def _render(self, *args, **kw):
     path = os.path.join(os.path.dirname(__file__), "../templates/matchinput.html")
     return template.render(path, self.template_values)
    def get(self):
        mobile = self.request.get('mobile')
        if mobile != "true":
            mobile = "false"
        # self.response.out.write('posted!')
        # Den Usernamen erfahren
        username = users.get_current_user()
        if not username:
            self.redirect('/')
        # Eventuell vorhande Fehlermeldung holen
        message = self.request.get('message')
        # Namen des Buckets holen, dessen Inhalt angezeigt wird
        bucketname = self.request.get('bucket')

        # Nachsehen, ob eine Region/Zone ausgewählte wurde
        aktivezone = db.GqlQuery(
            "SELECT * FROM KoalaCloudDatenbankAktiveZone WHERE user = :username_db",
            username_db=username)
        results = aktivezone.fetch(100)

        if not results:
            self.redirect('/')
        else:
            # Nachsehen, ob eine Sprache ausgewählte wurde und wenn ja, welche Sprache
            sprache = aktuelle_sprache(username)
            navigations_bar = navigations_bar_funktion(sprache, mobile)

            results = aktivezone.fetch(100)

            url = users.create_logout_url(self.request.uri).replace(
                '&', '&amp;').replace('&amp;amp;', '&amp;')
            #url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'

            conn_region, regionname = login(username)
            zone_amazon = amazon_region(username)
            zugangstyp = zugangstyp_erhalten(username)

            zonen_liste = zonen_liste_funktion(username, sprache, mobile)

            if sprache != "de":
                sprache = "en"

            input_error_message = error_messages.get(message, {}).get(sprache)

            # Wenn keine Fehlermeldung gefunden wird, ist das Ergebnis "None"
            if input_error_message == None:
                input_error_message = ""

            # Wenn die Nachricht grün formatiert werden soll...
            if message in ("111", "118", "120"):
                # wird sie hier, in der Hilfsfunktion grün formatiert
                input_error_message = format_error_message_green(
                    input_error_message)
            # Ansonsten wird die Nachricht rot formatiert
            elif message in ("112", "119", "121"):
                input_error_message = format_error_message_red(
                    input_error_message)
            else:
                input_error_message = ""

            AWSAccessKeyId = aws_access_key_erhalten(username, regionname)
            AWSSecretAccessKeyId = aws_secret_access_key_erhalten(
                username, regionname)

            # Mit S3 verbinden
            conn_s3 = logins3(username)

            try:
                # Liste der Buckets
                bucket_instance = conn_s3.get_bucket(bucketname)
            except:
                # Wenn es nicht klappt...
                if sprache == "de":
                    bucket_keys_tabelle = '<font color="red">Es ist zu einem Fehler gekommen</font>'
                else:
                    bucket_keys_tabelle = '<font color="red">An error occured</font>'
                laenge_liste_keys = 0
                # Wenn es geklappt hat...
            else:
                try:
                    # Liste der Keys
                    liste_keys = bucket_instance.get_all_keys()
                except:
                    # Wenn es nicht klappt...
                    if sprache == "de":
                        bucket_keys_tabelle = '<font color="red">Es ist zu einem Fehler gekommen</font>'
                    else:
                        bucket_keys_tabelle = '<font color="red">An error occured</font>'
                    laenge_liste_keys = 0
                else:
                    # Wenn es geklappt hat...
                    # Anzahl der Keys in der Liste
                    laenge_liste_keys = len(liste_keys)

                # Wenn wir in einer Eucalyputs-Infrastruktur sind, dann muss dieser
                # dämliche None-Eintrag weg
                if regionname != "Amazon":
                    liste_keys2 = []
                    for i in range(laenge_liste_keys):
                        if str(liste_keys[i].name) != 'None':
                            liste_keys2.append(liste_keys[i])
                    laenge_liste_keys2 = len(liste_keys2)
                    laenge_liste_keys = laenge_liste_keys2
                    liste_keys = liste_keys2

                if laenge_liste_keys == 0:
                    if sprache == "de":
                        bucket_keys_tabelle = 'Der Bucket <B>' + bucketname + ' </B>ist leer.'
                    else:
                        bucket_keys_tabelle = 'The bucket <B>' + bucketname + ' </B>is empty.'
                else:

                    if mobile == "true":
                        # mobile version...

                        bucket_keys_tabelle = ''
                        bucket_keys_tabelle += '<table border="0" cellspacing="0" cellpadding="5" width="300">'

                        counter = 0
                        for i in range(laenge_liste_keys):

                            if counter > 0:
                                bucket_keys_tabelle += '<tr><td colspan="3">&nbsp;</td></tr>'
                            counter += 1

                            bucket_keys_tabelle += '<tr>'
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '<td>&nbsp;</td>'
                            else:
                                bucket_keys_tabelle += '<td>'
                                bucket_keys_tabelle += '<a href="/bucketkeyentfernen?bucket='
                                bucket_keys_tabelle += str(bucketname)
                                bucket_keys_tabelle += '&amp;typ=pur'
                                bucket_keys_tabelle += '&amp;key='
                                bucket_keys_tabelle += str(liste_keys[i].name)
                                bucket_keys_tabelle += "&amp;mobile="
                                bucket_keys_tabelle += str(mobile)
                                if sprache == "de":
                                    bucket_keys_tabelle += '" title="Key l&ouml;schen"><img src="bilder/delete.png" width="16" height="16" border="0" alt="Key l&ouml;schen"></a>'
                                else:
                                    bucket_keys_tabelle += '" title="erase key"><img src="bilder/delete.png" width="16" height="16" border="0" alt="erase key"></a>'
                                bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '<td colspan="2" align="left">'
                            bucket_keys_tabelle += '<a href="'
                            if regionname == "Amazon":
                                bucket_keys_tabelle += liste_keys[
                                    i].generate_url(600,
                                                    method='GET',
                                                    headers=None,
                                                    query_auth=True,
                                                    force_http=True).replace(
                                                        '&', '&amp;').replace(
                                                            '&amp;amp;',
                                                            '&amp;')
                            else:
                                port = port_erhalten(username, regionname)
                                bucket_keys_tabelle += liste_keys[
                                    i].generate_url(
                                        600,
                                        method='GET',
                                        headers=None,
                                        query_auth=True,
                                        force_http=True).replace(
                                            '&', '&amp;').replace(
                                                '&amp;amp;', '&amp;').replace(
                                                    '/services/Walrus/',
                                                    ':' + str(port) +
                                                    '/services/Walrus/')
                            bucket_keys_tabelle += '">'
                            bucket_keys_tabelle += str(liste_keys[i].name)
                            bucket_keys_tabelle += '</a>'
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'
                            if sprache == "de":
                                bucket_keys_tabelle += '<td align="right" colspan="2"><b>Gr&ouml;&szlig;e:</b></td>'
                            else:
                                bucket_keys_tabelle += '<td align="right" colspan="2"><b>Size:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '&nbsp;'
                            else:
                                bucket_keys_tabelle += str(liste_keys[i].size)
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'

                            if sprache == "de":
                                bucket_keys_tabelle += '<td align="right" colspan="2"><b>Datum:</b></td>'
                            else:
                                bucket_keys_tabelle += '<td align="right" colspan="2"><b>Date:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            # Den ISO8601 Zeitstring umwandeln, damit es besser aussieht.
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '&nbsp;'
                            else:
                                datum_der_letzten_aenderung = parse(
                                    liste_keys[i].last_modified)
                                bucket_keys_tabelle += str(
                                    datum_der_letzten_aenderung.strftime(
                                        "%Y-%m-%d  %H:%M:%S"))
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'

                            bucket_keys_tabelle += '<td align="right" colspan="2"><b>ACL:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            bucket_keys_tabelle += '<a href="/acl_einsehen?bucket='
                            bucket_keys_tabelle += str(bucketname)
                            bucket_keys_tabelle += '&amp;typ=pur'
                            bucket_keys_tabelle += '&amp;key='
                            bucket_keys_tabelle += str(liste_keys[i].name)
                            bucket_keys_tabelle += "&amp;mobile="
                            bucket_keys_tabelle += str(mobile)
                            if sprache == "de":
                                bucket_keys_tabelle += '" title="einsehen/&auml;ndern">einsehen/&auml;ndern</a>'
                            else:
                                bucket_keys_tabelle += '" title="view/edit">view/edit</a>'
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'

                            # In S3 and Google Storage, each MD5 checksum is enclosed by double quotes.
                            # Eliminate them with .replace('"','')
                            bucket_keys_tabelle += '<td align="right" colspan="2"><b>MD5:</b></td>'
                            bucket_keys_tabelle += '<td align="left">' + str(
                                liste_keys[i].etag.replace('"', '')) + '</td>'
                            bucket_keys_tabelle += '</tr>'
                        bucket_keys_tabelle += '</table>'

                    else:
                        # not the mobile version

                        bucket_keys_tabelle = ''
                        bucket_keys_tabelle += '<table border="0" cellspacing="0" cellpadding="5">'

                        counter = 0
                        for i in range(laenge_liste_keys):

                            if counter > 0:
                                bucket_keys_tabelle += '<tr><td colspan="4">&nbsp;</td></tr>'
                            counter += 1

                            bucket_keys_tabelle += '<tr>'
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '<td>&nbsp;</td>'
                            else:
                                bucket_keys_tabelle += '<td align="left" bgcolor="#D4D4D4">'
                                bucket_keys_tabelle += '<a href="/bucketkeyentfernen?bucket='
                                bucket_keys_tabelle += str(bucketname)
                                bucket_keys_tabelle += '&amp;typ=pur'
                                bucket_keys_tabelle += '&amp;key='
                                bucket_keys_tabelle += str(liste_keys[i].name)
                                bucket_keys_tabelle += "&amp;mobile="
                                bucket_keys_tabelle += str(mobile)
                                if sprache == "de":
                                    bucket_keys_tabelle += '" title="Key l&ouml;schen"><img src="bilder/delete.png" width="16" height="16" border="0" alt="Key l&ouml;schen"></a>'
                                else:
                                    bucket_keys_tabelle += '" title="erase key"><img src="bilder/delete.png" width="16" height="16" border="0" alt="erase key"></a>'
                                bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '<td colspan="3" align="left" bgcolor="#D4D4D4">&nbsp;</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'

                            bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>ID:</b></td>'
                            bucket_keys_tabelle += '<td colspan="3" align="left">'
                            bucket_keys_tabelle += '<a href="'
                            if regionname == "Amazon":
                                bucket_keys_tabelle += liste_keys[
                                    i].generate_url(600,
                                                    method='GET',
                                                    headers=None,
                                                    query_auth=True,
                                                    force_http=True).replace(
                                                        '&', '&amp;').replace(
                                                            '&amp;amp;',
                                                            '&amp;')
                            else:
                                port = port_erhalten(username, regionname)
                                bucket_keys_tabelle += liste_keys[
                                    i].generate_url(
                                        600,
                                        method='GET',
                                        headers=None,
                                        query_auth=True,
                                        force_http=True).replace(
                                            '&', '&amp;').replace(
                                                '&amp;amp;', '&amp;').replace(
                                                    '/services/Walrus/',
                                                    ':' + str(port) +
                                                    '/services/Walrus/')
                            bucket_keys_tabelle += '">'
                            bucket_keys_tabelle += str(liste_keys[i].name)
                            bucket_keys_tabelle += '</a>'
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'
                            if sprache == "de":
                                bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>Gr&ouml;&szlig;e:</b></td>'
                            else:
                                bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>Size:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '&nbsp;'
                            else:
                                bucket_keys_tabelle += str(liste_keys[i].size)
                            bucket_keys_tabelle += '</td>'

                            if sprache == "de":
                                bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>Datum:</b></td>'
                            else:
                                bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>Date:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            # Den ISO8601 Zeitstring umwandeln, damit es besser aussieht.
                            if liste_keys[
                                    i].name == None and regionname != "Amazon":
                                bucket_keys_tabelle += '&nbsp;'
                            else:
                                datum_der_letzten_aenderung = parse(
                                    liste_keys[i].last_modified)
                                bucket_keys_tabelle += str(
                                    datum_der_letzten_aenderung.strftime(
                                        "%Y-%m-%d  %H:%M:%S"))
                            bucket_keys_tabelle += '</td>'

                            bucket_keys_tabelle += '</tr>'
                            bucket_keys_tabelle += '<tr>'

                            bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>ACL:</b></td>'
                            bucket_keys_tabelle += '<td align="left">'
                            bucket_keys_tabelle += '<a href="/acl_einsehen?bucket='
                            bucket_keys_tabelle += str(bucketname)
                            bucket_keys_tabelle += '&amp;typ=pur'
                            bucket_keys_tabelle += '&amp;key='
                            bucket_keys_tabelle += str(liste_keys[i].name)
                            bucket_keys_tabelle += "&amp;mobile="
                            bucket_keys_tabelle += str(mobile)
                            if sprache == "de":
                                bucket_keys_tabelle += '" title="einsehen/&auml;ndern">einsehen/&auml;ndern</a>'
                            else:
                                bucket_keys_tabelle += '" title="view/edit">view/edit</a>'
                            bucket_keys_tabelle += '</td>'

                            # In S3 and Google Storage, each MD5 checksum is enclosed by double quotes.
                            # Eliminate them with .replace('"','')
                            bucket_keys_tabelle += '<td align="right" bgcolor="#D4D4D4"><b>MD5:</b></td>'
                            bucket_keys_tabelle += '<td align="left">' + str(
                                liste_keys[i].etag.replace('"', '')) + '</td>'
                            bucket_keys_tabelle += '</tr>'
                        bucket_keys_tabelle += '</table>'

            # Wenn man sich NICHT unter Amazon befindet, funktioniert der Download von Keys nicht.
#          if regionname != "Amazon":
#            if sprache == "de":
#              eucalyptus_warnung = '<B>Achtung!</B> Unter Eucalyptus 1.6 und 1.6.1 funktioniert der Download von Keys nicht. Dabei handelt es sich um einen Fehler von Eucalyptus. Es kommt zu dieser Fehlermeldung: <B>Failure: 500 Internal Server Error</B>'
#            else:
#              eucalyptus_warnung = '<B>Attention!</B> With Eucalyptus 1.6 and 1.6.1 the download of Keys is broken. This is a bug of Eucalyptus. The result is this error message: <B>Failure: 500 Internal Server Error</B>'
#          else:
#            eucalyptus_warnung = ''

#Dokumentation zum Upload von Keys
#http://docs.amazonwebservices.com/AmazonS3/latest/index.html?HTTPPOSTForms.html
#http://doc.s3.amazonaws.com/proposals/post.html
#http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1434
#http://s3.amazonaws.com/doc/s3-example-code/post/post_sample.html

# Hier wird das Policy-Dokument erzeugt
            policy_document = ''
            policy_document = policy_document + '{'
            policy_document = policy_document + '"expiration": "2100-01-01T00:00:00Z",'
            policy_document = policy_document + '"conditions": ['
            policy_document = policy_document + '{"bucket": "' + bucketname + '"}, '
            policy_document = policy_document + '["starts-with", "$acl", ""],'
            if mobile == "true":
                policy_document = policy_document + '{"success_action_redirect": "http://koalacloud.appspot.com/bucket_inhalt_pure?mobile=true"},'
            else:
                policy_document = policy_document + '{"success_action_redirect": "http://koalacloud.appspot.com/bucket_inhalt_pure?mobile=false"},'
            policy_document = policy_document + '["starts-with", "$key", ""],'
            policy_document = policy_document + '["starts-with", "$Content-Type", ""]'
            policy_document = policy_document + ']'
            policy_document = policy_document + '}'

            policy = base64.b64encode(policy_document)

            signature = base64.b64encode(
                hmac.new(AWSSecretAccessKeyId, policy, sha).digest())

            keys_upload_formular = ''
            if zugangstyp == "Eucalyptus":
                endpointurl = endpointurl_erhalten(username, regionname)
                port = port_erhalten(username, regionname)
                keys_upload_formular += '<form action="http://' + str(
                    endpointurl
                ) + ':' + str(
                    port
                ) + '/services/Walrus/' + bucketname + '" method="post" enctype="multipart/form-data">\n'
            elif zugangstyp == "GoogleStorage":
                keys_upload_formular += '<form action="http://commondatastorage.googleapis.com/' + bucketname + '" method="post" enctype="multipart/form-data">\n'
            elif zugangstyp == "HostEuropeCloudStorage":
                keys_upload_formular += '<form action="http://' + bucketname + '.cs.hosteurope.de'
                keys_upload_formular += '" method="post" enctype="multipart/form-data">\n'
            elif zugangstyp == "DunkelCloudStorage":
                keys_upload_formular += '<form action="http://' + bucketname + '.dcs.dunkel.de'
                keys_upload_formular += '" method="post" enctype="multipart/form-data">\n'
            else:
                keys_upload_formular += '<form action="http://s3.amazonaws.com/' + bucketname + '" method="post" enctype="multipart/form-data">\n'

            if mobile == "true":
                # mobile version...
                keys_upload_formular += '<table border="0" cellspacing="0" cellpadding="5">\n'
                keys_upload_formular += '<tr>\n'
                keys_upload_formular += '<td>\n'
                keys_upload_formular += '<input type="hidden" name="key" value="${filename}">\n'
                keys_upload_formular += '<select name="acl" size="1">\n'
                keys_upload_formular += '<option selected="selected">public-read</option>\n'
                keys_upload_formular += '<option>private</option>\n'
                keys_upload_formular += '<option>public-read-write</option>\n'
                keys_upload_formular += '<option>authenticated-read</option>\n'
                keys_upload_formular += '</select>\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>'
                keys_upload_formular += '<select name="Content-Type" size="1">\n'
                keys_upload_formular += '<option selected="selected">application/octet-stream</option>\n'
                keys_upload_formular += '<option>application/pdf</option>\n'
                keys_upload_formular += '<option>application/zip</option>\n'
                keys_upload_formular += '<option>audio/mp4</option>\n'
                keys_upload_formular += '<option>audio/mpeg</option>\n'
                keys_upload_formular += '<option>audio/ogg</option>\n'
                keys_upload_formular += '<option>audio/vorbis</option>\n'
                keys_upload_formular += '<option>image/gif</option>\n'
                keys_upload_formular += '<option>image/jpeg</option>\n'
                keys_upload_formular += '<option>image/png</option>\n'
                keys_upload_formular += '<option>image/tiff</option>\n'
                keys_upload_formular += '<option>text/html</option>\n'
                keys_upload_formular += '<option>text/plain</option>\n'
                keys_upload_formular += '<option>video/mp4</option>\n'
                keys_upload_formular += '<option>video/mpeg</option>\n'
                keys_upload_formular += '<option>video/ogg</option>\n'
                keys_upload_formular += '</select>\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>\n'
                keys_upload_formular += '<input type="hidden" name="success_action_redirect" value="http://koalacloud.appspot.com/bucket_inhalt_pure?mobile=true">\n'
                keys_upload_formular += '<input type="hidden" name="AWSAccessKeyId" value="' + AWSAccessKeyId + '">\n'
                keys_upload_formular += '<input type="hidden" name="policy" value="' + policy + '">\n'
                keys_upload_formular += '<input type="hidden" name="signature" value="' + signature + '">\n'
                keys_upload_formular += '<input type="file" name="file" size="20">\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>'
                if sprache == "de":
                    keys_upload_formular += '<input type="submit" value="Objekt in den Bucket hochladen">\n'
                else:
                    keys_upload_formular += '<input type="submit" value="upload objekt into bucket">\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '</table>'
                keys_upload_formular += '</form>'
            else:
                # Not the mobile version
                keys_upload_formular += '<table border="0" cellspacing="0" cellpadding="5">'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>'
                keys_upload_formular += '<input type="hidden" name="key" value="${filename}">\n'
                keys_upload_formular += '<select name="acl" size="1">\n'
                keys_upload_formular += '<option selected="selected">public-read</option>\n'
                keys_upload_formular += '<option>private</option>\n'
                keys_upload_formular += '<option>public-read-write</option>\n'
                keys_upload_formular += '<option>authenticated-read</option>\n'
                keys_upload_formular += '</select>\n'
                keys_upload_formular += '<select name="Content-Type" size="1">\n'
                keys_upload_formular += '<option selected="selected">application/octet-stream</option>\n'
                keys_upload_formular += '<option>application/pdf</option>\n'
                keys_upload_formular += '<option>application/zip</option>\n'
                keys_upload_formular += '<option>audio/mp4</option>\n'
                keys_upload_formular += '<option>audio/mpeg</option>\n'
                keys_upload_formular += '<option>audio/ogg</option>\n'
                keys_upload_formular += '<option>audio/vorbis</option>\n'
                keys_upload_formular += '<option>image/gif</option>\n'
                keys_upload_formular += '<option>image/jpeg</option>\n'
                keys_upload_formular += '<option>image/png</option>\n'
                keys_upload_formular += '<option>image/tiff</option>\n'
                keys_upload_formular += '<option>text/html</option>\n'
                keys_upload_formular += '<option>text/plain</option>\n'
                keys_upload_formular += '<option>video/mp4</option>\n'
                keys_upload_formular += '<option>video/mpeg</option>\n'
                keys_upload_formular += '<option>video/ogg</option>\n'
                keys_upload_formular += '</select>\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>\n'
                keys_upload_formular += '<input type="hidden" name="success_action_redirect" value="http://koalacloud.appspot.com/bucket_inhalt_pure?mobile=false">\n'
                keys_upload_formular += '<input type="hidden" name="AWSAccessKeyId" value="' + AWSAccessKeyId + '">\n'
                keys_upload_formular += '<input type="hidden" name="policy" value="' + policy + '">\n'
                keys_upload_formular += '<input type="hidden" name="signature" value="' + signature + '">\n'
                keys_upload_formular += '<input type="file" name="file" size="60">\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '<tr>'
                keys_upload_formular += '<td>'
                if sprache == "de":
                    keys_upload_formular += '<input type="submit" value="Objekt in den Bucket hochladen">\n'
                else:
                    keys_upload_formular += '<input type="submit" value="upload objekt into bucket">\n'
                keys_upload_formular += '</td>'
                keys_upload_formular += '</tr>'
                keys_upload_formular += '</table>'
                keys_upload_formular += '</form>'

            # Unter Eucalyptus funktioniert das Hochladen von Keys nicht
            #else:
            #  if sprache == "de":
            #    keys_upload_formular = '<p>&nbsp;</p>\n Das Hochladen von Keys funktioniert unter Eucalyptus noch nicht'
            #  else:
            #    keys_upload_formular = '<p>&nbsp;</p>\n The key upload is still not working with Eucaplyptus'

            if laenge_liste_keys != 0:
                alle_keys_loeschen_button = '<p>&nbsp;</p>\n'
                alle_keys_loeschen_button += '<form action="/alle_keys_loeschen" method="get">\n'
                alle_keys_loeschen_button += '<input type="hidden" name="mobile" value="' + mobile + '">'
                alle_keys_loeschen_button += '<input type="hidden" name="s3_ansicht" value="pur"> \n'
                alle_keys_loeschen_button += '<input type="hidden" name="bucket_name" value="' + bucketname + '"> \n'
                if sprache == "de":
                    alle_keys_loeschen_button += '<input type="submit" value="Alle Objekte l&ouml;schen">\n'
                else:
                    alle_keys_loeschen_button += '<input type="submit" value="Erase all objects">\n'
                alle_keys_loeschen_button += '</form>\n'
            else:
                alle_keys_loeschen_button = ''

            path = '&amp;path=bucket_inhalt_pure&amp;bucket=' + bucketname + '&amp;mobile=' + mobile

            template_values = {
                'navigations_bar': navigations_bar,
                'url': url,
                'url_linktext': url_linktext,
                'zone': regionname,
                'zone_amazon': zone_amazon,
                'zonen_liste': zonen_liste,
                'bucket_keys_tabelle': bucket_keys_tabelle,
                'input_error_message': input_error_message,
                'bucketname': bucketname,
                'keys_upload_formular': keys_upload_formular,
                #'eucalyptus_warnung': eucalyptus_warnung,
                'alle_keys_loeschen_button': alle_keys_loeschen_button,
                'mobile': mobile,
                'path': path,
            }

            if mobile == "true":
                path = os.path.join(os.path.dirname(__file__),
                                    "../templates/mobile", sprache,
                                    "s3_keys_pur.html")
            else:
                path = os.path.join(os.path.dirname(__file__), "../templates",
                                    sprache, "s3_keys_pur.html")
            self.response.out.write(template.render(path, template_values))
 def get(self):
     path = os.path.join(os.path.dirname(__file__), 'Baskin.html')
     self.response.out.write(template.render(path, {}))
Exemple #49
0
 def get(self):
   """Serves the template"""
   self.response.out.write(template.render(self.template_path, {}))
 def get(self):
     self._require_admin()
     self.template_values['cur_year'] = datetime.datetime.now().year
     path = os.path.join(os.path.dirname(__file__), '../../templates/admin/debug.html')
     self.response.out.write(template.render(path, self.template_values))
Exemple #51
0
def RenderTemplate(template_name, template_values=None):
    template_values = template_values or {}
    template_file = os.path.join(os.path.dirname(__file__), 'templates',
                                 template_name)
    return template.render(template_file, template_values)
Exemple #52
0
 def get(self):
   """Writes out the root page"""
   self.response.out.write(
     self.response.out.write(template.render('index.tpl', {})))
Exemple #53
0
	def get(self):
		self.response.out.write(template.render('help.html', logged()))
Exemple #54
0
    def post(self):
        trip_key = self.request.get('trip_key').strip()
        if users.get_current_user():
            trip = db.get(db.Key(trip_key))
            viewhelper = ViewHelper(self.request)
            template_values = viewhelper.get_navigation_options()
            template_values.update(viewhelper.get_menu_options())

            if trip and trip.who == users.get_current_user():
                count = 0
                triplegs = []
                total_distance = 0
                for waypoint, distance in zip(trip.waypoints, trip.distances):
                    distance_miles = '%.1f' % (distance * 0.000621371192)
                    tripleg = TripLegView(waypoint, None, distance_miles,
                                          trip.when, count)
                    triplegs.append(tripleg)
                    count = count + 1
                    total_distance = total_distance + distance

                #fill triplegs with blank i it is less than 10
                if len(triplegs) < 10:
                    extras = 10 - len(triplegs)
                    trips_length = len(triplegs)
                    for i in range(extras):
                        tripleg = TripLegView('', None, 0, '',
                                              trips_length + i)
                        logging.debug('Added filler tripleg #' +
                                      str(trips_length + i))
                        triplegs.append(tripleg)

                if trip.total_distance and trip.total_distance > 0:
                    total_miles = '%.1f' % trip.total_distance
                else:
                    total_miles = '%.1f' % (total_distance * 0.000621371192)

                tripdate = trip.when.strftime('%m/%d/%Y')

                try:
                    cost_per_mile_pound = int(trip.pence_per_mile / 100)
                except:
                    cost_per_mile_pound = 0

                if cost_per_mile_pound > 0:
                    cost_per_mile_pence = trip.pence_per_mile - (
                        cost_per_mile_pound * 100)
                else:
                    cost_per_mile_pence = 0

                label_parking_expenses = trip.other_expenses_label or ''

                try:
                    other_expenses_charges_pound = int(
                        trip.other_expenses_charge / 100)
                except:
                    other_expenses_charges_pound = 0

                if trip.other_expenses_charge > 0:
                    other_expenses_charges_pence = trip.other_expenses_charge - (
                        other_expenses_charges_pound * 100)
                else:
                    other_expenses_charges_pence = 0

                other_no_passengers = trip.passenger_count if trip.passenger_count else 0
                other_passenger_miles = trip.passenger_mileage if trip.passenger_mileage else 0

                mode_of_travel = trip.trip_code.strip(
                ) if trip.trip_code else ''

                template_values.update({
                    'triplegs':
                    triplegs,
                    'total_miles':
                    total_miles,
                    'tripdate':
                    tripdate,
                    'trip_key':
                    trip_key,
                    'cost_per_mile_pound':
                    cost_per_mile_pound,
                    'cost_per_mile_pence':
                    cost_per_mile_pence,
                    'label_parking_expenses':
                    label_parking_expenses,
                    'other_expenses_charges_pound':
                    other_expenses_charges_pound,
                    'other_expenses_charges_pence':
                    other_expenses_charges_pence,
                    'mode_of_travel':
                    mode_of_travel,
                    'other_no_passengers':
                    other_no_passengers,
                    'other_passenger_miles':
                    other_passenger_miles
                })

            else:
                template_values.update({
                    'app_notification': 'Cannot find the trip.',
                    'app_notification_type': 'app_error'
                })

            path = os.path.join(os.path.dirname(__file__), '../../templates',
                                'index.html')
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect('/')
Exemple #55
0
    def errorFunc(self):
      fpath = os.path.join(os.path.dirname(__file__),'template/user','error.html')
      html = template.render(fpath,'')
      self.response.out.write(html)

      return
Exemple #56
0
 def write(self):
     self.response.out.write(template.render(self.template, self.values))
    def _render(self, district_abbrev, year=None, explicit_year=False):
        district_type = DistrictType.abbrevs[district_abbrev]

        event_keys = Event.query(
            Event.year == year,
            Event.event_district_enum == district_type).fetch(None,
                                                              keys_only=True)
        if not event_keys:
            self.abort(404)

        # needed for district teams
        district_key = '{}{}'.format(year, district_abbrev)
        district_teams_future = DistrictTeamsQuery(district_key).fetch_async()

        # needed for valid_years
        all_cmp_event_keys_future = Event.query(
            Event.event_district_enum == district_type,
            Event.event_type_enum == EventType.DISTRICT_CMP).fetch_async(
                None, keys_only=True)

        # needed for valid_districts
        district_cmp_keys_future = Event.query(
            Event.year == year,
            Event.event_type_enum == EventType.DISTRICT_CMP).fetch_async(
                None, keys_only=True)  # to compute valid_districts

        event_futures = ndb.get_multi_async(event_keys)
        event_team_keys_future = EventTeam.query(
            EventTeam.event.IN(event_keys)).fetch_async(None, keys_only=True)
        team_futures = ndb.get_multi_async(
            set([
                ndb.Key(Team,
                        et_key.id().split('_')[1])
                for et_key in event_team_keys_future.get_result()
            ]))

        events = [event_future.get_result() for event_future in event_futures]
        EventHelper.sort_events(events)

        district_cmp_futures = ndb.get_multi_async(
            district_cmp_keys_future.get_result())

        team_totals = DistrictHelper.calculate_rankings(
            events, team_futures, year)

        valid_districts = set()
        for district_cmp_future in district_cmp_futures:
            district_cmp = district_cmp_future.get_result()
            cmp_dis_type = district_cmp.event_district_enum
            if cmp_dis_type is None:
                logging.warning(
                    "District event {} has unknown district type!".format(
                        district_cmp.key.id()))
            else:
                valid_districts.add((DistrictType.type_names[cmp_dis_type],
                                     DistrictType.type_abbrevs[cmp_dis_type]))
        valid_districts = sorted(valid_districts, key=lambda (name, _): name)

        teams = TeamHelper.sortTeams(district_teams_future.get_result())

        num_teams = len(teams)
        middle_value = num_teams / 2
        if num_teams % 2 != 0:
            middle_value += 1
        teams_a, teams_b = teams[:middle_value], teams[middle_value:]

        self.template_values.update({
            'explicit_year':
            explicit_year,
            'year':
            year,
            'valid_years':
            sorted(
                set([
                    int(event_key.id()[:4])
                    for event_key in all_cmp_event_keys_future.get_result()
                ])),
            'valid_districts':
            valid_districts,
            'district_name':
            DistrictType.type_names[district_type],
            'district_abbrev':
            district_abbrev,
            'events':
            events,
            'team_totals':
            team_totals,
            'teams_a':
            teams_a,
            'teams_b':
            teams_b,
        })

        path = os.path.join(os.path.dirname(__file__),
                            '../templates/district_details.html')
        return template.render(path, self.template_values)
Exemple #58
0
                        int(add_to_schedule_form.cleaned_data['device_count']))
                else:
                    task.put()

        schedule = model.Task.all()
        schedule.order('-created')

        template_args = {
            'user_schedule_admin': acl.UserIsScheduleAdmin(),
            'add_form': add_to_schedule_form,
            'schedule': schedule,
            'user': users.get_current_user().email(),
            'logout_link': users.create_logout_url('/')
        }
        self.response.out.write(
            template.render('templates/schedule.html', template_args))

    def Delete(self, **unused_args):
        """Delete a task from the schedule."""
        if not acl.UserIsScheduleAdmin():
            self.error(404)
            return

        errormsg = None
        message = None
        add_to_schedule_form = type('AddToScheduleForm', (forms.BaseForm, ),
                                    {'base_fields': self._BuildFields()})()

        task_id = self.request.get('id')
        task = model.Task.get_by_id(int(task_id))
        if not task:
Exemple #59
0
 def go_to_login(self, data):
     for name, uri in providers.items():
         data[name] = users.create_login_url(federated_identity=uri)
     path = os.path.join(os.path.dirname(__file__),
                         "templates/others/login.html")
     self.response.out.write(template.render(path, data))
Exemple #60
0
 def Render(self, template_file, values):
   path = os.path.join(os.curdir, '..', 'templates', template_file)
   self.response.out.write(template.render(path, values))