def test_churn_rage_per_time(self): ''' test method Dashboard.churn_rage_per_time() ''' # Empty database has no users self.failUnlessEqual(Dashboard.churn_rage_per_time(), '0 / 0 / 0') # create user which left 20 days before u = self.getUser() now = datetime.datetime.now() date = now - datetime.timedelta(days=20) s = Subscription(owner=u, monthly_fee=0) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.churn_rage_per_time(), '0 / 0 / 1') # create user which left 3 days before date = now - datetime.timedelta(days=3) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.churn_rage_per_time(), '0 / 1 / 1') # create user which left today s.date_cancelled = now s.date_deleted = now s.save() self.failUnlessEqual(Dashboard.churn_rage_per_time(), '1 / 1 / 1') # Delete all data u.delete() self.failUnlessEqual(Dashboard.churn_rage_per_time(), '0 / 0 / 0')
def adddashboard(request): if not request.is_ajax() or request.method != 'POST': #return method not allowed responsedata = { 'success': False, 'message': 'Non-ajax requests not allowed.' } return HttpResponse(json.dumps(responsedata), status=405) params = json.loads(request.body) try: dashboard = Dashboard(user=request.user, name=params['name']) dashboard.save() except (KeyError, ValueError) as e: print e responsedata = {'success': False, 'message': 'Internal server error.'} return HttpResponse(json.dumps(responsedata), status=500) responsedata = { 'success': True, 'message': 'Dashboard created.', 'uid': str(dashboard.uid) } return HttpResponse(json.dumps(responsedata))
def delete(): # username = session.get('username') session_token = session.get("session_token") if not session_token: print "session_token not exists!" return None # app_name = app_name # app_id = request.args.get('app_id') # print 'the app_id of the app is: %s' %(str(app_id)) user = Developer() user.session_token = session_token # print 'The form is: %s' %(str(request.form)) # _xsrf = request.form.get('_xsrf') app_id = request.form.get("app_id") dashboard = Dashboard() dashboard.app_id = app_id res = user.delete_app(app_id=app_id, kind=None) if res == 0: response_json = {"delete": "success"} return jsonify(response_json) else: response_json = {"delete": "failed"} return jsonify(response_json)
def test_average_files(self): ''' test method Dashboard.average_files() ''' # Empty database has no files self.failUnlessEqual(Dashboard.average_files(), '0.0') # create 1 user and 1 file u = self.getUser() s = self.getSubscription(u) f = self.getFile(s) self.failUnlessEqual(Dashboard.average_files(), '1.0') # create second user u2 = self.getUser() s2 = self.getSubscription(u2) self.failUnlessEqual(Dashboard.average_files(), '0.5') # create file for second user f2 = self.getFile(s2) self.failUnlessEqual(Dashboard.average_files(), '1.0') # delete all users u.delete() u2.delete() self.failUnlessEqual(Dashboard.average_files(), '0.0')
def test_churn_acquisition(self): ''' test method Dashboard.churn_acquisition() ''' # Empty database has no users self.failUnlessEqual(Dashboard.churn_acquisition(), '0% / 0% / 0%') # create user which left today date = datetime.datetime.now() u = self.getUser() s = Subscription(owner=u, monthly_fee=0) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.churn_acquisition(), '100% / 100% / 100%') # create user which left 3 days before date -= datetime.timedelta(days=3) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.churn_acquisition(), '0% / 100% / 100%') # create user which left 23 days before date -= datetime.timedelta(days=20) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.churn_acquisition(), '0% / 0% / 100%') # Delete all data u.delete() self.failUnlessEqual(Dashboard.churn_acquisition(), '0% / 0% / 0%')
def test_not_access_users(self): ''' test method Dashboard.not_access_users() ''' # Empty database has no users self.failUnlessEqual(Dashboard.not_access_users(), '0%(0) / 0%(0)') now = datetime.datetime.now() # create 1 user with last login 3 days before u = User.objects.create_user('not_access', '*****@*****.**', 'testpassword') u.last_login = now - datetime.timedelta(days=3) u.save() self.failUnlessEqual(Dashboard.not_access_users(), '100%(1) / 100%(1)') # create second user with last login 20 days before u2 = User.objects.create_user('not_access2', '*****@*****.**', 'testpassword') u2.last_login = now - datetime.timedelta(days=20) u2.save() self.failUnlessEqual(Dashboard.not_access_users(), '50%(1) / 100%(2)') # delete second user u.delete() self.failUnlessEqual(Dashboard.not_access_users(), '0%(0) / 100%(1)') #delete all users u2.delete() self.failUnlessEqual(Dashboard.not_access_users(), '0%(0) / 0%(0)')
def test_average_lifetime_in_months(self): ''' test method Dashboard.average_lifetime_in_months() ''' # Empty database has no users self.failUnlessEqual(Dashboard.average_lifetime_in_months(), '0.0') # Create user with date_created = now u = self.getUser() s = self.getSubscription(u) self.failUnlessEqual(Dashboard.average_lifetime_in_months(), '0.0') # change date_created = -1 month s.date_created -= datetime.timedelta(days=30) s.save() self.failUnlessEqual(Dashboard.average_lifetime_in_months(), '1.0') # Create user with date_created = -3 months u2 = self.getUser() s2 = self.getSubscription(u2) s2.date_created -= datetime.timedelta(days=90) s2.save() self.failUnlessEqual(Dashboard.average_lifetime_in_months(), '2.0') # delete all data u.delete() u2.delete() self.failUnlessEqual(Dashboard.average_lifetime_in_months(), '0.0')
def test_average_lifetime_in_dollars(self): ''' test method Dashboard.average_lifetime_in_dollars() ''' # Empty database has no users self.failUnlessEqual(Dashboard.average_lifetime_in_dollars(), '0.00') # create receipt with amount = 10 u = self.getUser() s = self.getSubscription(u) r = self.getReceipt(s, decimal.Decimal(10)) self.failUnlessEqual(Dashboard.average_lifetime_in_dollars(), '10.00') # create receipt with amount = 20 u2 = self.getUser() s2 = self.getSubscription(u2) r2 = self.getReceipt(s2, decimal.Decimal(20)) self.failUnlessEqual(Dashboard.average_lifetime_in_dollars(), '15.00') # delete receipt with amount = 10 r.delete() self.failUnlessEqual(Dashboard.average_lifetime_in_dollars(), '20.00') # remove all data r2.delete() u.delete() u2.delete() self.failUnlessEqual(Dashboard.average_lifetime_in_dollars(), '0.00')
def admin_functions(request): usernames = [] dashboards = [] userids = [] dashprivfound = [] if (not request.user.is_superuser): #remove before production... add setadminuser as parameter and use username as value if request.method=="GET" and request.GET.get("setadminuser") is not None: set_site_admin(request.GET.get("setadminuser")) #template = loader.get_template('Authentication/Login.html') #context = RequestContext(request, {}) return redirect(settings.BASE_URL)#HttpResponse(template.render(context)) actionselected = "user" if request.method=="POST" and request.POST['adminaction']== "delete": rmvuser = request.POST['username'] delete_user(rmvuser) usernames = retrieve_all_usernames() elif request.method=="POST" and request.POST['adminaction']== "viewactiveusers": usernames = retrieve_active_usernames() elif request.method=="POST" and request.POST['adminaction']== "viewusers": usernames = retrieve_all_usernames() elif request.method=="POST" and request.POST['adminaction'] == "viewsiteadmins": usernames = view_site_admins() elif request.method=="POST" and request.POST['adminaction'] == "setadmin": set_site_admin(request.POST['username']) usernames = view_site_admins() elif request.method=="POST" and request.POST['adminaction'] == "removeadmin": remove_site_admin(request.POST['username']) usernames = view_site_admins() elif request.method=="POST" and request.POST['adminaction'] == "viewalldashboards": actionselected = "dashboard" dash_objs = Dashboard.objects() for dash in dash_objs: dashboards.append(dash.title) print(dashboards) elif request.method=="POST" and request.POST['adminaction'] == "deletedashboard": actionselected = "dashboard" delete_dashboard(request.POST['dashboard']) dash_objs = Dashboard.objects() for dash in dash_objs: dashboards.append(dash.title) elif request.method=="POST" and request.POST['adminaction'] == "viewuserdashboards": actionselected = "dashboard" dashprivfound = Dashboard_Permission.objects.filter(user=request.POST['dashusername']) elif request.method=="POST": print(request.POST['adminaction']) print(actionselected) template = loader.get_template('Administration/adminfunctions.html') context = RequestContext(request, {'ursfound': usernames , 'dashboardsfound': dashboards, 'actionselected': actionselected, 'dashprivfound':dashprivfound }) return HttpResponse(template.render(context))
def list(request): #print "found list" #print "Request: " + str(request) #print "User logged in: " + str(request.user.is_authenticated())#str(auth.user_logged_in) messages = [] error_messages = [] if (not request.user.is_authenticated()): return redirect(settings.BASE_URL) username = request.user.username #should check to make sure dashboard doesn't already exist if request.method == "POST": try: if request.POST[ "create_dashboard_submit"] == "Create Chat Dashboard": title = request.POST['title'].strip() dashboard = Dashboard(title=title, creator=username) permission = Dashboard_Permission( dashboard_title=title, user=username, privilege=Dashboard_Permissions.ADMIN) to_save = True for dash in Dashboard.objects: if dash.title == title: to_save = False if to_save: dashboard.save() permission.save() print "Created Dashboard: " + title else: messages.append( "Cannot create dashboard - the dashboard already exists" ) except: try: if request.POST["invite_user_submit"] == "Invite User": invite_user(request.POST["inviteemail"], username) except: pass user_dashboards = None try: user_dashboards = Dashboard_Permission.objects.filter(user=username) except: messages.append("You are not a user on any Dashboards.") all_dashboards = Dashboard.objects() template = loader.get_template('list.html') context = RequestContext( request, { 'all_dashboards': all_dashboards, 'user_dashboards': user_dashboards, 'messages': messages, 'error_messages': error_messages }) return HttpResponse(template.render(context))
def setUp(self): super(DashboardsViewTest, self).setUp() self.dash1 = Dashboard(widgets='{"test":"widget"}', owner=self.existing_user) self.dash1.save() self.dash2 = Dashboard(widgets='{"test2":"widget2"}', owner=self.existing_user) self.dash2.save() self.factory = RequestFactory()
def test_total_users(self): ''' test method Dashboard.total_users() ''' # Empty database has no users self.failUnlessEqual(Dashboard.total_users(), 0) u = self.getUser() self.failUnlessEqual(Dashboard.total_users(), 1) u.delete() self.failUnlessEqual(Dashboard.total_users(), 0)
def dashboard(): username = session.get("username") session_token = session.get("session_token") print username print "session_token+", session_token # if not session_token: # return redirect(url_for('index')) # change app_name & app_id as demo for test app_name = request.args.get("app_name") app_id = request.args.get("app_id") app_id = "demo55bc5d8e00b0cb9c40dec37b" print "the app_id of the app is: %s" % (str(app_id)) user = Developer() user.session_token = session_token if user.get_all_application(): all_application_dict = user.all_application_dict else: print "no application exists" all_application_dict = {} print "all_application_dict is : %s" % (str(all_application_dict)) if app_name and app_id: del all_application_dict[app_name] else: app_name = all_application_dict.keys()[0] app_id = all_application_dict[app_name] del all_application_dict[app_name] dashboard = Dashboard() dashboard.app_id = app_id # 存到session中是为了在dash中使用 session["app_name"] = app_name session["app_id"] = app_id if request.method == "POST": is_xhr = True else: is_xhr = False dashboard_link = "/dashboard/" return render_template( "dashboard.html", is_xhr=is_xhr, dashboard_link=dashboard_link, route_link="dashboard", # sort according to ['16down', '16to35', '35to55', '55up'] # discard unknown data username=username, app_name=app_name, app_id=app_id, all_application_dict=all_application_dict, )
def list(request): #print "found list" #print "Request: " + str(request) #print "User logged in: " + str(request.user.is_authenticated())#str(auth.user_logged_in) messages = [] error_messages = [] if (not request.user.is_authenticated()): return redirect(settings.BASE_URL) username = request.user.username #should check to make sure dashboard doesn't already exist if request.method == "POST": try: if request.POST["create_dashboard_submit"] == "Create Chat Dashboard": title = request.POST['title'].strip() dashboard = Dashboard(title=title, creator=username) permission = Dashboard_Permission(dashboard_title=title, user=username, privilege=Dashboard_Permissions.ADMIN) to_save = True for dash in Dashboard.objects: if dash.title == title: to_save = False if to_save: dashboard.save() permission.save() print "Created Dashboard: " + title else: messages.append("Cannot create dashboard - the dashboard already exists") except: try: if request.POST["invite_user_submit"] == "Invite User": invite_user(request.POST["inviteemail"],username) except: pass user_dashboards = None try: user_dashboards = Dashboard_Permission.objects.filter(user=username) except: messages.append("You are not a user on any Dashboards.") all_dashboards = Dashboard.objects() template = loader.get_template('list.html') context = RequestContext(request, { 'all_dashboards': all_dashboards, 'user_dashboards': user_dashboards, 'messages': messages, 'error_messages': error_messages }) return HttpResponse(template.render(context))
def test_not_activate_users(self): ''' test method Dashboard.not_activate_users() ''' # Empty database has no users self.failUnlessEqual(Dashboard.not_activate_users(), 0) # create 1 not active user u = User.objects.create_user('test', '*****@*****.**', 'testpassword') u.is_active = 0 u.save() self.failUnlessEqual(Dashboard.not_activate_users(), 1) # Delete all data u.delete() self.failUnlessEqual(Dashboard.not_activate_users(), 0 )
def integration(): # print 'args: '+str(request.args) # print 'form: '+str(request.form) # app_id = request.form.get('app_id') # app_name = session.get('app_name') app_id = session.get("app_id") dashboard = Dashboard() dashboard.app_id = app_id app_key = dashboard.get_app_key() if not app_key: app_key = dashboard.get_demo_app_key() if not app_key: flash("App not exists") return render_template("console.html") return render_template("integration.html", app_id=app_id, app_key=app_key)
def demo(): username = session.get("username") session_token = session.get("session_token") if not session_token: return redirect(url_for("index")) user = Developer() user.session_token = session_token if user.get_all_demo_application(): all_demo_application_dict = user.all_demo_application_dict # 一旦上一步执行成功,会给user添加一个成员变量 all_demo_application_dict else: print "no demo application exists" all_demo_application_dict = {} print "all_demo_application_dict is : %s" % (str(all_demo_application_dict)) if DEMO_APP_NAME in all_demo_application_dict.keys(): app_name = DEMO_APP_NAME app_id = all_demo_application_dict[app_name] else: "Demo not exists" app_name = None app_id = None session["app_name"] = app_name session["app_id"] = app_id # del all_demo_application_dict[app_name] print "app_name is %s and app_id is %s" % (str(app_name), str(app_id)) dashboard = Dashboard() dashboard.app_id = app_id # all_app_event = 1 if request.method == "POST": is_xhr = True else: is_xhr = False dashboard_link = "/demo" return render_template( "demo.html", is_xhr=is_xhr, dashboard_link=dashboard_link, route_link="dashboard", # sort according to ['16down', '16to35', '35to55', '55up'] # discard unknown data username=username, app_name=app_name, app_id=app_id, all_application_dict={}, )
def ajax_dashboard(param): # username = session.get('username') session_token = session.get("session_token") if not session_token: print "session_token not exists!" return None # app_name = app_name # app_id = request.args.get('app_id') # print 'the app_id of the app is: %s' %(str(app_id)) user = Developer() user.session_token = session_token # print 'The form is: %s' %(str(request.form)) # print 'Param is: %s' %(str(param)) # _xsrf = request.form.get('_xsrf') app_id = request.form.get("app_id") dashboard = Dashboard() dashboard.app_id = app_id if param == "profile": category = request.form.get("category") print "before get_profile_option" option = dashboard.get_profile_option(category=category, kind=None) print "Option is: %s" % (str(option)) return jsonify(option) pass elif param == "path": category = request.form.get("category") option = dashboard.get_path_option(category=category, kind=None) return jsonify(option) pass elif param == "behavior": event_name = request.form.get("event") category = request.form.get("category") option = dashboard.get_event_option(event_name=event_name, category=category, kind=None) print "after get_event_option" print "Option is: %s" % (str(option)) return jsonify(option) pass else: return None pass
def post(self): data = request.get_json() user = Dashboard(**data) db.session.add(user) db.session.flush() id = user.id emit_object_creation({"name": dash.name, "type": "dashboard"}) db.session.commit() return {'id': id}, 201
def test_left_daily(self): ''' test method Dashboard.left_daily() ''' u = self.getUser() now = datetime.datetime.now() # Empty database has no users self.failUnlessEqual(Dashboard.left_daily(), 0) # create 1 user which left today s = Subscription(owner=u, monthly_fee=0) s.date_cancelled = now s.date_deleted = now s.save() self.failUnlessEqual(Dashboard.left_daily(), 1) # Delete all data u.delete() self.failUnlessEqual(Dashboard.left_monthly(), 0)
def settings(): print "args: " + str(request.args) print "form: " + str(request.form) # app_id = request.form.get('app_id') app_name = session.get("app_name") app_id = session.get("app_id") dashboard = Dashboard() dashboard.app_id = app_id app_key = dashboard.get_app_key() if not app_key: app_key = dashboard.get_demo_app_key() if not app_key: flash("App not exists") return render_template("console.html") if app_name == DEMO_APP_NAME: disabled = True else: disabled = False return render_template("settings.html", app_id=app_id, app_key=app_key, disabled=disabled)
def test_left_weekly(self): ''' test method Dashboard.left_weekly() ''' # Empty database has no users self.failUnlessEqual(Dashboard.left_weekly(), 0) # create 1 user which left 3 days before u = self.getUser() date = datetime.datetime.now() - datetime.timedelta(days=3) s = Subscription(owner=u, monthly_fee=0) s.date_cancelled = date s.date_deleted = date s.save() self.failUnlessEqual(Dashboard.left_weekly(), 1) # Delete all data u.delete() self.failUnlessEqual(Dashboard.left_monthly(), 0)
def get_dashboard_data(request): dash_data = json.loads(request.POST["data"]) print dash_data filename = dash_data["name"] + "_config.json" with open("media/" + filename, 'w') as conf: json.dump(dash_data, conf) Dashboard(name=dash_data["name"], config_file=filename).save() return HttpResponseRedirect(reverse("dashboard:list"))
def test_average_shares(self): ''' test method Dashboard.average_shares() ''' # Empty database has no shares self.failUnlessEqual(Dashboard.average_shares(), '0.0') # create 1 share for 1 sender u = self.getUser() sh = self.getShare(u) self.failUnlessEqual(Dashboard.average_shares(), '1.0') # create second user u2 = self.getUser() self.failUnlessEqual(Dashboard.average_shares(), '0.5') # create share for second user sh2 = self.getShare(u2) self.failUnlessEqual(Dashboard.average_shares(), '1.0') # delete all users u.delete() u2.delete() self.failUnlessEqual(Dashboard.average_shares(), '0.0')
def test_average_signups(self): ''' test method Dashboard.average_signups() ''' # Empty database has no signups self.failUnlessEqual(Dashboard.average_signups(), '0 / 0 / 0') u = self.getUser() # create subscription for today s = self.getSubscription(u) self.failUnlessEqual(Dashboard.average_signups(), '1 / 1 / 1') # change date_created 3 days ago for weekly s.date_created -= datetime.timedelta(days=3) s.save() self.failUnlessEqual(Dashboard.average_signups(), '0 / 1 / 1') # change date_created 23 days ago for monthly s.date_created -= datetime.timedelta(days=20) s.save() self.failUnlessEqual(Dashboard.average_signups(), '0 / 0 / 1') # Delete all data u.delete() self.failUnlessEqual(Dashboard.average_signups(), '0 / 0 / 0')
def test_monthly_revenue(self): ''' test method Dashboard.monthly_revenue() ''' # Empty database has no receipts self.failUnlessEqual(Dashboard.monthly_revenue(), '0.00') u = self.getUser() s = self.getSubscription(u) # set amount 10 for 1 receipt r = self.getReceipt(s, decimal.Decimal(10)) self.failUnlessEqual(Dashboard.monthly_revenue(), '10.00') # set amount 20 for 1 receipt r2 = self.getReceipt(s, decimal.Decimal(20)) self.failUnlessEqual(Dashboard.monthly_revenue(), '30.00') # remove receipt with amount=10 r.delete() self.failUnlessEqual(Dashboard.monthly_revenue(), '20.00') # remove all data r2.delete() u.delete() self.failUnlessEqual(Dashboard.monthly_revenue(), '0.00')
def post(self, user_id): data = request.get_json() board = Dashboard(**data) try: User.query.get(user_id).serialize() print(data) db.session.add(board) db.session.commit() connections = dashboard_users_table.insert().\ values(dashboard_id=board.id, user_id=user_id) db.session.execute(connections) db.session.commit() return {"id": board.id}, 201 except: return "User not registered"
def admin_functions(request): usernames = [] dashboards = [] userids = [] dashprivfound = [] if (not request.user.is_superuser): #remove before production... add setadminuser as parameter and use username as value if request.method == "GET" and request.GET.get( "setadminuser") is not None: set_site_admin(request.GET.get("setadminuser")) #template = loader.get_template('Authentication/Login.html') #context = RequestContext(request, {}) return redirect( settings.BASE_URL) #HttpResponse(template.render(context)) actionselected = "user" if request.method == "POST" and request.POST['adminaction'] == "delete": rmvuser = request.POST['username'] delete_user(rmvuser) usernames = retrieve_all_usernames() elif request.method == "POST" and request.POST[ 'adminaction'] == "viewactiveusers": usernames = retrieve_active_usernames() elif request.method == "POST" and request.POST[ 'adminaction'] == "viewusers": usernames = retrieve_all_usernames() elif request.method == "POST" and request.POST[ 'adminaction'] == "viewsiteadmins": usernames = view_site_admins() elif request.method == "POST" and request.POST['adminaction'] == "setadmin": set_site_admin(request.POST['username']) usernames = view_site_admins() elif request.method == "POST" and request.POST[ 'adminaction'] == "removeadmin": remove_site_admin(request.POST['username']) usernames = view_site_admins() elif request.method == "POST" and request.POST[ 'adminaction'] == "viewalldashboards": actionselected = "dashboard" dash_objs = Dashboard.objects() for dash in dash_objs: dashboards.append(dash.title) print(dashboards) elif request.method == "POST" and request.POST[ 'adminaction'] == "deletedashboard": actionselected = "dashboard" delete_dashboard(request.POST['dashboard']) dash_objs = Dashboard.objects() for dash in dash_objs: dashboards.append(dash.title) elif request.method == "POST" and request.POST[ 'adminaction'] == "viewuserdashboards": actionselected = "dashboard" dashprivfound = Dashboard_Permission.objects.filter( user=request.POST['dashusername']) elif request.method == "POST": print(request.POST['adminaction']) print(actionselected) template = loader.get_template('Administration/adminfunctions.html') context = RequestContext( request, { 'ursfound': usernames, 'dashboardsfound': dashboards, 'actionselected': actionselected, 'dashprivfound': dashprivfound }) return HttpResponse(template.render(context))
def panel(): location1_list = [ "home", "dining", "scenic_spot", "traffic", "exhibition", "entertainment", "healthcare", "estate", "life_service", "hotel", "work_office", "finance", "education", "government", "infrastructure", "auto_related", "shopping", "sports", ] location2_list = [ ["home"], [ "chinese_restaurant", "japan_korea_restaurant", "japan_restaurant", "korea_restaurant", "western_restaurant", "bbq", "chafing_dish", "seafood_restaurant", "vegetarian_diet", "muslim_dish", "buffet", "dessert", "cooler_store", "snack_bar", "vegetarian_diet", ], ["scenic_spot"], [ "traffic", "bus_stop", "subway", "highway_service_area", "railway_station", "airport", "coach_station", "traffic_place", "bus_route", "subway_track", ], ["museum", "exhibition_hall", "science_museum", "library", "gallery", "convention_center"], [ "bath_sauna", "ktv", "bar", "coffee", "night_club", "cinema", "odeum", "resort", "outdoor", "game_room", "internet_bar", "botanic_garden", "music_hall", "movie", "playground", "temple", "aquarium", "cultural_venues", "fishing_garden", "picking_garden", "cultural_palace", "memorial_hall", "park", "zoo", "chess_room", "bathing_beach", "theater", ], ["hospital", "clinic", "emergency_center", "drugstore", "special_hospital"], ["residence", "business_building", "community_center"], [ "travel_agency", "ticket_agent", "ticket_agent_plane", "ticket_agent_train", "post_office", "telecom_offices", "telecom_offices_unicom", "telecom_offices_netcom", "newstand", "water_supply_office", "electricity_office", "photographic_studio", "laundry", "talent_market", "lottery_station", "housekeeping", "housekeeping_lock", "housekeeping_hour", "housekeeping_water_deliver", "intermediary", "pet_service", "salvage_station", "welfare_house", "barbershop", "laundry", "ticket_agent_coach", "housekeeping_nanny", "housekeeping_house_moving", "telecom_offices_tietong", "ticket_agent_bus", "telecom_offices_mobile", "housekeeping_alliance_repair", "telecom_offices_telecom", ], [ "motel", "hotel", "economy_hotel", "guest_house", "hostel", "farm_house", "villa", "dormitory", "other_hotel", "apartment_hotel", "inn", "holiday_village", ], ["work_office"], ["bank", "atm", "insurance_company", "security_company"], [ "university", "high_school", "primary_school", "kinder_garten", "training_institutions", "technical_school", "adult_education", "scientific_research_institution", "driving_school", ], [ "agriculture_forestry_and_fishing_base", "foreign_institutional", "government_agency", "minor_institutions", "tax_authorities", ], [ "public_utilities", "toll_station", "other_infrastructure", "public_phone", "factory", "city_square", "refuge", "public_toilet", "church", "industrial_area", ], [ "gas_station", "parking_plot", "auto_sale", "auto_repair", "motorcycle", "car_maintenance", "car_wash", "motorcycle_service", "motorcycle_repair", ], [ "comprehensive_market", "convenience_store", "supermarket", "digital_store", "pet_market", "furniture_store", "farmers_market", "commodity_market", "flea_market", "sports_store", "clothing_store", "video_store", "glass_store", "mother_store", "jewelry_store", "cosmetics_store", "gift_store", "pawnshop", "antique_store", "bike_store", "cigarette_store", "stationer", "motorcycle_sell", "sports_store", "shopping_street", ], [ "golf", "skiing", "sports_venues", "football_field", "tennis_court", "horsemanship", "race_course", "basketball_court", ], ] motion_dict = {"sitting": 0, "walking": 3, "running": 4, "ridding": 2, "driving": 1, "unknown": -1} event_list = [ "attend_concert", "go_outing", "dining_in_restaurant", "watch_movie", "study_in_class", "visit_sights", "work_in_office", "exercise_outdoor", "shopping_in_mall", "exercise_indoor", ] status_dict = { "unknown": -1, "arriving_home": 0, "leaving_home": 1, "arriving_office": 2, "leaving_office": 3, "going_home": 4, "going_office": 5, "user_home_office_not_yet_defined": 6, } session_token = session.get("session_token") if not session_token: return redirect(url_for("login")) user = Developer() user.session_token = session_token app_id = request.form.get("app_id") dashboard = Dashboard() dashboard.app_id = app_id app_key = dashboard.get_app_key() if not app_key: app_key = dashboard.get_demo_app_key() if not app_key: flash("App not exists") return render_template("console.html") type = request.form.get("type") val = request.form.get("val") if type and val: if user.get_tracker_of_app(app_id): tracker_list = user.tracker_list headers = { "X-AVOSCloud-Application-Id": "qTFUwcnM3U3us8B3ArenyJbm", "X-AVOSCloud-Application-Key": "ksfJtp9tIEriApWmbtOrQs5F", } payload = {"type": type, "val": val} # for tracker in tracker_list: requests.post("https://leancloud.cn/1.1/functions/notify_new_details", headers=headers, data=payload) return render_template( "panel.html", location1_list=location1_list, location2_list=location2_list, motion_dict=motion_dict, event_list=event_list, status_dict=status_dict, )
def dash(param): username = session.get("username") session_token = session.get("session_token") if not session_token: return redirect(url_for("index")) # app_name = request.args.get('app_name') # app_id = request.args.get('app_id') app_name = session.get("app_name") app_id = session.get("app_id") print "the app_name is %s and the app_id is: %s" % (str(app_name), str(app_id)) user = Developer() user.session_token = session_token print "Param is %s" % (str(param)) if param == "dashboard": if user.get_all_application(): all_application_dict = user.all_application_dict # 一旦上一步执行成功,会给user添加一个成员变量 all_application_dict else: print "no application exists" all_application_dict = {} print "all_application_dict is : %s" % (str(all_application_dict)) if app_name and app_id: del all_application_dict[app_name] else: app_name = all_application_dict.keys()[0] app_id = all_application_dict[app_name] del all_application_dict[app_name] elif param == "demo": if user.get_all_demo_application(): all_demo_application_dict = ( user.all_demo_application_dict ) # 一旦上一步执行成功,会给user添加一个成员变量 all_demo_application_dict else: print "no demo application exists" all_demo_application_dict = {} print "all_demo_application_dict is : %s" % (str(all_demo_application_dict)) all_application_dict = {} if DEMO_APP_NAME in all_demo_application_dict.keys(): app_name = DEMO_APP_NAME app_id = all_demo_application_dict[app_name] else: "Demo not exists" app_name = None app_id = None else: print "Param is %s" % (str(param)) all_application_dict = {} session["app_name"] = app_name session["app_id"] = app_id # del all_demo_application_dict[app_name] print "app_name is %s and app_id is %s" % (str(app_name), str(app_id)) dashboard = Dashboard() dashboard.app_id = app_id # all_app_event = 1 if request.method == "POST": is_xhr = True else: is_xhr = False print "last all_application_dict is : %s" % (str(all_application_dict)) default_user_profile_category = "Age&Gender" default_path_analysis_category = "Frequently Location" default_event_name = "Event1" default_behavior_recognition_measure = "Activity" user_profile_type = "age" path_analysis_type = "location" event_name_type = "Event1" behavior_recognition_measure_type = "activity" user_profile_category_dict = dashboard.get_user_profile_category_dict() # ['Occupation','Tastes'] path_analysis_measure_dict = dashboard.get_path_analysis_measure_dict() # ['Frequently Track'] behavior_recognition_event_dict = dashboard.get_behavior_recognition_event_dict() # ['event2'] behavior_recognition_measure_dict = dashboard.get_behavior_recognition_measure_dict() # ['Location','Time'] del user_profile_category_dict[user_profile_type] del path_analysis_measure_dict[path_analysis_type] del behavior_recognition_event_dict[event_name_type] del behavior_recognition_measure_dict[behavior_recognition_measure_type] print "log comes out !!!!!" return render_template( "shared/dash.html", is_xhr=is_xhr, # dashboard_link = dashboard_link, route_link="dashboard", # sort according to ['16down', '16to35', '35to55', '55up'] # discard unknown data username=username, app_name=app_name, app_id=app_id, all_application_dict=all_application_dict, default_user_profile_category=default_user_profile_category, default_path_analysis_category=default_path_analysis_category, default_event_name=default_event_name, default_behavior_recognition_measure=default_behavior_recognition_measure, user_profile_type=user_profile_type, path_analysis_type=path_analysis_type, event_name_type=event_name_type, behavior_recognition_measure_type=behavior_recognition_measure_type, user_profile_category_dict=user_profile_category_dict, path_analysis_measure_dict=path_analysis_measure_dict, behavior_recognition_event_dict=behavior_recognition_event_dict, behavior_recognition_measure_dict=behavior_recognition_measure_dict, )
class DashboardsViewTest(MockedCloudAuthenticatedTestCase): def setUp(self): super(DashboardsViewTest, self).setUp() self.dash1 = Dashboard(widgets='{"test":"widget"}', owner=self.existing_user) self.dash1.save() self.dash2 = Dashboard(widgets='{"test2":"widget2"}', owner=self.existing_user) self.dash2.save() self.factory = RequestFactory() def test_dashboard_list_read(self): resp = self.client.get(reverse('dashboard-list')) self.assertEqual(resp.status_code, 200) json_resp = json.loads(resp.content) self.assertTrue(type(json_resp) is list) self.assertTrue(len(json_resp) == 2) self.assertEqual(json_resp[0]['widgets'], self.dash1.widgets) def test_dashboard_detail_read(self): resp = self.client.get( reverse('dashboard-list') + '/{}'.format(self.dash1.pk)) self.assertEqual(resp.status_code, 200) json_resp = json.loads(resp.content) self.assertTrue(type(json_resp) is not list) self.assertEqual(json_resp['widgets'], self.dash1.widgets) def test_unauthenticated_dashboard_read(self): self.client.logout() resp = self.client.get(reverse('dashboard-list')) self.assertEqual(resp.status_code, 403) def test_dashboard_create(self): old_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() body = {'widgets': '{"test3":"widget3"}'} resp = self.client.post(reverse('dashboard-list'), data=body) self.assertEqual(resp.status_code, 201) new_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() self.assertEqual(old_dash_count + 1, new_dash_count) def test_dashboard_bad_create(self): old_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() bad_body = {'widgets': '{"badjsson'} resp = self.client.post(reverse('dashboard-list'), data=bad_body) self.assertEqual(resp.status_code, 400) new_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() self.assertEqual(old_dash_count, new_dash_count) def test_dashboard_update(self): dashes = self.client.get(reverse('dashboard-list')) dash_loc = dashes.data[0]['url'] new_widget = {"widgets": {"new": "widget"}} resp = self.client.put(dash_loc, new_widget) self.assertEqual(resp.status_code, 200) widget = self.client.get(dash_loc) self.assertEqual(widget.data['widgets'], new_widget['widgets']) def test_dashboard_delete(self): old_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() dashes = self.client.get(reverse('dashboard-list')) dash_loc = dashes.data[0]['url'] resp = self.client.delete(dash_loc) self.assertEqual(resp.status_code, 204) new_dash_count = Dashboard.objects.filter( owner=self.existing_user).count() self.assertEqual(old_dash_count - 1, new_dash_count)
class DashboardsViewTest(MockedCloudAuthenticatedTestCase): def setUp(self): super(DashboardsViewTest, self).setUp() self.dash1 = Dashboard(widgets='{"test":"widget"}', owner=self.existing_user) self.dash1.save() self.dash2 = Dashboard(widgets='{"test2":"widget2"}', owner=self.existing_user) self.dash2.save() self.factory = RequestFactory() def test_dashboard_list_read(self): resp = self.client.get(reverse('dashboard-list')) self.assertEqual(resp.status_code, 200) json_resp = json.loads(resp.content) self.assertTrue(type(json_resp) is list) self.assertTrue(len(json_resp) == 2) self.assertEqual(json_resp[0]['widgets'], self.dash1.widgets) def test_dashboard_detail_read(self): resp = self.client.get(reverse('dashboard-list')+'/{}'.format(self.dash1.pk)) self.assertEqual(resp.status_code, 200) json_resp = json.loads(resp.content) self.assertTrue(type(json_resp) is not list) self.assertEqual(json_resp['widgets'], self.dash1.widgets) def test_unauthenticated_dashboard_read(self): self.client.logout() resp = self.client.get(reverse('dashboard-list')) self.assertEqual(resp.status_code, 403) def test_dashboard_create(self): old_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() body = {'widgets':'{"test3":"widget3"}'} resp = self.client.post(reverse('dashboard-list'), data=body) self.assertEqual(resp.status_code, 201) new_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() self.assertEqual(old_dash_count + 1, new_dash_count) def test_dashboard_bad_create(self): old_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() bad_body = {'widgets':'{"badjsson'} resp = self.client.post(reverse('dashboard-list'), data=bad_body) self.assertEqual(resp.status_code, 400) new_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() self.assertEqual(old_dash_count, new_dash_count) def test_dashboard_update(self): dashes = self.client.get(reverse('dashboard-list')) dash_loc = dashes.data[0]['url'] new_widget = {"widgets":{"new":"widget"}} resp = self.client.put(dash_loc, new_widget) self.assertEqual(resp.status_code, 200) widget = self.client.get(dash_loc) self.assertEqual(widget.data['widgets'], new_widget['widgets']) def test_dashboard_delete(self): old_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() dashes = self.client.get(reverse('dashboard-list')) dash_loc = dashes.data[0]['url'] resp = self.client.delete(dash_loc) self.assertEqual(resp.status_code, 204) new_dash_count = Dashboard.objects.filter(owner = self.existing_user).count() self.assertEqual(old_dash_count-1, new_dash_count)
def panel(): location1_list = ['home','dining','scenic_spot','traffic', 'exhibition', 'entertainment','healthcare', 'estate','life_service','hotel', 'work_office','finance', 'education','government','infrastructure', 'auto_related','shopping','sports'] location2_list = [ ['home'], ['chinese_restaurant', 'japan_korea_restaurant','japan_restaurant','korea_restaurant', 'western_restaurant', 'bbq', 'chafing_dish', 'seafood_restaurant', 'vegetarian_diet', 'muslim_dish', 'buffet', 'dessert', 'cooler_store', 'snack_bar','vegetarian_diet'], ['scenic_spot'], ['traffic','bus_stop','subway','highway_service_area','railway_station','airport','coach_station','traffic_place','bus_route','subway_track'], ['museum', 'exhibition_hall', 'science_museum', 'library', 'gallery', 'convention_center'], ['bath_sauna', 'ktv', 'bar', 'coffee', 'night_club', 'cinema', 'odeum', 'resort', 'outdoor', 'game_room', 'internet_bar','botanic_garden','music_hall','movie','playground','temple','aquarium','cultural_venues','fishing_garden','picking_garden','cultural_palace', 'memorial_hall','park','zoo','chess_room','bathing_beach','theater'], ['hospital', 'clinic', 'emergency_center', 'drugstore','special_hospital'], ['residence', 'business_building','community_center'], ['travel_agency', 'ticket_agent','ticket_agent_plane', 'ticket_agent_train','post_office', 'telecom_offices' ,'telecom_offices_unicom', 'telecom_offices_netcom','newstand', 'water_supply_office', 'electricity_office', 'photographic_studio', 'laundry', 'talent_market', 'lottery_station', 'housekeeping','housekeeping_lock','housekeeping_hour','housekeeping_water_deliver', 'intermediary', 'pet_service', 'salvage_station', 'welfare_house', 'barbershop','laundry','ticket_agent_coach','housekeeping_nanny','housekeeping_house_moving', 'telecom_offices_tietong','ticket_agent_bus','telecom_offices_mobile','housekeeping_alliance_repair','telecom_offices_telecom'], ['motel', 'hotel', 'economy_hotel', 'guest_house', 'hostel','farm_house','villa','dormitory','other_hotel','apartment_hotel','inn','holiday_village'], ['work_office'], ['bank', 'atm', 'insurance_company', 'security_company'], ['university', 'high_school', 'primary_school', 'kinder_garten', 'training_institutions', 'technical_school', 'adult_education','scientific_research_institution','driving_school'], ['agriculture_forestry_and_fishing_base','foreign_institutional','government_agency','minor_institutions','tax_authorities'], ['public_utilities', 'toll_station', 'other_infrastructure','public_phone','factory' ,'city_square','refuge','public_toilet','church','industrial_area'], ['gas_station', 'parking_plot', 'auto_sale', 'auto_repair', 'motorcycle', 'car_maintenance', 'car_wash','motorcycle_service','motorcycle_repair'], ['comprehensive_market', 'convenience_store', 'supermarket', 'digital_store', 'pet_market', 'furniture_store', 'farmers_market', 'commodity_market', 'flea_market', 'sports_store', 'clothing_store', 'video_store', 'glass_store', 'mother_store', 'jewelry_store', 'cosmetics_store', 'gift_store', 'pawnshop', 'antique_store', 'bike_store', 'cigarette_store', 'stationer','motorcycle_sell','sports_store','shopping_street'], ['golf','skiing','sports_venues','football_field','tennis_court','horsemanship','race_course','basketball_court'], ] motion_dict = {'sitting': 0, 'walking': 3, 'running': 4, 'ridding': 2, 'driving': 1, 'unknown': -1} event_list = ['attend_concert', 'go_outing', 'dining_in_restaurant', 'watch_movie', 'study_in_class', 'visit_sights', 'work_in_office', 'exercise_outdoor', 'shopping_in_mall', 'exercise_indoor'] status_dict = {"unknown": -1, "arriving_home":0, "leaving_home":1, "arriving_office": 2, "leaving_office": 3, "going_home":4, "going_office":5, "user_home_office_not_yet_defined": 6} session_token = session.get('session_token') if not session_token: return redirect(url_for('login')) user = Developer() user.session_token = session_token app_id = request.form.get('app_id') dashboard = Dashboard() dashboard.app_id = app_id app_key = dashboard.get_app_key() if not app_key: app_key = dashboard.get_demo_app_key() if not app_key: flash('App not exists') return render_template('console.html') type = request.form.get('type') val = request.form.get('val') if type and val: if user.get_tracker_of_app(app_id): tracker_list = user.tracker_list headers = {"X-AVOSCloud-Application-Id": "qTFUwcnM3U3us8B3ArenyJbm", "X-AVOSCloud-Application-Key": "ksfJtp9tIEriApWmbtOrQs5F"} payload = {"type": type, "val": val} #for tracker in tracker_list: requests.post("https://leancloud.cn/1.1/functions/notify_new_details", headers = headers, data = payload) return render_template('panel.html', location1_list = location1_list, location2_list = location2_list, motion_dict = motion_dict, event_list = event_list, status_dict= status_dict)