def get(self): #user_email = get_email() user = users.get_current_user() if user: # fetch the user from the database user_key = ndb.Key("Account", user.user_id()) user_account = user_key.get() #If the user isn't found in the database, add to the database if not user_account: logging.info("USER NOT FOUND, ADDING NOW") user_account = Account(id=user.user_id(), name = user.nickname(), hobby_text = '') user_key = user_account.put() else: logging.info("USER FOUND") logging.info(user_account) # Redirect to the user's view profile page self.redirect('/viewprofile?id=' + user.user_id()) template_params = { "user":user.email(), "login":users.create_login_url(), "logout":users.create_logout_url('/'), "name":user_account.name, "hobby":user_account.hobby_text, "modified":user_account.modified } else: logging.info("NOT LOGGED IN") template_params = { "user":None, "login":users.create_login_url('/'), "logout":users.create_logout_url('/') } render_template(self, 'index.html', template_params)
def get(self, bandid): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) logging.info('bandid: ' + bandid) try: namespace_manager.set_namespace(bandid) except: self.error(400); return conf = Configuration.get_by_id("singleton") if user not in conf.users: conf.users.append(user) # TODO: For now users are authenticated by default. This should # probably be a configuration parameter. conf.auth_users.append(user) conf.put() ranking_query = SongNode.query().order(-SongNode.vote_cnt) ranking_query = ranking_query.filter(SongNode.vote_cnt < conf.votes_to_graduate) songs = ranking_query.fetch(50) template_values = { 'is_admin': conf.admin == user, 'songs': songs, 'band_name': conf.name, 'bandid': bandid, 'logout_uri': users.create_login_url(self.request.uri), 'votes_to_graduate': conf.votes_to_graduate } template = JINJA_ENVIRONMENT.get_template('ranking.html') self.response.write(template.render(template_values))
def get(self): 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' return self.redirect(users.create_login_url(self.request.uri)) locations = OwnerLocations.all().filter('owner = ', users.get_current_user()) user=users.get_current_user() if locations.count() == 0: locations = {} message_body = """ Welcome to the miingle app """ mail.send_mail( sender='*****@*****.**', to='*****@*****.**', subject='welcome to miingle', body=message_body) template_values = { 'locations': locations, 'userdisplay' : user.nickname(), 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'searchlocations.html') self.response.out.write(template.render(path, template_values))
def get(self): questionID = self.request.get('id') id = get_user_id() review = models.getQuestionFromURL(questionID) is_admin = 0 if users.is_current_user_admin(): is_admin = 1 if id is not None: q = models.check_if_user_exists(id) if q == None: page_params = { 'upload_url': blobstore.create_upload_url('/profile'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': get_user_id(), 'profile': models.getUser(id), 'admin': is_admin } render_template(self, 'createProfile.html' ,page_params) return page_params = { 'upload_urlQE': blobstore.create_upload_url('/ReviewQuestion?id=' + questionID), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': id, 'review': review, 'admin' : is_admin } render_template(self, 'questionReview.html', page_params)
def get(self): continue_url = self.request.GET.get('continue') openid_url = self.request.GET.get('openid') if openid_url: self.redirect(users.create_login_url(continue_url, None, openid_url)) else: self.redirect(users.create_login_url(continue_url, None, federated_identity='https://openid.nus.edu.sg/'))
def get(self): forum = Forum.from_url(self.request.path_info) user = users.get_current_user() is_admin = users.is_current_user_admin() if not forum or (forum.is_disabled and not is_admin): return self.redirect("/") if not is_admin and not self.settings.check_ip(self.request.remote_addr): return self.response.out.write('Your IP address has been banned') if not is_admin and not self.settings.check_user( user ): return self.redirect( users.create_login_url("/") ) offset, topics = Topic.getlist(forum, is_admin=is_admin, offset=self.request.get("from") or None) for topic in topics: topic.excerpt = Post.gql("WHERE topic = :1 ORDER BY created_on", topic)[0].get_excerpt() tvals = { 'user': user, 'analytics_code': forum.analytics_code or "", 'siteurl': self.request.url, 'isadmin': is_admin, 'forum' : forum, 'forum_urls': [f.url for f in Forum.all()], 'topics': topics, 'offset': offset, 'login_url': users.create_login_url(forum.root()), 'logout_url': users.create_logout_url(forum.root()) } self.template_out("skins/default/topic_list.html", tvals)
def get(self): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) query = UrlItem.all() query.filter("owner =", users.get_current_user()) query.order("-date") url_items = query.fetch(10) 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 = { 'current_user': users.get_current_user(), 'url_items': url_items, 'url': url, 'url_linktext': url_linktext, } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values))
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))
def _handler(self, expense_key, post=False): user = users.get_current_user() if user: instance = Transaction.get(expense_key) if instance.user != user: self.redirect(users.create_login_url(self.request.uri)) if post: form = IncomeForm(user, instance=instance, data=self.request.POST) if form.is_valid(): transaction = form.save(commit=False) transaction.account = transaction.customer.account transaction.put() self.redirect("/receitas/") form = IncomeForm(user, instance=instance) path = os.path.join(os.path.dirname(__file__), 'templates/income.html') self.response.out.write(template.render(path, { 'form': form, 'user': user, 'logout_url': users.create_logout_url("/") })) else: self.redirect(users.create_login_url(self.request.uri))
def getTemplateValues(self, cgiArgs): user = users.get_current_user() greeting = '' logoutUrl = '' loginUrl = '' email = '' isOnGoogleCode = self.request.path.find('apis/ajax/playground') if cgiArgs != '': cgiArgs = '?' + cgiArgs if user: greeting = '%s' % (user.nickname()) email = user.email() if isOnGoogleCode != -1: logoutUrl = users.create_logout_url('/apis/ajax/playground/' + cgiArgs) else: logoutUrl = users.create_logout_url('/' + cgiArgs) else: if isOnGoogleCode != -1: loginUrl = users.create_login_url('/apis/ajax/playground/' + cgiArgs) else: loginUrl = users.create_login_url('/' + cgiArgs) template_values = { 'loginUrl': loginUrl, 'greeting': greeting, 'logoutUrl': logoutUrl, 'userEmail': email } return template_values
def get(self): template = jinja_environment.get_template('templates/supplement-info.html') name = self.request.get('name') company = CompanyInfo.query().filter(CompanyInfo.company_name == name).fetch()[0] stringOfQuestions = company.required_supplement listOfQuestions = stringOfQuestions.split("?") listOfSupplements = []; for sentence in listOfQuestions: if sentence != "": newSentence = sentence + "?" logging.info(newSentence) logging.info(sentence) logging.info(stringOfQuestions) listOfSupplements.append(newSentence) user = users.get_current_user() if user: user_id = user.user_id() greeting = ('<a href="%s">Sign out!</a>.' % users.create_login_url('/')) else: greeting = ('<a id="login" href="%s">Sign in with your gmail account!</a>.' % users.create_login_url('/')) template_list = {"listOfSupplements" : listOfSupplements, "login" : greeting} self.response.write(template.render(template_list))
def getOwnerDetails(handler, owner): mocklists = [] if owner: q = MockList.gql("WHERE owner = :1", owner).fetch(1000) for mocklist in q: mocklists.append({ 'id' : mocklist.get_id(), 'name' : mocklist.name }) return { 'mocklists' : mocklists, 'name' : str(owner.email), 'sign_in_url' : users.create_login_url("/signin/?d=" + handler.request.path), 'sign_out_url' : users.create_logout_url("/"), 'signed_in' : bool(users.get_current_user()), } else: return { 'mocklists' : [], 'name' : '', 'sign_in_url' : users.create_login_url("/signin/?d=" + handler.request.path), 'sign_out_url' : users.create_logout_url("/"), 'signed_in' : False, }
def get(self): user = users.get_current_user() if user: # Use existing user or generate a new one if they don't exist. owner = Owner.gql("WHERE user_id = :1", user.user_id()).get() if not owner: owner = Owner() owner.name = user.nickname() owner.email = user.email() owner.user_id = user.user_id() owner.hobo_id = '' owner.put() # Migrate not-signed-in mocks to account. old_owner = None if 'hobo_id' in self.request.cookies: old_owner = Owner.gql("WHERE hobo_id = :1", self.request.cookies['hobo_id']).get() if old_owner and owner != old_owner: mocklists = MockList.gql("WHERE owner = :1", old_owner).fetch(1000) for mocklist in mocklists: mocklist.owner = owner mocklist.put() old_owner.delete() if self.request.get("d"): self.redirect(self.request.get("d")) else: self.redirect("/") else: users.create_login_url("/signin/")
def get(self): user = users.get_current_user() if user is None: login_url = users.create_login_url(self.request.path) self.redirect(login_url) return else: if user.email() in ADMIN_USER_IDS: userslist={}; q1= TestDetails.query(); q1.fetch(); count=0; for data in q1: lcenter=data.learningcenter; if not userslist.has_key(lcenter): count=1; userslist[lcenter]=count; else: count=int(userslist[lcenter]); userslist[lcenter]=count+1; template_values = {'tests':userslist} template = JINJA_ENVIRONMENT.get_template('admin.html') self.response.write(template.render(template_values)) else: users.create_logout_url('/') login_url = users.create_login_url(self.request.path) #self.redirect(login_url) self.response.write("<center><h3><font color='red'>Invalid Admin Credentials</font></h3><h3>Please <a href='%s'>Login</a> Again</h3></center>"% login_url);
def checkAuth(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) else: if not (user.email() == "*****@*****.**" or user.email() == "*****@*****.**"): self.redirect(users.create_login_url(self.request.uri))
def get(self): #get user and login usr = users.get_current_user() if not usr: url = users.create_login_url(self.request.uri) url_linktext = 'Login' self.redirect(users.create_login_url(self.request.uri)) else: url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' #get the client key to start a channel key = self.request.get('client_key') if not key: key = usr.email() #create token to use on channel with client token = channel.create_channel(str(key)) #send template values template_values = {'user': usr, 'token': token, 'client_key': key, 'url': url, 'url_linktext': url_linktext, } template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values))
def get(self): #login usr = users.get_current_user() if not usr: url = users.create_login_url(self.request.uri) url_linktext = 'Login' self.redirect(users.create_login_url(self.request.uri)) else: url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' #testing users deb model userlist = User.query().fetch(5) #get files from bucket for the user bucket_name = "/"+os.environ.get('BUCKET_NAME',app_identity.get_default_gcs_bucket_name())+"/"+str(usr) l_files=gcs.listbucket(bucket_name) #get shared files of the user sh_files = SharedFile.query(SharedFile.recipients == usr.email()) result = sh_files.fetch(1000) template_values = { 'url': url, 'url_linktext': url_linktext, 'user_name': usr, 'files': l_files, 'users': userlist, 'shared_files': sh_files, } template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values))
def get(self): if users.get_current_user(): staff = (str(users.get_current_user().email())) #check if user is admin method goes here domain = re.search("(?<=@)[\w.]+", staff) mydomain = domain.group() if mydomain == 'intellisoftplus.com': url = "https://crm.zoho.com/crm/private/json/Leads/getRecords?authtoken=b72f0f5ed3d2afa9b8a314649d3cf66f&scope=crmapi" response = urllib.urlopen(url) leads = json.loads(response.read()) url_accounts = "https://crm.zoho.com/crm/private/json/Accounts/getRecords?authtoken=b72f0f5ed3d2afa9b8a314649d3cf66f&scope=crmapi" response_accounts = urllib.urlopen(url_accounts) accounts = json.loads(response_accounts.read()) template_values = { 'leads':leads, 'accounts':accounts } template = jinja2_env.get_template('main/records.html') self.response.out.write(template.render(template_values)) else: self.redirect(users.create_login_url(self.request.uri)) else: self.redirect(users.create_login_url(self.request.uri))
def get(self): if users.get_current_user(): staff = (str(users.get_current_user().email())) #check if user is admin method goes here domain = re.search("(?<=@)[\w.]+", staff) mydomain = domain.group() if mydomain == 'intellisoftplus.com': url = "https://books.zoho.com/api/v3/customerpayments?authtoken=640df7b6237bec6ccc0101aec2a1605d&organization_id=8470645" response = urllib.urlopen(url) data = json.loads(response.read()) url_invoice = "https://books.zoho.com/api/v3/invoices?authtoken=640df7b6237bec6ccc0101aec2a1605d&organization_id=8470645" response_invoice = urllib.urlopen(url_invoice) data_invoice = json.loads(response_invoice.read()) template_values = { 'data':data, 'data_invoice':data_invoice } template = jinja2_env.get_template('main/zbooks.html') self.response.out.write(template.render(template_values)) else: self.redirect(users.create_login_url(self.request.uri)) else: self.redirect(users.create_login_url(self.request.uri))
def testMakeStaticHandler(self): dummy_template = object() dummy_path = object() dummy_url = object() handler_class = base.MakeStaticHandler(dummy_template) handler = handler_class() handler.request = self.mox.CreateMockAnything() handler.request.path = dummy_path self.mox.StubOutWithMock(users, 'get_current_user') self.mox.StubOutWithMock(users, 'create_login_url') self.mox.StubOutWithMock(handler, 'RenderTemplate') self.mox.StubOutWithMock(handler, 'redirect') # Logged in; render. users.get_current_user().AndReturn(True) handler.RenderTemplate(None, '', dummy_template, {}) # Not logged in; redirect. users.get_current_user().AndReturn(None) users.create_login_url(dummy_path).AndReturn(dummy_url) handler.redirect(dummy_url) self.mox.ReplayAll() handler.get() handler.get()
def get(self): if users.get_current_user(): staff = (str(users.get_current_user().email())) #check if user is admin method goes here if validate_staff_email(staff): url_invoice = "https://books.zoho.com/api/v3/invoices?authtoken=640df7b6237bec6ccc0101aec2a1605d&organization_id=8470645" invoices = [] try: response_invoice = urllib.urlopen(url_invoice) data_invoice = json.loads(response_invoice.read()) present_keys = [] for invoice in data_invoice['invoices']: name = invoice['customer_name'] if name not in present_keys: present_keys.append(name) invoices.append(invoice) except IOError: pass template_values = { 'data_invoice':invoices, 'logout': users.create_logout_url(self.request.uri) } template = jinja2_env.get_template('main/customerinfo.html') self.response.out.write(template.render(template_values)) else: self.redirect(users.create_login_url(self.request.uri)) else: self.redirect(users.create_login_url(self.request.uri))
def handle_openid(self, continue_url=None, openid_url=None): if openid_url: self.redirect(users.create_login_url(continue_url, None, openid_url)) else: self.response.out.write(template.render( 'templates/login.html', { 'google_url': users.create_login_url(federated_identity=providers.get('Google')) }))
def get(self): #user_param = self.request.get('user_param') #if (user_param == 'admin'): user = users.get_current_user() if user: if users.is_current_user_admin(): logout_url = users.create_logout_url(self.request.uri) logout = 'Welcome! (<a href="{}">sign out</a>)'.format(logout_url) to_confirm = Startup.query(Startup.accettato == 0) to_confirm_list = to_confirm.fetch() confirm_param = { 'to_confirm_list': to_confirm_list, 'logout': logout, } template = JINJA_ENVIRONMENT.get_template('confirm.html') out = template.render(confirm_param) else: login_url = users.create_login_url(self.request.uri) out = '<html><body><a style="color: #428bca; text-decoration: none;" href="{}">SIGN IN</a></body></html>'.format(login_url) else: login_url = users.create_login_url(self.request.uri) out = '<html><body><a style="color: #428bca; text-decoration: none;" href="{}">SIGN IN</a></body></html>'.format(login_url) self.response.write(out)
def get(self): id = get_user_id() is_admin = 0 if users.is_current_user_admin(): is_admin = 1 if id is not None: q = models.check_if_user_exists(id) if q == None: page_params = { 'upload_url': blobstore.create_upload_url('/profile'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': get_user_id(), 'profile': models.getUser(id), 'admin': is_admin } render_template(self, 'createProfile.html' ,page_params) return newList = models.getCategoryList() page_params = { 'catList': newList, 'upload_urlQ': blobstore.create_upload_url('/NewQuestion'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': id, 'admin' : is_admin } render_template(self, 'newQuestionSubmit.html', page_params)
def get(self): user = users.get_current_user() url = users.create_login_url(self.request.uri) url_linktext = 'Login' if user: url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: self.redirect(users.create_login_url(self.request.uri)) # GQL is similar to SQL id = self.request.get('id') selectionsview = SelectionSujetModel.getSelectionByEspaceID(id) values = { 'selections' : selectionsview, 'id':id, 'user': user, 'url': url, 'url_linktext': url_linktext, } self.response.out.write(template.render('templates/selectionsujet.html', values))
def get(self): id = get_user_id() jAson = models.getAllUserScores() userList = json.dumps(jAson) is_admin = 0 if users.is_current_user_admin(): is_admin = 1 if id is not None: q = models.check_if_user_exists(id) if q == None: page_params = { 'upload_url': blobstore.create_upload_url('/profile'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': get_user_id(), 'profile': models.getUser(id), 'admin': is_admin } render_template(self, 'createProfile.html' ,page_params) return newList = models.getCategoryList() page_params = { 'category': 'ALL', 'catList': newList, 'user_id': get_user_id(), 'list': jAson, 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'admin': is_admin, } render_template(self, 'leaderboard.html', page_params)
def get(self): id = get_user_id() trueList = models.getCategoryList(True) falseList = models.getCategoryList(False) is_admin = 0 if users.is_current_user_admin(): is_admin = 1 if id is not None: q = models.check_if_user_exists(id) if q == None: page_params = { 'upload_url': blobstore.create_upload_url('/profile'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': get_user_id(), 'profile': models.getUser(id), 'admin': is_admin } render_template(self, 'createProfile.html' ,page_params) return page_params = { 'user_id': get_user_id(), 'trueCatList': trueList, 'falseCatList': falseList, 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'admin': is_admin, } render_template(self, 'reviewCategories.html', page_params)
def test_switch_to_same_account(self): gcu = 'djangae.contrib.gauth.middleware.users.get_current_user' final_destination = '/death/' switch_accounts_url = get_switch_accounts_url(next=final_destination) any_url = '/_ah/warmup' jekyll = users.User(email='*****@*****.**', _user_id='1') with sleuth.switch(gcu, lambda: jekyll): response = self.client.get(any_url) # Check that the user is logged in expected_user_query = GaeDatastoreUser.objects.filter(username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client.session['_auth_user_id']), expected_user_query[0].pk) # Call switch_accounts view, which should give a redirect to login url response = self.client.get(switch_accounts_url, follow=False) self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], users.create_login_url(switch_accounts_url)) # Assume the user is signed in to one account, so it should redirect to logout url response = self.client.get(switch_accounts_url) self.assertEqual(response.status_code, 302) self.assertEqual( response['location'], users.create_logout_url(users.create_login_url(switch_accounts_url)) ) # Now the user decides against switching accounts and comes back with the same account response = self.client.get(switch_accounts_url) redirect_path = urlparse(response['location']).path self.assertEqual(redirect_path, final_destination) expected_user_query = GaeDatastoreUser.objects.filter(username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client.session['_auth_user_id']), expected_user_query[0].pk)
def get(self): id = get_user_id() #just loops and prints every question from query review = models.get_oldest_questions(True,False) is_admin = 0 if users.is_current_user_admin(): is_admin = 1 if id is not None: q = models.check_if_user_exists(id) if q == None: page_params = { 'upload_url': blobstore.create_upload_url('/profile'), 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': get_user_id(), 'profile': models.getUser(id), 'admin': is_admin } render_template(self, 'createProfile.html' ,page_params) return page_params = { 'user_email': get_user_email(), 'login_url': users.create_login_url(), 'logout_url': users.create_logout_url('/'), 'user_id': id, 'review': review, 'admin' : is_admin } render_template(self, 'viewDatabase.html', page_params)
def check_user(view): c_user = users.get_current_user() if c_user: log = users.create_logout_url(url_for('index')) else: if view[0] in ('security'): log = users.create_login_url(url_for(view[0], pos=view[1])) elif view[0] in ('sec_info', 'edit_security'): log = users.create_login_url(url_for(view[0], pos=view[1], sec_id=view[2])) else: log = users.create_login_url(url_for(view[0])) # Create a new portfolio if new user if c_user: ptfs = Portfolio.query(Portfolio.user == c_user) ptfs = list(ptfs) if len(ptfs) == 0: ptf = Portfolio( user = c_user, points = START_POINTS ) ptf.put() ptf_id = ptf.key.id() flash(u'Portfolio %s successfully created.' % ptf_id, 'success') return [c_user, log]
def get(self): return self.render("login.html", googleurl=users.create_login_url("/profile"))
def post(self): for blob_info in self.get_uploads(): if not users.get_current_user(): #if they are not logged in then delete all the upload data and redirect them to login for blob in self.get_uploads(): blob.delete() self.redirect(users.create_login_url("/")) return #if uploading a csv file, update the datastore to match records in file if blob_info.content_type == "application/vnd.ms-excel": blobdata = blobstore.BlobReader(blob_info) reader = csv.DictReader(blobdata, dialect='excel') self.response.headers['Content-Type'] = 'text/plain' for row in reader: artist = row["Artist"] categories = row["Categories"] name = row["Name of Piece"] price = row["Price($)"] itemNumber = row["Item Number"] width = row["Width(in)"] height = row["Height(in)"] depth = row["Depth(in)"] weight = row["Weight"] width = row["Width(in)"] description = row["Product Description"] colors = row["Colors"] mediums = row["Mediums"] masterNum = row["Master Art Piece (Item Number)"] pictureName = row["Picture Name"] #check if artpiece with this item number already exists qry = ArtPiece.query(ArtPiece.itemNumber == itemNumber) existingArtPiece = qry.get() #if existingArtPiece: #if an artpiece with that itemNumber is already stored then update the record with the new information #delete and skip to the next file, we don't save excel files nor do we perform photo related code blob_info.delete() continue #otherwise we assume it is a photo (since it only allows jpg, png, gif, and csv) else: #check to see if a photo with that name already exists qry = File.query(File.file_name == blob_info.filename.upper()) existingPhoto = qry.get() if existingPhoto: #if a file with that name is already stored then replace the blob with the new uploaded file blobstore.delete(existingPhoto.blob) existingPhoto.blob = blob_info.key() existingPhoto.uploaded_by = users.get_current_user() existingPhoto.thumbnail = images.get_serving_url( blob_info.key(), size=200) existingPhoto.url = images.get_serving_url(blob_info.key()) existingPhoto.put() else: #add a new file entry if no file with that name already exists file = File(blob=blob_info.key(), file_name=blob_info.filename.upper(), uploaded_by=users.get_current_user(), url=images.get_serving_url(blob_info.key()), thumbnail=images.get_serving_url( blob_info.key(), size=200)) file.put() self.redirect("/admin/photos/%s/success" % blob_info.key())
def get(self, identity): url = users.create_login_url(dest_url='/', federated_identity=identity) self.redirect(url)
def get_login_url(self): return users.create_login_url(self.request.uri)
def get(self): # データブックの名前を取得 databook_name = get_databook_name(self.request.get('db')) # データブックの表示タイトルを取得 databook_title = get_databook_title(self.request.get('db')) # 全文検索用インデックスの名前を取得 databook_indexname = get_databook_indexname(self.request.get('db')) # 表示メッセージの初期化 message_data = '' # 管理者ログインのチェック admin_login = False if users.is_current_user_admin(): admin_login = True # 管理者ログイン中の表示 admin_message = '' if users.get_current_user(): if admin_login: admin_message = '(管理者としてログインしています)' else: admin_message = '(管理者ではありません)' # ログイン/ログアウトURL設定 if users.get_current_user(): login_url = users.create_logout_url(self.request.uri) login_text = '[ログアウト]' else: login_url = users.create_login_url(self.request.uri) # login_text = '[ログイン]' login_text = '[管理]' # 書き込み禁止の判定 write_disabled_message = '' if not capabilities.CapabilitySet('datastore_v3', ['write']).is_enabled(): write_disabled_message = '【現在書き込みは禁止しています】' # 全文検索の単語を取得 search_flag = False search_count = 0 search_word = self.request.get('word').strip() # 全文検索の単語の先頭が「=」のときは特別扱い show_all_flag = False show_offset = 0 if search_word.startswith('='): i = 1 while i < len(search_word): ch = search_word[i] # 「*」のときは表示フラグを無視して全て表示する if ch == '*': i += 1 show_all_flag = True continue # 数字のときは表示件数のオフセットとする if ch.isdigit(): i += 1 j = i - 1 while i < len(search_word): ch = search_word[i] if ch.isdigit(): i += 1 continue break k = i if (k - j) > 5: k = j + 5 show_offset = int(search_word[j:k]) continue # その他のときは抜ける break search_word2 = search_word[i:] else: search_word2 = search_word # 全文検索の単語をチェック if search_word2: # 全文検索を行うとき articles = [] # 検索結果を日付の降順でソートする指定 expr_list = [ search.SortExpression( expression='date', default_value=datetime.datetime.min, direction=search.SortExpression.DESCENDING) ] # ソートオプションに設定する sort_opts = search.SortOptions(expressions=expr_list) # クエリーオプションに設定する # (表示件数指定、ソートオプション指定、検索結果はタイトルのみ取得) query_opts = search.QueryOptions(limit=mainpage_show_num, offset=show_offset, sort_options=sort_opts, returned_fields=['title']) try: # 単語とクエリーオプションを指定して全文検索実行 query_obj = search.Query(query_string=search_word2, options=query_opts) search_results = search.Index(name=databook_indexname).search( query=query_obj) # 検索結果から記事のタイトルを取得する req_titles = [] for scored_doc in search_results: req_titles.append(scored_doc.field('title').value) if len(req_titles) >= 1: # 記事を検索(タイトルで表示件数まで) if show_all_flag: articles_query = Article.query( Article.title.IN(req_titles), ancestor=databook_key(databook_name)).order( -Article.date) else: articles_query = Article.query( Article.title.IN(req_titles), Article.show_flag == 1, ancestor=databook_key(databook_name)).order( -Article.date) articles = articles_query.fetch(mainpage_show_num) except (search.QueryError, search.InvalidRequest), e: # クエリーエラーのとき message_data = message_data + '(クエリーエラー:検索文字列に記号が含まれると発生することがあります)' search_flag = True search_count = len(articles)
if self.errorMsg is not '': self.set_cookie('error', str(self.errorMsg)) self.response.out.write(json.dumps(material)) elif self.request.get('unit'): material = self.get_material( int(self.request.get('unit')), self.request.get('stage') == 'review') self.response.out.write(material) elif self.request.get('recent'): disciple = Disciple.get_current(user) material = self.dictionary.prepare_for_quiz( json.loads(disciple.recent_mastered)) self.response.out.write(json.dumps(material)) else: self.redirect(users.create_login_url(self.request.uri)) def get_material(self, unitIndex, isCumulative): stuff = LESSONS[unitIndex]["quiz"] if (isCumulative and unitIndex > 0): stuff = LESSONS[unitIndex]["quiz"] for i in reversed(range(0, unitIndex)): stuff = dict(stuff.items() + LESSONS[i]["quiz"].items()) stuff = [int(i) for i in stuff.keys()] return stuff app = webapp2.WSGIApplication([('/quiz/?', QuizPage), ('/quiz/data', QuizData)], debug=True)
def get(self): user = users.get_current_user() if user: log_out_url = users.create_logout_url("/") coach = Coach.all().filter("user ="******"schedule").split("-") if not season or not week: season, week = misc.get_ofl_season_and_week() season += 3 else: season = int(season) week = int(week) parser = OFLScheduleParser() ofl_info = urlfetch.fetch( "http://www.shalkith.com/bloodbowl/processSchedule.php?s=%s&w=%s" % (season, week)) parser.feed(ofl_info.content) update_schedule_entries(coach, season, week, parser.data) sort_wagers(coach, season, week) def logoA_getter(match): html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % ( match.teamAlogo) return html def logoB_getter(match): html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % ( match.teamBlogo) return html def nameA_getter(prediction): match = OFL_Match.get_by_key_name(prediction.key().name()) html = "%s (%s)" % (match.teamA, match.teamAcoach) return html def nameB_getter(prediction): match = OFL_Match.get_by_key_name(prediction.key().name()) html = "%s (%s)" % (match.teamB, match.teamBcoach) return html def key_name_getter(prediction): return prediction.key().name() def choice_getter(prediction): match = OFL_Match.get_by_key_name(prediction.key().name()) html = "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % ( match.teamAlogo) if not match.gamePlayed: html += "<input type='radio' name='%schoice' value='-1' %s>" % ( match.key().name(), prediction.isChecked(-1)) html += "<input type='radio' name='%schoice' value='0' %s>" % ( match.key().name(), prediction.isChecked(0)) html += "<input type='radio' name='%schoice' value='1' %s>" % ( match.key().name(), prediction.isChecked(1)) else: html += "<input type='radio' name='%schoice' value='-1' disabled %s>" % ( match.key().name(), prediction.isChecked(-1)) html += "<input type='radio' name='%schoice' value='0' disabled %s>" % ( match.key().name(), prediction.isChecked(0)) html += "<input type='radio' name='%schoice' value='1' disabled %s>" % ( match.key().name(), prediction.isChecked(1)) html += "<img src='http://www.shalkith.com/bloodbowl/%s'/>" % ( match.teamBlogo) return html # Bypassing table.html Django template to create this table # Table requires Jquery code for sortable entires and wagers # Hidden input tags are also used with form. prediction_list = OFL_Prediction.all().filter( "season =", season).filter("week =", week).ancestor(coach).filter( "gameScored =", False).order("-wager") columns = ["Wager", "Away Team", "Prediction", "Home Team"] table_html = [] table_html.append(''' <table class="ofl_pickem schedule_table"> <thead> <tr>''') for column in columns: table_html.append( '<th style="text-align: center;"> %s </th>' % column) table_html.append(''' </tr> </thead> <tbody id="sortable">''') k = 0 for prediction in prediction_list: table_html.append('<tr class="row_%s">' % k) table_html.append( '<input type="hidden" name="row_%s" value="%s">' % (k, prediction.key().name())) table_html.append( "<input type='hidden' class='row_%s' name='%svalue' value='%s'>" % (k, prediction.key().name(), prediction.wager)) table_html.append( '<td class="row_%s" style="text -align: center;">%s</td>' % (k, prediction.wager)) table_html.append( '<td style="text-align: center;">%s</td>' % nameA_getter(prediction)) table_html.append( '<td style="text-align: center;">%s</td>' % choice_getter(prediction)) table_html.append( '<td style="text-align: center;">%s</td>' % nameB_getter(prediction)) k += 1 table_html.append('</tbody>\n</table>') table_html = "\n".join(table_html) played_table = Table( columns=[ # profile Column("Points", "Points Earned", attrgetter("points")), Column("Wager", "Wager Placed", attrgetter("wager")), Column("Away Team", "Away Team", nameA_getter, center=True), Column("Prediction", "Your Prediction", choice_getter, center=True), Column("Home Team", "Home Team", nameB_getter, center=True), ], query=OFL_Prediction.all().filter( "season =", season).filter("week =", week).ancestor(coach).filter( "gameScored =", True).order("-points"), id="played_table", cls="tablesorter", ) else: log_in_url = users.create_login_url("/") # render and update #--------------------------------------------------------------------# ofl_pickem_page = misc.render('ofl_pickem_box.html', locals()) self.update(ofl_pickem_page) self.response.out.write(ofl_pickem_page)
def get(self): if users.get_current_user(): self.redirect(users.create_logout_url('/')) else: self.redirect(users.create_login_url('/'))
def post(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) # Cleanup any old movies that have timed out from all users self.cleanup() filename = self.request.headers['Content-Disposition'] filename = re.search('^attachment; filename=\"([^\"]*)\"$', filename).groups()[0] # Get what byte range we are dealing with byteRange = self.request.headers['Content-Range'] matches = re.search('^bytes ([^\-]*)\-([^\/]*)\/(.*)$', byteRange) start = long(matches.group(1)) end = long(matches.group(2)) total = long(matches.group(3)) # Get any location information geoAddress = None if self.request.get('geoAddress') != '': geoAddress = self.request.get('geoAddress') # Delete old completed entries that match this filename query = Movie.gql('WHERE filename = :1 AND owner = :2', filename, user) m = None if query.count() > 0: m = query[0] if m.length != None and m.bytes_uploaded != None and m.length == m.bytes_uploaded: db.delete(query) m = Movie(owner=user, filename=filename) # Get old partially uploaded data already saved query = Movie.gql('WHERE filename = :1 AND owner = :2 LIMIT 1', filename, user) if query.count() == 1: m = query[0] # Will uploading this full file put the user over their quota? quotaUsed = total for entry in Movie.gql('WHERE owner = :1', user): if entry.filename != filename: quotaUsed += entry.length if quotaUsed >= self.TOTAL_QUOTA: self.error(413) # 413 = Request Too Large return # If we are just starting, create an entry; else if # there is nothing in the database and we _aren't_ # the first range chunk, return an error if m == None and start == 0: m = Movie(owner=user, filename=filename) elif m == None and start > 0: self.error(500) return # If there is something in the db, but our chunk is earlier than that # delete what is in the db if m != None and m.bytes_uploaded != 0 and start < m.bytes_uploaded: m.delete() m = Movie(owner=user, filename=filename) # Update Movie with new range and geographic information if m.blob != None: m.blob = db.Blob(m.blob + self.request.body) else: m.blob = db.Blob(self.request.body) m.length = total m.bytes_uploaded = end + 1 m.geoAddress = geoAddress if m.bytes_uploaded == m.length: m.uploaded = True m.put() # Look at our total length so far for this file; if its greater than # ~20 megabytes reject and delete this movie if m.bytes_uploaded > self.MAX_FILE_SIZE: m.delete() self.error(413) # 413 = Request Too Large return self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('200 OK')
def get(self): login_template = the_jinja_env.get_template('templates/login.html') the_variable_dict = {"login_url": users.create_login_url('/')} self.response.write(login_template.render(the_variable_dict))
def get_user(page): user = users.get_current_user() # used for online use # user = users.User("*****@*****.**") # only used for local server if user: return user page.redirect(users.create_login_url(page.request.uri)) return None
def build_url(self, request): from google.appengine.api import users url = users.create_login_url(redirect_to) return url
def get(self): self.response.headers['Content-Type'] = 'text/html' # pull the current user from the Request user = users.get_current_user() tb_list = [] tb_id_list = [] tb_userslist = [] invited_list = [] user = users.get_current_user() if user == None: url_string = 'login' url = users.create_login_url(self.request.uri) template_values = { 'url_string': url_string, 'url': url, 'login_url': users.create_login_url(self.request.uri) } template = JINJA_ENVIRONMENT.get_template('main.html') self.response.write(template.render(template_values)) return url_string = 'logout' url = users.create_logout_url(self.request.uri) id = user.user_id() myuser_key = ndb.Key('MyUser', id) myuser = myuser_key.get() print(myuser.tb_key) for n in myuser.tb_key: tboard = n.get() #if tboard == None: #tboard = TaskBoard() #tboard.put() logging.info("Debug message") print(n) logging.info("END") #tb_list.append(tboard) #tb_id_list.append(tboard.key.id()) query = MyUser.query( ndb.AND(MyUser.email_address != myuser.email_address)) #for n in query: #logging.info("START message") #print(n.email_address) #logging.info("End message") #for n in myuser.tb_key: #logging.info("Debug message") #print(n.get().tbd_name) #logging.info("END") #tb_userslist.append(n.get().tbd_name) #for n in myuser.invited_tb_list: #TaskBoard = n.get() #invited_list.append(TaskBoard) #invited_list.append(n.get().tbd_name) template_values = { 'myuser': myuser, 'user': user, #'tb_list' : tb_list, #'tboard' : tboard, 'url_string': url_string, 'url': url, } # pull the template file and ask jinja to render # it with the given template values template = JINJA_ENVIRONMENT.get_template('viewtaskboard.html') self.response.write(template.render(template_values))
def loginurl(self, url): return self.redirect(users.create_login_url(url))
def decorated_view(*args, **kwargs): if users.get_current_user(): if not users.is_current_user_admin(): abort(401) # Unauthorized return func(*args, **kwargs) return redirect(users.create_login_url(request.url))
def get(self): noDates = False errmsg = '' try: # get list of datetimes in DECENDING ORDER q = db.GqlQuery("SELECT DISTINCT tdate\ FROM systemData \ ORDER BY tdate DESC") # Container of unique dates dates = [] # add most recent date first to the list latest = datetime.date(q.get().tdate) dates.append(latest) # check if any of the following dates already exist # in our list. the list of datetimes will have multiple # entries # of the same date but we want to have a list of # unique dates for p in q: # create date object newDate = datetime.date(p.tdate) if not (newDate == latest): dates.append(newDate) latest = newDate except: noDates = True errmsg = 'There\'s no data to download. Come back ' \ 'another time' user_name = active_user() active = False if (user_name == '') else True login = users.create_login_url(self.request.uri) template_values = { 'user_name': user_name, 'active_user': active, 'login_url': login, 'dates': dates, 'noDates': noDates, 'errmsg': errmsg } template = JINJA_ENVIRONMENT.get_template('/pages/downloads.html') self.response.write(template.render(template_values)) # check if user submitted the download form down = cgi.escape(self.request.get('downloading')) if down == '1': # retrieve form arguments start = cgi.escape(self.request.get('startDate')) end = cgi.escape(self.request.get('endDate')) c = cgi.escape(self.request.get('checkbox')) #self.response.out.write( "1389979974") buf = self.fetch_data(c, start, end) # write download content into a buffer size = 56 # clear all data written to the output stream self.response.clear() # set HTTP headers to notify server of download self.response.headers["Content-Type"] = "text/csv" self.response.headers["Cache-Control"] = "no-cache" self.response.headers[ "Content-Disposition"] = "attachment; filename=kioskData.csv" self.response.headers["Content-Transfer-Encoding"] = "binary" self.response.headers["Pragma"] = "no-cache" self.response.write(buf) else: logging.info("No download\n")
def get(self): if users.get_current_user() is None: self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('ok\n') else: self.redirect(users.create_login_url('/logout'))
def get(self, request): index = reverse('index') url = users.create_login_url(index) return HttpResponseRedirect(url)
def get(self): login_url = users.create_login_url("/") params = {"login_url": login_url} return self.render_template("login.html", params=params)
def decorated_view(*args, **kwargs): if not users.get_current_user(): return redirect(users.create_login_url(request.url)) return func(*args, **kwargs)
def get(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) else: self.redirect('/')
def create_login_url(slug): """Creates a login url.""" return users.create_login_url(slug)
def get(self): self.redirect(users.create_login_url())
def signin_google(): save_request_params() google_url = users.create_login_url(flask.url_for('google_authorized')) return flask.redirect(google_url)
def get(self, stock_symbol): #make symbol all caps stock_symbol = stock_symbol.upper() # Checks for active Google account session user = users.get_current_user() #Only commit to ndb if we need to need_to_commit = False #Do we have a loged in user if user: #Get the users list of favorite stocks up = UserProfile.query(UserProfile.user_id == str(user.user_id())) # If new user, make profile if up.count() == 0: UserProfile(nickname=str(user.nickname()), email=str(user.email()), user_id=str(user.user_id()), federated_identity=str(user.federated_identity()), federated_provider=str(user.federated_provider()), favorite_list=[]).put() up = UserProfile.query( UserProfile.user_id == str(user.user_id())) need_to_commit = True else: for u in up: #Update last login date u.last_login_date = datetime.now() #update user email if changed if user.email != u.email: u.email = str(user.email()) need_to_commit = True #optinal:Remove the stock if its in the list, otherwise add it for u in up: if stock_symbol != '': need_to_commit = True if stock_symbol in u.favorite_list: u.favorite_list.remove(stock_symbol) else: u.favorite_list.append(stock_symbol) #commit the changes if need_to_commit: for u in up: u.put() #return to where the user was if stock_symbol != '': try: self.redirect(self.request.referer) except: self.redirect('./') #no user else: #A non user tried to favorite something, lets log them in so they get the action still after login if stock_symbol != '': self.redirect(users.create_login_url(self.request.uri)) #Form the symbol list to query queryList = [] if user: for u in up: for item in u.favorite_list: queryList.append(item) #Get the time, make a string of format: #Tue, Jan 6, 2014, 12:00AM EST - US MARKETS CLOSED now = datetime.now(tz=timezone('US/Eastern')) #Construct the EST time for the top of page if ((now.time() >= time(9, 30) and now.time() <= time(16, 30)) and (now.weekday() <= 4)): timeString = "{0:s} EST - US Markets Are Open".format( now.strftime("%a, %b %d %Y, %I:%M%p")) else: timeString = "{0:s} EST - US Markets Are Closed".format( now.strftime("%a, %b %d %Y, %I:%M%p")) # stockList = Forecast.query(Forecast.symbol.IN(queryList)).order( Forecast.rank) #prevent empty query from causing crashes if len(queryList) == 0: stockList = [] #Get computed values if len(queryList) != 0: computedCloseValues = np.zeros((stockList.count(), 2), float) else: computedCloseValues = np.zeros((0, 2), float) i = 0 if len(queryList) != 0: for stock in stockList: #computedCloseValues[i][0] = stock.forecastedPrice-stock.currentPrice #computedCloseValues[i][1] = (stock.forecastedPrice-stock.currentPrice)/abs(stock.currentPrice)*100.0 computedCloseValues[i][ 0] = stock.closePredPrice[-1] - stock.closePriceHistory[-1] computedCloseValues[i][1] = ( stock.closePredPrice[-1] - stock.closePriceHistory[-1] ) / abs(stock.closePriceHistory[-1]) * 100.0 i += 1 #Init items using info from forecast, just use the first item dayOfForecast = now.strftime("%A, %B %d %Y") dof = now #if stockList.count() > 0: for stock in stockList: dayOfForecast = stock.date.strftime("%A, %B %d %Y") #dof = forecast.date break #Form the login/logout url and a name to id the state in jinja2 if 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 = { 'stock_list': stockList, 'computed_values': computedCloseValues, #'forecast_count':forecastCount, 'timeStr': timeString, 'dayOfForecast': dayOfForecast, 'url': url, 'url_linktext': url_linktext, } #Show mystock page template = JINJA_ENVIRONMENT.get_template('mystocks.html') self.response.write(template.render(template_values))
def get(self, resource=''): admin_url = users.create_login_url("/blog") self.redirect(admin_url)
def signin(ruri): try: from google.appengine.api import users return users.create_login_url(ruri) except: return None
def get(self): #Get total nubmer of predictions #global_stat = stats.GlobalStat.query().get() #forecastCount = global_stat.count #Get the time, make a string of format: #Tue, Jan 6, 2014, 12:00AM EST - US MARKETS CLOSED now = datetime.now(tz=timezone('US/Eastern')) #Construct the EST time for the top of page if ((now.time() >= time(9, 30) and now.time() <= time(16, 30)) and (now.weekday() <= 4)): timeString = "{0:s} EST - US Markets Are Open".format( now.strftime("%a, %b %d %Y, %I:%M%p")) else: timeString = "{0:s} EST - US Markets Are Closed".format( now.strftime("%a, %b %d %Y, %I:%M%p")) # stockList = StockList.query(StockList.rank.IN(list(np.arange(1, 26)))) computedCloseValues = np.zeros((stockList.count(), 3), float) #createa binary list of stock list vs user favorite list user = users.get_current_user() if user: up = UserProfile.query(UserProfile.user_id == str(user.user_id())) favBinary = [] for u in up: for stock in stockList: if stock.symbol in u.favorite_list: favBinary.append(1) else: favBinary.append(0) break #case where user exists(like admin) but no profile yet if stockList.count() != len(favBinary): favBinary = np.zeros((stockList.count(), )) else: favBinary = np.zeros((stockList.count(), )) # i = 0 for stock in stockList: computedCloseValues[i][ 0] = stock.forecastedPrice - stock.currentPrice computedCloseValues[i][1] = (stock.forecastedPrice - stock.currentPrice) / abs( stock.currentPrice) * 100.0 computedCloseValues[i][2] = favBinary[i] i += 1 #Init items using info from forecast, just use the first item dayOfForecast = now.strftime("%A, %B %d %Y") dof = now for stock in stockList: dayOfForecast = stock.date.strftime("%A, %B %d %Y") #dof = forecast.date break 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 = 'Sign Up for Updates' template_values = { 'stock_list': stockList, 'computed_values': computedCloseValues, #'forecast_count':forecastCount, 'timeStr': timeString, 'dayOfForecast': dayOfForecast, 'url': url, 'url_linktext': url_linktext, } template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values))
def createloginurl(): return users.create_login_url('/')
def get(self, stock_symbol): #Request the market and prepare its data for plotting #Reqest the stock and prepare its data for plotting #Get total nubmer of predictions #global_stat = stats.GlobalStat.query().get() #forecastCount = global_stat.count if stock_symbol == '': symbol_search = self.request.get("symbol_search") #Get the time, make a string of format: #Tue, Jan 6, 2014, 12:00AM EST - US MARKETS CLOSED now = datetime.now(tz=timezone('US/Eastern')) #Construct the EST time for the top of page if ((now.time() >= time(9, 30) and now.time() <= time(16, 30)) and (now.weekday() <= 4)): timeString = "{0:s} EST - US Markets Are Open".format( now.strftime("%a, %b %d %Y, %I:%M%p")) else: timeString = "{0:s} EST - US Markets Are Closed".format( now.strftime("%a, %b %d %Y, %I:%M%p")) # #query to get the top 10 stocks for newest forecast round #stockList = Forecast.query(Forecast.rank.IN(list(np.arange(1,11)))) stockList = Forecast.query(Forecast.symbol == stock_symbol.upper()) #createa binary list of stock list vs user favorite list user = users.get_current_user() if user: up = UserProfile.query(UserProfile.user_id == str(user.user_id())) favBinary = [] for u in up: for stock in stockList: if stock.symbol in u.favorite_list: favBinary.append(1) else: favBinary.append(0) break #case where user exists(like admin) but no profile yet if stockList.count() != len(favBinary): favBinary = np.zeros((stockList.count(), )) else: favBinary = np.zeros((stockList.count(), )) # #3d array of the candlestick plots # stock, list of L, list of O, list of C, list of H, list of V #stocks, history, category forecastPlotData = np.zeros((stockList.count(), 10, 6), object) #3d array of the validation plots #Stocks, history, category validationPlotData = [] #3d array of computed values nstock, 10 computedValued = np.zeros((stockList.count(), 11), float) #Init items using info from forecast, just use the first item dayOfForecast = now.strftime("%A, %B %d %Y") dof = now for forecast in stockList: validationPlotData = np.zeros( (stockList.count(), len(forecast.lowPriceHistory), 10), object) dayOfForecast = forecast.date.strftime("%A, %B %d %Y") dof = forecast.date break i = 0 for forecast in stockList: forecastPlotData[i, :, 0] = [ x.encode('utf-8').replace("'", "") for x in forecast.dayOfPred[-10:] ] #forecastPlotData[i,-1,0] = str(forecast.dayOfPred[-1]).replace("'","")#.encode('utf-8')#.replace(''','') forecastPlotData[i, :-1, 1] = forecast.lowPriceHistory[-9:] forecastPlotData[i, -1, 1] = forecast.lowPredPrice[-1] forecastPlotData[i, :-1, 2] = forecast.openPriceHistory[-9:] forecastPlotData[i, -1, 2] = forecast.openPredPrice[-1] forecastPlotData[i, :-1, 3] = forecast.closePriceHistory[-9:] forecastPlotData[i, -1, 3] = forecast.closePredPrice[-1] forecastPlotData[i, :-1, 4] = forecast.highPriceHistory[-9:] forecastPlotData[i, -1, 4] = forecast.highPredPrice[-1] forecastPlotData[i, :-1, 5] = forecast.volumeHistory[-9:] forecastPlotData[i, -1, 5] = forecast.volumePred[-1] validationPlotData[i, :, 0] = forecast.openPriceHistory validationPlotData[i, :, 1] = forecast.openPredPrice[:-1] validationPlotData[i, :, 2] = forecast.closePriceHistory validationPlotData[i, :, 3] = forecast.closePredPrice[:-1] validationPlotData[i, :, 4] = forecast.highPriceHistory validationPlotData[i, :, 5] = forecast.highPredPrice[:-1] validationPlotData[i, :, 6] = forecast.lowPriceHistory validationPlotData[i, :, 7] = forecast.lowPredPrice[:-1] validationPlotData[i, :, 8] = forecast.volumeHistory validationPlotData[i, :, 9] = forecast.volumePred[:-1] computedValued[i][ 0] = forecast.openPredPrice[-1] - forecast.openPriceHistory[-1] computedValued[i][1] = (forecast.openPredPrice[-1] - forecast.openPriceHistory[-1]) / abs( forecast.openPriceHistory[-1]) * 100.0 computedValued[i][2] = forecast.closePredPrice[ -1] - forecast.closePriceHistory[-1] computedValued[i][3] = (forecast.closePredPrice[-1] - forecast.closePriceHistory[-1]) / abs( forecast.closePriceHistory[-1]) * 100.0 computedValued[i][ 4] = forecast.highPredPrice[-1] - forecast.highPriceHistory[-1] computedValued[i][5] = (forecast.highPredPrice[-1] - forecast.highPriceHistory[-1]) / abs( forecast.highPriceHistory[-1]) * 100.0 computedValued[i][ 6] = forecast.lowPredPrice[-1] - forecast.lowPriceHistory[-1] computedValued[i][7] = (forecast.lowPredPrice[-1] - forecast.lowPriceHistory[-1]) / abs( forecast.lowPriceHistory[-1]) * 100.0 computedValued[i][ 8] = forecast.volumePred[-1] - forecast.volumeHistory[-1] computedValued[i][9] = (forecast.volumePred[-1] - forecast.volumeHistory[-1]) / abs( forecast.volumeHistory[-1]) * 100.0 computedValued[i][10] = favBinary[i] #Count for filling arrays i += 1 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 = 'Sign Up for Updates' template_values = { 'stock_list': stockList, 'forecast_data': forecastPlotData, 'validation_data': validationPlotData, 'computed_values': computedValued, #'forecast_count':forecastCount, 'timeStr': timeString, 'dayOfForecast': dayOfForecast, 'url': url, 'url_linktext': url_linktext, } template = JINJA_ENVIRONMENT.get_template('symbol.html') self.response.write(template.render(template_values))