def __setattr__(self, name, value): if name in ('_vals', '_name', '_appname', '_verbose_name', '_readonly', '_cache_prefix', '_main'): return object.__setattr__(self, name, value) if self._readonly: raise AttributeError, 'settings group %s is read-only' % self._name if not name in self._vals: raise AttributeError, 'setting "%s" not found' % name if not has_db: raise SettingsException, "no database -- settings are immutable" self._vals[name].initial = self._vals[name].clean(value) try: setting = Setting.objects.get(app=self._appname, site=Site.objects.get_current(), class_name=self._name, key=name) except Setting.DoesNotExist: setting = Setting(site=Site.objects.get_current(), app=self._appname, class_name=self._name, key=name) serialized = value if hasattr(self._vals[name].widget, '_format_value'): serialized = self._vals[name].widget._format_value(value) serialized = force_unicode(serialized) setting.value = serialized setting.save() if appsettings.USE_CACHE: cache.set(self._cache_prefix + name, value) if self._main: setattr(django_settings, name, value)
def update_database(): last_data = {'readings': {'temp': 0, 'humidity': 0}, 'parameters': None} while 1: update_time = timezone.now() data = (yield) if (round(last_data["readings"]["temp"]) != round( data["readings"]["temp"])) or (round( last_data["readings"]["humidity"]) != round( data["readings"]["humidity"])): try: reading_record = Reading.objects.get(pk=1) except Reading.DoesNotExist: reading_record = Reading(time=update_time, temperature=data["readings"]["temp"], humidity=data["readings"]["humidity"]) else: reading_record.time = update_time reading_record.temperature = data["readings"]["temp"] reading_record.humidity = data["readings"]["humidity"] reading_record.save() if last_data["parameters"] != data["parameters"]: setting_record = Setting(time=update_time, mode=data["parameters"]["mode"], temperature=data["parameters"]["temp"], humidity=data["parameters"]["humidity"]) setting_record.save() last_data = data
def set_value(db_session, keyname, value): setting = Setting.query.filter(Setting.key == keyname).first() if not setting: setting = Setting(keyname, value) else: setting.value = value db_session.add(setting)
def index(): if request.method == "GET": # find the latest setting record settings = Setting.query.order_by(desc(Setting.id)).all() if len(settings) > 0: setting = settings[0] else: setting = None return render_template("admin/settings.html", setting=setting) elif request.method == "POST": # get post data setting_id = request.form['setting_id'] host = request.form['host'] headline = request.form['headline'] setting_text = request.form['text'] start_date = request.form['start_date'] current_app.logger.info("%s, %s, %s, %s, %s" % (setting_id, host, headline, setting_text, start_date)) # find or create setting object setting = None if setting_id: setting = Setting.query.get(int(setting_id)) if not setting: setting = Setting() # udpate db setting.host = host setting.headline = headline setting.setting_text = setting_text setting.start_date = start_date db_session.add(setting) db_session.commit() flash(_("Setting updated!")) return redirect(url_for(".index"))
def __setattr__(self, name, value): if name in ('_vals', '_name', '_appname', '_verbose_name', '_readonly', '_cache_prefix', '_main'): return object.__setattr__(self, name, value) if self._readonly: raise AttributeError, 'settings group %s is read-only' % self._name if not name in self._vals: raise AttributeError, 'setting "%s" not found'%name if not has_db: raise SettingsException, "no database -- settings are immutable" self._vals[name].initial = self._vals[name].clean(value) try: setting = Setting.objects.get(app = self._appname, site = Site.objects.get_current(), class_name = self._name, key = name) except Setting.DoesNotExist: setting = Setting(site = Site.objects.get_current(), app = self._appname, class_name = self._name, key = name) serialized = value if hasattr(self._vals[name].widget, '_format_value'): serialized = self._vals[name].widget._format_value(value) serialized = force_unicode(serialized) setting.value = serialized setting.save() if appsettings.USE_CACHE: cache.set(self._cache_prefix+name, value) if self._main: setattr(django_settings, name, value)
def update_database(): last_data = {'readings': {'temp': 0, 'humidity': 0}, 'parameters': None} while 1: update_time = timezone.now() data = (yield) # Round current temperature and humidity readings temperature_rounded = round(data["readings"]["temp"]) humidity_rounded = round(data["readings"]["humidity"]) # Compare rounded current readings against the rounded previous readings if (round(last_data["readings"]["temp"]) != temperature_rounded) or ( round(last_data["readings"]["humidity"]) != humidity_rounded): try: reading_record = Reading.objects.get(pk=1) except Reading.DoesNotExist: reading_record = Reading(time=update_time, temperature=temperature_rounded, humidity=humidity_rounded) else: reading_record.time = update_time reading_record.temperature = temperature_rounded reading_record.humidity = humidity_rounded reading_record.save() if last_data["parameters"] != data["parameters"]: setting_record = Setting(time=update_time, source=0, mode=data["parameters"]["mode"], temperature=data["parameters"]["temp"], humidity=data["parameters"]["humidity"]) setting_record.save() last_data = data
def save(self): """ Custom save method for standard Django Form""" data = self.cleaned_data for k,v in data.items(): if self.user: Setting.set_setting(self.user, k, v) else: AdminSetting.set_setting(k, v)
def settings(): form = SettingsForm(format_string = Setting.get("format_string")) if request.method == 'POST': if form.validate_on_submit(): Setting.set("format_string", form.format_string.data) flash("Settings Updated") return redirect("/") return render_template('settings.html', form=form)
def create_database(destroy_existing=False): """ Create db and tables if it doesn't exist """ if not os.path.exists(DB_NAME): logger.info('Create database: {0}'.format(DB_NAME)) open(DB_NAME, 'a').close() Show.create_table() Episode.create_table() Setting.create_table()
def set_value(self, key, value): setting = Setting.query.filter(Setting.key == key).first() if setting is None: setting = Setting(key,'') db.session.add(setting) # self.logger.debug('setting {0} to {1}'.format(key, value)) setting.value = value db.session.commit()
def set_value(self, key, value): setting = Setting.query.filter(Setting.key == key).first() if setting is None: setting = Setting(key, '') db.session.add(setting) # self.logger.debug('setting {0} to {1}'.format(key, value)) setting.value = value db.session.commit()
def playlist_content_html(): """" Returns the HTML for the structure of the playlists as they will be populated ont he homepage. Does not actually contain the list of video names as those are filled in later asynchronously via the cache. """ # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() dict_playlists_by_title = {} all_playlists = [] for playlist in Playlist.all(): if playlist.title in topics_list: dict_playlists_by_title[playlist.title] = playlist for topic in topics_list: if topic in dict_playlists_by_title: playlist = dict_playlists_by_title[topic] video_count = playlist.get_video_count() # 3 columns, 18px per row. This must be updated in conjunction # with code in homepage.js height = math.ceil(video_count / 3) * 18 playlist_data = { 'title': topic, 'topic': topic, 'playlist': playlist, 'list_height': height, 'next': None, } all_playlists.append(playlist_data) playlist_data_prev = None for playlist_data in all_playlists: if playlist_data_prev: playlist_data_prev['next'] = playlist_data playlist_data_prev = playlist_data timestamp = time.time() template_values = { 'App': App, 'all_playlists': all_playlists, 'smart_history': smart_history, # convert timestamp to a nice integer for the JS 'timestamp': int(round(timestamp * 1000)), } html = shared_jinja.get().render_template("library_playlist_template.html", **template_values) Setting.cached_playlist_content_date( str(datetime.datetime.fromtimestamp(timestamp))) return html
def playlist_content_html(): """" Returns the HTML for the structure of the playlists as they will be populated ont he homepage. Does not actually contain the list of video names as those are filled in later asynchronously via the cache. """ # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() dict_playlists_by_title = {} all_playlists = [] for playlist in Playlist.all(): if playlist.title in topics_list: dict_playlists_by_title[playlist.title] = playlist for topic in topics_list: if topic in dict_playlists_by_title: playlist = dict_playlists_by_title[topic] video_count = playlist.get_video_count() # 3 columns, 18px per row. This must be updated in conjunction # with code in homepage.js height = math.ceil(video_count / 3) * 18 playlist_data = { 'title': topic, 'topic': topic, 'playlist': playlist, 'list_height': height, 'next': None, } all_playlists.append(playlist_data) playlist_data_prev = None for playlist_data in all_playlists: if playlist_data_prev: playlist_data_prev['next'] = playlist_data playlist_data_prev = playlist_data timestamp = time.time() template_values = { 'App' : App, 'all_playlists': all_playlists, 'smart_history': smart_history, # convert timestamp to a nice integer for the JS 'timestamp': int(round(timestamp * 1000)), } html = shared_jinja.get().render_template("library_playlist_template.html", **template_values) Setting.cached_playlist_content_date( str(datetime.datetime.fromtimestamp(timestamp))) return html
def get_settings(self): try: setting = Setting.get(name=self.setting_name) return json.loads(setting.value) except: Setting.create( name=self.setting_name, value=json.dumps(self._settings) ) return self._settings
def logviews(): """ 操作日志界面 :return: 返回数据查询结果并构建相应页面 """ if request.method == "GET": page = request.values.get('page', 1, type=int) uname = request.values.get('username', "", type=str) username = b64decode(unquote(uname)) catsname = request.values.get('cats', "", type=str) cats = b64decode(unquote(catsname)) date = request.values.get('date', "", type=str) logdata = Dev_Loging.query.filter( (Dev_Loging.UserName.like("%" + username + "%"), "")[username is None], (Dev_Loging.Date.like("%" + date + "%"), "")[date is None], (Dev_Loging.Log.like("%" + cats + "%"), "")[cats is None] ) paginateion = logdata.paginate( page, per_page=Setting().pagination ) posts = paginateion.items count = logdata.count() eventlog("[查看日志]" + " 第" + str(page) +"页") return render_template( '/admin/log.html', posts=posts, count=count, pagination=paginateion, page=page, username=uname, cats=catsname, date=date, thuname=username.decode('utf-8'), thcats=cats.decode('utf-8') ) elif request.method == "POST": cleancode = request.values.get('logcode', 'None', type=str) if cleancode == "all": return emptylog() else: page = request.values.get('page', 1, type=int) uname = request.values.get('username', "", type=str) username = b64decode(unquote(uname)) catsname = request.values.get('cats', "", type=str) cats = b64decode(unquote(catsname)) date = request.values.get('date', "", type=str) logdata = Dev_Loging.query.filter( (Dev_Loging.UserName.like("%" + username + "%"), "")[username is None], (Dev_Loging.Date.like("%" + date + "%"), "")[date is None], (Dev_Loging.Log.like("%" + cats + "%"), "")[cats is None] ) paginateion = logdata.paginate( page, per_page=Setting().pagination ) posts = paginateion.items count = logdata.count() eventlog("[查看日志]" + " 第" + str(page) + "页") return render_template( '/admin/log.html', posts=posts, count=count, pagination=paginateion, page=page, username=uname, cats=catsname, date=date, thuname=username.decode('utf-8'), thcats=cats.decode('utf-8') )
def load_deeds(self): if not Setting.get('user_id', None): self.set_status("Error: Please set user_id and password in settings") return sync.load_sync_data( Setting.get_all(self.db), on_success=self.sync_load_success, on_error=self.sync_error, on_failure=self.sync_error )
def sync_deeds(self): if not Setting.get('user_id', None): self.set_status("Error: Please set user_id and password in settings") return sync.sync_data( self.db.query(Deed).filter_by(synced=False), Setting.get_all(self.db), on_success=self.sync_success, on_error=self.sync_error, on_failure=self.sync_error )
def deleteuserpayment(request): if request.is_ajax(): if request.method == 'POST': txtmessage = '' try: json_data = json.loads(request.body) if json_data['txtmessage']: txtmessage = json_data['txtmessage'] userpayment_id = json_data['userpayment_id'] registro = UserPayment.objects.get( user_payment_id=userpayment_id) registro.message = txtmessage registro.enabled = False registro.status = 'CA' registro.channel = 'X' registro.save() # Envio envento a intercom ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) reply = intercom.submitEvent( registro.user.user_id, registro.user.email, "cancelled-sub", { "event_description": "recurrencia cancelada por el administrador" }) if not reply: registro.message = "Intercom error: cannot post the event" registro.save() except Exception as e: registro.message = "Intercom error: %s" % str(e) registro.save() return JsonResponse({'message': 'activado correctamente'}, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def expireuser(request): if request.is_ajax(): if request.method == 'GET': fecha = datetime.today() if request.method == 'POST': try: json_data = json.loads(request.body) user_id = json_data['user_id'] user = User.objects.get(user_id=user_id) fecha = datetime.today() d = timedelta(days=1) fecha -= d user.expiration = fecha user.save() # Envio envento a intercom ep = Setting.get_var('intercom_endpoint') token = Setting.get_var('intercom_token') try: intercom = Intercom(ep, token) metadata = { "event_description": "usuario expirado por el administrador", "expire_at": str(int(mktime(user.expiration.timetuple()))) } reply = intercom.submitEvent(user.user_id, user.email, "user_expired", metadata) except Exception as e: pass return JsonResponse( { 'message': 'Guardado correctamente', 'data': fecha }, status=200) except Exception as e: return JsonResponse( { 'message': 'Hubo un error', 'data': e.message }, status=500) return JsonResponse({ 'message': 'Metodo no permitido', 'data': '' }, status=500)
def set_settings(self, **kwargs): # Only copy valid keys fallback to default settings vk = self._settings.keys() kwargs = {k: v for k, v in kwargs.items() if k in vk} kwargs = dict(self._settings.items() + kwargs.items()) try: s = Setting.get(name=self.setting_name) s.value = json.dumps(kwargs) s.save() except: Setting.create( name=self.setting_name, value=json.dumps(kwargs), date_last_updated=datetime.datetime.now() )
def post(self): setting = Setting.query().get() if not setting: setting = Setting() setting.year = int(self.request.get('year')) setting.quarter = int(self.request.get('quarter')) setting.num_labs = int(self.request.get('num_labs')) setting.repeat_partners = eval(self.request.get('repeat_partners')) setting.cross_section_partners = eval( self.request.get('cross_section_partners')) setting.put() return self.redirect('/admin?message=Quarter and Year Updated')
def create_app(config): if config is None: config = 'dev' if not os.path.isfile(CONFIG_FILE): create_config() #Create Flask application app = Flask(__name__) app.config.from_object(configurations[config]) #set 404 errors to the not_found function app.error_handler_spec[None][404] = not_found #Init flask extentinons db.init_app(app) with app.app_context(): from models import Setting try: db_version = Setting.db_version() if db_version < Setting.DB_VERSION: #TODO: Implement settings db upgrade code print " * Upgrading the settings database" except: pass from .api_v1 import api_v1 app.register_blueprint(api_v1) return app
def notice_list(): """ 通知公告列表 :return: """ page = request.values.get('page', 1, type=int) aname = request.values.get('aname', "", type=str) b64aname = b64decode(unquote(aname)) cuser = request.values.get('cuser', "", type=str) b64cuser = b64decode(unquote(cuser)) cdata = request.values.get('cdata', "", type=str) notices = Dev_Note.query.filter( (Dev_Note.articlename.like("%" + b64aname + "%"), "")[aname is None], (Dev_Note.createuser.like("%" + b64cuser + "%"), "")[cuser is None], (Dev_Note.createdate.like("%" + cdata + "%"), "")[cdata is None]) paginateion = notices.paginate(page, per_page=Setting().pagination) posts = paginateion.items count = notices.count() eventlog("[查看通知公告列表页] " + "第" + str(page) + "页") result = { 'posts': posts, 'count': count, 'pagination': paginateion, 'page': page } return result
def test_setting_unicode(self): a = Setting.get("test") self.assertEqual(a.__unicode__(), "test") a.set_value("e") self.assertEqual(a.get_value(), "e")
def admin_query_list(): """ 后台ajax查询 :return: """ page = request.args.get('page', 1, type=int) request.script_root = url_for('indexview.index', _external=True) campusname = b64decode(unquote(request.args.get('campusname', "", type=str))) buildname = b64decode(unquote(request.args.get('buildname', "", type=str))) devinfo = Dev_DeviceStatus.query.filter( Dev_DeviceStatus.DeviceCondition != "N", (Dev_DeviceStatus.Campus.like("%" + campusname + "%"), "")[campusname is None], (Dev_DeviceStatus.Location.like("%" + buildname + "%"), "")[buildname is None] ).order_by(Dev_DeviceStatus.Campus.desc()) paginateion = devinfo.paginate( page, per_page=Setting().pagination ) count = devinfo.count() posts = paginateion.items campus = Dev_Campus.query.all() eventlog( "[查询校区/楼宇]" + campusname + buildname + " 第" + str(page) + "页" ) result = { 'posts': posts, 'count': count, 'pagination': paginateion, 'campus': campus, 'campusname': campusname.decode('utf-8'), 'buildname': buildname.decode('utf-8') } return result
def admin_query_serach(): """ 后台搜索 :return: """ request.script_root = url_for('indexview.index', _external=True) page = request.args.get('page', 1, type=int) word = request.args.get('keyword', "", type=str) serach = unquote(b64decode(word)).decode('utf-8') serp = qserach(serach) paginateion = serp.paginate( page, per_page=Setting().pagination ) count = serp.count() posts = paginateion.items eventlog( "[搜索]" + serach.encode('utf-8') + " 第" + str(page) + "页" ) result = { 'posts': posts, 'count': count, 'pagiation': paginateion, 'keyword': serach } return result
def post(self): if bool(self.request.get('choice')): ndb.delete_multi(Student.query().fetch(keys_only=True)) ndb.delete_multi(Assignment.query().fetch(keys_only=True)) ndb.delete_multi(Setting.query().fetch(keys_only=True)) self.redirect('/admin')
def settings(): errors = None admin_settings = get_settings(g.db, admin_id=current_user.admin_id) or Setting() form = SettingForm(request.form) if request.method == 'POST': if form.validate(): already_completed = finished_setting(admin_settings) form.populate_obj(admin_settings) admin_settings.admin_id = current_user.admin_id g.db.session.add(admin_settings) g.db.session.commit() url = 'hunts' if already_completed else 'new_hunt' flash('Settings have been updated successfully', 'success') return make_response(redirect(url_for(url))) else: logger.info( '%s attempted to submit settings information' ' resulting in errors: %s', current_user.email, form.errors) return make_response( render_template('settings.html', login=admin_settings.login, form=form, password=admin_settings.password, wax_site=admin_settings.wax_site))
def dvr_list_get(): """ dvr分类查询 :return: """ page = request.args.get('page', 1, type=int) request.script_root = url_for('indexview.index', _external=True) devtype = b64decode(unquote(request.args.get('devtype', "", type=str))) devonline = unquote(request.args.get('devonline', "", type=str)) if devonline == "5piv": devonline = "Y" elif devonline == "5ZCm": devonline = "N" devinfo = dvrselectsql(devtype, devonline) pagination = devinfo.paginate(page, per_page=Setting().pagination) count = devinfo.count() datas = pagination.items dev_types = DevDevType.query.all() result = { 'datas': datas, 'count': count, 'pagination': pagination, 'devtype': dev_types, 'devtypebname': devtype.decode('utf-8'), 'devostatus': devonline } eventlog("[访问设备管理分类查询页面] " + str(devtype) + str(devonline)) return result
def test_setting_unicode(self): a = Setting.get('test') self.assertEqual(a.__unicode__(), 'test') a.set_value('e') self.assertEqual(a.get_value(), 'e')
def post(self): # Protected for admins only by app.yaml so taskqueue can hit this URL step = self.request_int("step", default=0) if step == YouTubeSyncStep.START: self.startYouTubeSync() elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_DATA: self.updateVideoAndPlaylistData() # elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_READABLE_NAMES: # self.updateVideoAndPlaylistReadableNames() # elif step == YouTubeSyncStep.COMMIT_LIVE_ASSOCIATIONS: # self.commitLiveAssociations() # elif step == YouTubeSyncStep.INDEX_VIDEO_DATA: # self.indexVideoData() # elif step == YouTubeSyncStep.INDEX_PLAYLIST_DATA: # self.indexPlaylistData() # elif step == YouTubeSyncStep.REGENERATE_LIBRARY_CONTENT: # self.regenerateLibraryContent() elif step == YouTubeSyncStep.UPDATE_FROM_TOPICS: self.copyTopicsToPlaylist() log = YouTubeSyncStepLog() log.step = step log.generation = int(Setting.last_youtube_sync_generation_start()) log.put() if step < YouTubeSyncStep.UPDATE_FROM_TOPICS: self.task_step(step + 1)
def post(self): # Protected for admins only by app.yaml so taskqueue can hit this URL step = self.request_int("step", default = 0) if step == YouTubeSyncStep.START: self.startYouTubeSync() elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_DATA: self.updateVideoAndPlaylistData() # elif step == YouTubeSyncStep.UPDATE_VIDEO_AND_PLAYLIST_READABLE_NAMES: # self.updateVideoAndPlaylistReadableNames() # elif step == YouTubeSyncStep.COMMIT_LIVE_ASSOCIATIONS: # self.commitLiveAssociations() # elif step == YouTubeSyncStep.INDEX_VIDEO_DATA: # self.indexVideoData() # elif step == YouTubeSyncStep.INDEX_PLAYLIST_DATA: # self.indexPlaylistData() # elif step == YouTubeSyncStep.REGENERATE_LIBRARY_CONTENT: # self.regenerateLibraryContent() elif step == YouTubeSyncStep.UPDATE_FROM_TOPICS: self.copyTopicsToPlaylist() log = YouTubeSyncStepLog() log.step = step log.generation = int(Setting.last_youtube_sync_generation_start()) log.put() if step < YouTubeSyncStep.UPDATE_FROM_TOPICS: self.task_step(step + 1)
def admin_userindex(): """ 用户管理 :return: """ page = request.args.get('page', 1 ,type=int) ulevel = request.args.get('level', "", type=str) if ulevel == "all": upkey = "" elif ulevel == "su": upkey = 80 elif ulevel == "admin": upkey = 70 elif ulevel == "ordman": upkey = 10 else: upkey = "" request.script_root = url_for('indexview.index', _external=True) if upkey == "": pagination = User.query.order_by(User.id.asc()).paginate( page, per_page=Setting().pagination ) count = User.query.count() else: pagination = User.query.filter( User.permissions == upkey ).order_by(User.id.asc()).paginate( page, per_page=Setting().pagination ) count = User.query.filter( User.permissions == upkey ).count() posts = pagination.items suadmin_count = User.query.filter(User.permissions == 80).count() admin_count = User.query.filter(User.permissions == 70).count() ord_count = User.query.filter(User.permissions == 10).count() result = { 'posts': posts, 'count': count, 'pagination': pagination, 'all_count': count, 'suadmin_count': suadmin_count, 'admin_count': admin_count, 'user_count': ord_count } eventlog("[访问用户信息页面]") return result
class ExercisesCreatedHistogram(request_handler.RequestHandler): def get(self): past_days = self.request_int('past_days', 7) today_dt = dt.datetime.combine(dt.date.today(), dt.time()) earliest_dt = today_dt - dt.timedelta(days=past_days) self.response.out.write( self.get_histogram_spline_for_highcharts(earliest_dt)) @layer_cache.cache_with_key_fxn(lambda self, date: "%s|%s" % (Setting.cached_exercises_date(), date), expiration=CACHE_EXPIRATION_SECS, layer=layer_cache.Layers.Memcache) def get_histogram_spline_for_highcharts(self, earliest_dt=dt.datetime.min): histogram = {} for ex in Exercise.get_all_use_cache(): if ex.creation_date: creation_day = dt.datetime.combine(ex.creation_date, dt.time()) timestamp = to_unix_secs(creation_day) * 1000 histogram[timestamp] = histogram.get(timestamp, 0) + 1 total_exercises = {} prev_value = 0 for day, value in sorted(histogram.items()): prev_value = total_exercises[day] = prev_value + value # Only retain recent dates earliest_unix = to_unix_secs(earliest_dt) * 1000 histogram = [[k, v] for k, v in histogram.items() if k >= earliest_unix] total_exercises = [[k, v] for k, v in total_exercises.items() if k >= earliest_unix] context = { 'series': [{ 'name': 'Histogram (created per day)', 'type': 'column', 'data_values': json.dumps(histogram), 'axis': 0, }, { 'name': 'Total exercises', 'type': 'spline', 'data_values': json.dumps(total_exercises), 'axis': 1, }], # Let highcharts determine the scales for now. 'axes': [ { 'max': 'null' }, { 'max': 'null' }, ], } return self.render_jinja2_template_to_string( 'exercisestats/highcharts_exercises_created_histogram.json', context)
def __check_apikey(request): if 'HTTP_X_AUTH_CCM_KEY' in request.META: if request.META['HTTP_X_AUTH_CCM_KEY'] == Setting.get_var('ma_apikey'): return {'status': 'success'} else: return {'status': 'error'} else: return {'status': 'error'}
def manual_payment(request): if request.is_ajax(): if request.method == 'POST': try: json_data = json.loads(request.body) userpayment_id = json_data['userpayment_id'] up = UserPayment.get_by_id(userpayment_id) if up is None: return JsonResponse( { 'message': 'Error al realizar el pago, el usuario no existe' }, status=500) if up.user.has_active_recurrence(): return JsonResponse( { 'message': 'Error al realizar el pago: el usuario ya posee una recurrencia activa' }, status=500) logging.basicConfig( format= '%(asctime)s - manual_payments -[%(levelname)s]: %(message)s', filename=Setting.get_var('log_path'), level=logging.INFO) # Cambio a estado Pending up.status = 'PE' up.save() # Obtengo la tarjeta habilitada para el usuario card = up.user.get_card() if card is None: msg = 'Error al obtener la tarjeta para el usuario' up.error(msg) return JsonResponse({'message': msg}, status=500) pay = make_payment(up, card, logging, True) if pay: return JsonResponse( {'message': 'Pago efectuado correctamente'}, status=200) else: return JsonResponse( { 'message': 'Error al realizar el pago: verificar PaymentHistory' }, status=500) except Exception: return JsonResponse({'message': 'Hubo un error'}, status=500) return JsonResponse({'message': 'metodo no permitido'}, status=500)
def post(self): setting = Setting.query().get() if not setting: setting = Setting() setting.year = int(self.request.get('year')) setting.quarter = int(self.request.get('quarter')) setting.num_labs = int(self.request.get('num_labs')) setting.repeat_partners = eval(self.request.get('repeat_partners')) setting.cross_section_partners = eval(self.request.get('cross_section_partners')) setting.put() return self.redirect('/admin?message=Quarter and Year Updated')
def post(self): name = self.request.get("name").strip() theme = self.request.get("theme-name").strip() s = S.get_s() s.name = name s.theme = theme s.is_check_md5 = True if self.request.get("is_check_md5") else False s.put() self.redirect("/a/settings/")
def dvr_manage_post(): """ dvr管理ajax页面 :return: """ count = request.values.get('count', None, type=int) pagenum = request.values.get('pagenum', None, type=int) page_num = ((count / Setting().pagination + pagenum), 0)[count / Setting().pagination == 0] dvrinfo = Dev_DeviceInfo.query.order_by(Dev_DeviceInfo.ID.asc()).paginate( (page_num), per_page=Setting().pagination) dvrinfotemp = [] hasnext = {'next': dvrinfo.has_next} for devx in dvrinfo.items: jsonlist = devx.to_json() jsonlist.update(hasnext) dvrinfotemp.append(jsonlist) return jsonify(dvrinfotemp)
def dispatch_request(self): settings = Setting.query.filter(Setting.name != 'otpsecret').all() form = EditForm(request.form) if request.method == 'POST' and form.validate(): setting = Setting(form.name.data, form.value_decrypted.data) session.add(setting) session.commit() return redirect(url_for('settings.list')) return render_template('settings/list.html', settings=settings, form=form)
def update_database(): last_data = {'readings':{'temp':0,'humidity':0}, 'parameters':None} while 1: update_time = timezone.now() data = (yield) if (round(last_data["readings"]["temp"]) != round(data["readings"]["temp"])) or (round(last_data["readings"]["humidity"]) != round(data["readings"]["humidity"])): try: reading_record = Reading.objects.get(pk=1) except Reading.DoesNotExist: reading_record = Reading(time=update_time, temperature=data["readings"]["temp"], humidity=data["readings"]["humidity"]) else: reading_record.time = update_time reading_record.temperature = data["readings"]["temp"] reading_record.humidity = data["readings"]["humidity"] reading_record.save() if last_data["parameters"] != data["parameters"]: setting_record = Setting(time=update_time, mode=data["parameters"]["mode"], temperature=data["parameters"]["temp"], humidity=data["parameters"]["humidity"]) setting_record.save() last_data = data
def get(self): website = Setting().all().fetch(1) if 0 == len(website): w = Setting() w.webSite = "http://im.zxxsbook.com" w.put() website.append(w) web = website[0] self.searchRSS(web.webSite + "/RssSource")
def commitLiveAssociations(self): association_generation = int(Setting.last_youtube_sync_generation_start()) video_playlists_to_put = [] for video_playlist in VideoPlaylist.all(): live = (video_playlist.last_live_association_generation >= association_generation) if video_playlist.live_association != live: video_playlist.live_association = live video_playlists_to_put.append(video_playlist) db.put(video_playlists_to_put)
def post(self): rpcupload=self.request.get('rpcupload') rpcuser=self.request.get('rpcuser') rpcpwd=self.request.get('rpcpwd') logging.info(rpcupload) setting=Setting.getsetting() setting.rpcupload=(rpcupload=='1') setting.rpcuser=rpcuser setting.rpcpwd=rpcpwd setting.put() self.redirect('/admin/', '302')
def main(): # Check if defaults have been installed installed_defaults = memcache.get("installed_defaults") if installed_defaults is None: installed_defaults = Setting.all().filter('name = ', 'installed_defaults').get() if installed_defaults is None: logging.info("Installing default statuses") Status.install_defaults() if not memcache.add("installed_defaults", True): logging.error("Memcache set failed.") application = webapp.WSGIApplication(ROUTES, debug=config.DEBUG) wsgiref.handlers.CGIHandler().run(application)
def main(queue, interval_in_seconds=300): '''Queue is used to communicate with the climaduino_controller. Interval is how often to check the database for program settings.''' # BUG: Does not work when interval wraps around between days. If interval is 5 minutes # then times between 23:55 and 00:00 (midnight) do not work properly # set process niceness value to lower its priority os.nice(1) print("Climaduino Programming Sentry Active") while 1: now = datetime.datetime.now() current_settings = Setting.objects.last() # find out the day 0 is Monday current_day = now.weekday() # find out the time current_time = now.time() # calculate the time minus interval_in_seconds earliest_time = now - datetime.timedelta(seconds=interval_in_seconds) earliest_time = earliest_time.time() # query DB with interval_in_seconds "fudge factor" program_query = Program.objects.filter(mode=current_settings.mode, day=current_day, time__range=(earliest_time, current_time)) # if program exists, find out what should be changed and then change it for program in program_query: setting_record = Setting(time=now, source=3, mode=program.mode, temperature=program.temperature, humidity=program.humidity) setting_record.save() if program.temperature != current_settings.temperature: queue.put("%sF" % program.temperature) if program.humidity != current_settings.humidity: queue.put("%s%%" % program.humidity) # sleep for interval_in_seconds so we only check once during that interval time.sleep(interval_in_seconds)
def update(self, value): current_value = self.value new_value = self.to_python(value) if current_value != new_value: db_value = self.get_db_prep_save(value) try: s = self.setting s.value = db_value except SettingNotSet: log.debug('new setting %s.%s', self.group.key, self.key) s = Setting(group=self.group.key, key=self.key, value=db_value) if self.use_default and self.default == new_value: if s.id: log.info("Deleted setting %s.%s", self.group.key, self.key) s.delete() else: log.info("Updated setting %s.%s = %s", self.group.key, self.key, value) s.save() return True return False
def update_database(): last_data = {'readings':{'temp':0,'humidity':0}, 'parameters':None} while 1: update_time = timezone.now() data = (yield) # Round current temperature and humidity readings temperature_rounded = round(data["readings"]["temp"]) humidity_rounded = round(data["readings"]["humidity"]) # Compare rounded current readings against the rounded previous readings if (round(last_data["readings"]["temp"]) != temperature_rounded) or (round(last_data["readings"]["humidity"]) != humidity_rounded): try: reading_record = Reading.objects.get(pk=1) except Reading.DoesNotExist: reading_record = Reading(time=update_time, temperature=temperature_rounded, humidity=humidity_rounded) else: reading_record.time = update_time reading_record.temperature = temperature_rounded reading_record.humidity = humidity_rounded reading_record.save() if last_data["parameters"] != data["parameters"]: setting_record = Setting(time=update_time, source=0, mode=data["parameters"]["mode"], temperature=data["parameters"]["temp"], humidity=data["parameters"]["humidity"]) setting_record.save() last_data = data
def __init__(self, *args, **kwargs): """ Overrides the __init__ to fill the form initial data from database """ user = kwargs.get('user', None) initial = {} for field_name, obj in self.base_fields.items(): if user: initial[field_name] = Setting.get_setting(user, field_name) else: initial[field_name] = AdminSetting.get_setting(field_name) kwargs['initial'] = initial super(BaseSettingForm, self).__init__(*args, **kwargs) self.user = user
def testConsistency(self): from models import Setting # put in some old values self.policy.SetProbability(1) Setting.count_videos(10) self.policy.SetProbability(0) self.assertEqual(Setting.count_videos(), "10") Setting.count_videos(15) self.assertEqual(Setting.count_videos(), "15")
def initialize(self, request, response): """initial webapp.RequestHandler""" webapp.RequestHandler.initialize(self, request, response) if not self.request.path.endswith('/'): return self.redirect(self.request.path + "/", True) self.setting = Setting.get_setting() self.template_value = {'setting' : self.setting} # check cookies and find user cookies = parse_cookie(self.request.headers.get("Cookie", "")) self.session_key = cookies.get('bitsable-session-key', None) self.user = None if self.session_key is not None and len(self.session_key) == 40: logging.info("session_key:%s" % self.session_key) self.user = Session.get_user_by_session(self.session_key) self.template_value['user'] = self.user
def library_content_html(): # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() all_playlists = [] dict_videos = {} dict_videos_counted = {} dict_playlists = {} dict_playlists_by_title = {} dict_video_playlists = {} async_queries = [ Video.all(), Playlist.all(), VideoPlaylist.all().filter('live_association = ', True).order('video_position'), ] results = util.async_queries(async_queries) for video in results[0].get_result(): dict_videos[video.key()] = video for playlist in results[1].get_result(): dict_playlists[playlist.key()] = playlist if playlist.title in topics_list: dict_playlists_by_title[playlist.title] = playlist for video_playlist in results[2].get_result(): playlist_key = VideoPlaylist.playlist.get_value_for_datastore(video_playlist) video_key = VideoPlaylist.video.get_value_for_datastore(video_playlist) if dict_videos.has_key(video_key) and dict_playlists.has_key(playlist_key): video = dict_videos[video_key] playlist = dict_playlists[playlist_key] fast_video_playlist_dict = {"video":video, "playlist":playlist} if dict_video_playlists.has_key(playlist_key): dict_video_playlists[playlist_key].append(fast_video_playlist_dict) else: dict_video_playlists[playlist_key] = [fast_video_playlist_dict] if dict_playlists_by_title.has_key(playlist.title): # Only count videos in topics_list dict_videos_counted[video.youtube_id] = True # Update count of all distinct videos associated w/ a live playlist Setting.count_videos(len(dict_videos_counted.keys())) for topic in topics_list: if topic in dict_playlists_by_title: playlist = dict_playlists_by_title[topic] playlist_key = playlist.key() playlist_videos = dict_video_playlists.get(playlist_key) or [] if not playlist_videos: logging.error('Playlist %s has no videos!', playlist.title) playlist_data = { 'title': topic, 'topic': topic, 'playlist': playlist, 'videos': playlist_videos, 'next': None } all_playlists.append(playlist_data) playlist_data_prev = None for playlist_data in all_playlists: if playlist_data_prev: playlist_data_prev['next'] = playlist_data playlist_data_prev = playlist_data # Separating out the columns because the formatting is a little different on each column template_values = { 'App' : App, 'all_playlists': all_playlists, 'smart_history': smart_history, } html = shared_jinja.get().render_template("library_content_template.html", **template_values) # Set shared date of last generated content Setting.cached_library_content_date(str(datetime.datetime.now())) return html
@layer_cache.cache(layer=layer_cache.Layers.Memcache | layer_cache.Layers.Datastore, expiration=86400) def getSmartHistoryContent(): request = urllib2.Request("http://smarthistory.org/khan-home.html") try: response = urllib2.urlopen(request) smart_history = response.read() smart_history = re.search(re.compile("<body>(.*)</body>", re.S), smart_history).group(1).decode("utf-8") smart_history.replace("script", "") except Exception, e: logging.exception("Failed fetching smarthistory playlist") smart_history = None pass return smart_history @layer_cache.cache_with_key_fxn( lambda *args, **kwargs: "library_content_html_%s" % Setting.cached_library_content_date() ) def library_content_html(): # No cache found -- regenerate HTML smart_history = getSmartHistoryContent() all_playlists = [] dict_videos = {} dict_videos_counted = {} dict_playlists = {} dict_playlists_by_title = {} dict_video_playlists = {} async_queries = [ Video.all(),
user_data = UserData.get_for_current_user() logout_url = users.create_logout_url(self.request.uri) template_values = qa.add_template_values({'App': App, 'points': user_data.points, 'username': user and user.nickname() or "", 'login_url': util.create_login_url(self.request.uri), 'student_email' : self.request.get('student_email'), 'logout_url': logout_url}, self.request) path = os.path.join(os.path.dirname(__file__), 'import.html') self.response.out.write(template.render(path, template_values)) @layer_cache.cache_with_key("playlists_%s" % Setting.cached_library_content_date()) def get_playlists(): playlists = [] for playlist_title in all_topics_list: query = Playlist.all() query.filter('title =', playlist_title) playlist = query.get() playlist_dict = {'youtube_id': playlist.youtube_id, 'youtube_url': playlist.url, 'title': playlist.title, 'description': playlist.description, 'api_url': "http://www.khanacademy.org/api/playlistvideos?playlist=%s" % (urllib.quote_plus(playlist_title)), } playlists.append(playlist_dict) return json.dumps(playlists, indent=4)