def create_plan(): form = forms.NewPlanForm(request.form) if not form.validate(): flash("Error, all fields are required") return render_template("new_plan.html") if form.end_date.data < form.start_date.data: flash("Error, end date can't be earlier than start date") return render_template("new_plan.html") url = generate_hash() plan = Plan(name=form.name.data, start_date=form.start_date.data, end_date=form.end_date.data, hashed_url=url) if len(plan.date_range()) > 14: flash("Error, this trip is too log. You can choose maximum 14 days") return render_template("new_plan.html") current_user.plans.append(plan) for day in plan.date_range(): timeline = Timeline(date=day) plan.timelines.append(timeline) db.session.commit() db.session.refresh(plan) return redirect(url_for("view_plan", id=plan.id))
def get(self, member_id=""): self.member_allowd(member_id) tnodes = Timeline.get_nodes(self.current_user, member_id) timenodes = [] for item in tnodes: timenodes.append(item['addday']) result = {"data": timenodes} self.finish(result)
def post(timeline_id=None): if timeline_id is None: user = current_user params = request.json name = params.get('name') timeline = Timeline(title=name, owner=user) db.session.add(timeline) db.session.commit() return timeline_schema.dump(timeline)
def put(self, point_id): note = self.get_argument("note", "") if self.request.files and 'photo' in self.request.files: file_metas = self.request.files['photo'][0] filename = rand_name(file_metas['filename']) save(filename, file_metas['body']) result = {'timeline_id': Timeline.modify(point_id, filename, note)} self.finish(result) else: raise HTTPAPIError(400)
def parse_card(self, card): """ :param card: a dict :return: """ mblog = card['mblog'] reset_dict(self.timeline) # initialization self.timeline['uid'] = self.parse_uid(mblog) if self.timeline['uid'] == -1: return -1 # No access to this post self.timeline['mid'] = self.parse_mid(mblog) self.timeline['encrypted_mid'] = self.parse_encrypted_mid(mblog) self.timeline['screen_name'] = self.parse_screen_name(mblog) self.timeline['text'] = self.parse_text(mblog) self.timeline['app_source'] = self.parse_app_source(mblog) self.timeline['created_at'] = self.parse_created_at(mblog) self.timeline['attitudes'] = self.parse_attitudes(mblog) self.timeline['comments'] = self.parse_comments(mblog) self.timeline['reposts'] = self.parse_reposts(mblog) self.timeline['pic_urls'] = self.parse_pic_urls(mblog) self.timeline['json'] = self.parse_json(mblog) self.timeline['timestamp'] = datetime.now() self.timeline['omid'] = self.parse_omid(mblog) if self.timeline['omid'] != 0: self.parse_origin_timeline(mblog) self.timeline['text'] = u'%s //@%s:%s' % ( self.timeline['text'], self.origin_timeline['screen_name'], self.origin_timeline['text']) self.timeline['pic_urls'] = u'%s, %s' % ( self.timeline['pic_urls'], self.origin_timeline['pic_urls']) self.timeline['pic_urls'].strip(u', ') self.timelines.append(Timeline(**self.origin_timeline)) self.timelines.append(Timeline(**self.timeline)) return 0
def get(self, member_id=""): self.member_allowd(member_id) month = self.get_argument("month", None) tlines = Timeline.get(self.current_user, member_id, month) timelines = {} days = [] for item in tlines: if not timelines.has_key(item['addday']): timelines[item['addday']] = [] days.append(item['addday']) timelines[item['addday']].append(item) result = {"data": timelines, "days": ",".join(days), "keys": days} self.finish(result)
def submit_metric(): """ Submits the metric data for a specific computer if the computer doesn't exist it is created. """ gson = json.loads(request.get_json()) new_point = DataPoint(computer_name=gson["computer_name"], cpu_percentage=gson["cpu_percentage"], memory_percentage=gson["memory_percentage"], timestamp=gson["timestamp"]) with lock: if not instances.get(new_point.computer_name): instances[new_point.computer_name] = Timeline( maxsize=int(os.environ.get("COLLECTOR_BUFFER_SIZE"))) instances[new_point.computer_name].append(new_point) return Response(status=200)
def post(self, member_id): self.member_allowd(member_id) height = self.get_argument("height", "") weight = self.get_argument("weight", "") note = utf8(self.get_argument("note", "")) if height or weight: tday = format_time("%Y%m%d") tdaydata = Pointdata.get_by_day(member_id, tday) if tdaydata: Pointdata.modify(tdaydata['pid'], height, weight, note) result = {'point_id': tdaydata['pid']} else: result = {'point_id': Pointdata.creat(member_id, height, weight, note, tday)} if self.request.files and 'photo' in self.request.files: file_metas = self.request.files['photo'][0] filename = "%s.jpg" % rand_name(file_metas['filename']) save(filename, file_metas['body']) filename = "http://dstore-dstor.stor.sinaapp.com/%s" % filename result['timeline_id'] = Timeline.creat(self.current_user, member_id, filename, note, tday) self.finish(result) else: raise HTTPAPIError(400)
def submitArticles(articles): today = datetime.datetime.now().date() article_list = Timeline.query.filter_by(articles_date=today).first() if article_list is None: timeline = Timeline(today) db.session.add(timeline) db.session.commit() for x in articles: dup_article = Article.query.filter_by(url=x["url"], title=x["name"]).first() if dup_article is None: try: print(x) category = "World" img_url = None img_height = None img_width = None try: img_url = x["image"]["thumbnail"]["contentUrl"] img_height=x["image"]["thumbnail"]["height"] img_width=x["image"]["thumbnail"]["width"] except KeyError: print("Image not found") try: category = x["category"] except KeyError: print("Category not found") article = Article(url=x["url"], title=x["name"], city=x["city"], category=category, description=x["description"], publisher=x["provider"][0]["name"], country=x["country"], latitude=x["latitude"], longitude=x["longitude"], img_url=img_url, img_height=img_height, img_width=img_width, article_date=today) db.session.add(article) db.session.commit() except KeyError: print("Key not found")
def ensure_content(user_id): """ Checks to see whether the user has any content and if not, adds some to make sure they have >= 10 """ activity_collection = get_activity_collection() timeline_col = get_timeline_collection() activities = Timeline.get_visible_activities(user_id) size = len(activities) user = User.get_by_id(user_id, extra_fields = ['gender']) interests = user.get('interests', []) if user.get('gender') == 'male': default_interests = ['touch', 'cycling', 'gymsession', 'bbq', 'indoorfootball', 'squash', 'poker', 'surf', 'rockclimbing', 'drinksatmine', 'beachcricket'] else: #Female default_interests = ['beachtime', 'champagnebreakfast', 'freetradecoffee', 'byodinner', 'crossfit', 'easyjog', 'movieday', 'tennis', 'drinksatmine', 'missionbaymission'] shuffle(default_interests) prefixes = ['Whos keen for some #%s tomorrow?', 'Whos keen.to #%s tomorrow?', 'Im feeling like #%s today, whos keen?', 'Whos up for #%s today?', 'keen.to #%s today?'] raw_friends = FriendStore.get_friends_raw(user_id) suggesters = User.get_by_ids_type(ids = list(raw_friends.iterkeys()), user_type=User.ACTIVE) friend_interests = [] for friend in suggesters: friend_interests.extend(friend.get('interests')) if len(suggesters) + size < 10: raw_fof_ids = FriendOfFriendStore.get_fof_ids_raw(user_id) more_suggesters = User.get_by_ids_type(ids = list(raw_fof_ids), user_type=User.ACTIVE) suggesters.extend(more_suggesters) while size < 10: if len(suggesters) == 0: break shuffle(prefixes) #We want to add some more if len(interests) >= 1: interest = interests.pop() elif len(friend_interests) >= 1: interest = friend_interests.pop() elif len(default_interests) >= 1: interest = default_interests.pop() prefix = prefixes[0] text = prefix % interest raw_suggester = suggesters.pop() #Add the activity into activities activity = { "suggester_id" : raw_suggester.get('_id'), "text" : text, "keyword" : interest, "keens" : [{ "user_id" : raw_suggester.get('_id'), "fb_username" : '', "first_name" : raw_suggester.get('first_name'), "last_name" : raw_suggester.get('last_name'), "network" : raw_suggester.get('network'), "confirmed" : True, "user_type" : User.ACTIVE }], 'invited' : [], "status" : Activity.EXPIRED, "visibility" : '', "created_on" : datetime.datetime.now() - datetime.timedelta(days = randint(2,7)), } activity_id = str(activity_collection.insert(activity)) #Add it to the users timeline activity_timeline_dict = { "suggester_id" : raw_suggester.get('_id'), "keyword" : interest, "activity_id" : activity_id, #This has to be string to consistency "activity_hash" : '', "confirmed" : False, "visibility" : '', "keen" : False, "degree" : None } timeline_col.update({"user_id" : user_id}, #Match criteria {"$push": { "visible_activities" : activity_timeline_dict } }) size += 1 return True
def delete(self, timeline_ids): Timeline.delete(self.current_user, timeline_ids) self.finish()
def rpc_get_csv_timelines(self, project, typ="general/aggregate", tag=None): return Timeline.get_timeline(project.ph_id, slashify(project.ph_id, "timeline", typ), tag)