Esempio n. 1
0
 def get(self):
     SETTING_NAMES = ('recaptcha_public',
                     'recaptcha_private',
                     'disabled_contributions'
                     )
     data = {
         "SERVER_NAME" : self.request.environ["SERVER_NAME"]
     }
     
     if self.request.get('save'):
         for name in SETTING_NAMES:
             Setting.save(name, self.request.get(name) or '')
     
     for name in SETTING_NAMES:
         data[name] = Setting.get(name, '')
         
     # We are using the template module to output the page.
 
     path = os.path.join(os.path.dirname(__file__), '../views' ,'admin/settings.html')
     self.response.out.write(
     
         # The render method takes the path to a html template,
         # and a dictionary of key/value pairs that will be
         # embedded in the page.
         
         template.render( path, data))
Esempio n. 2
0
    def post(self):
        json_data = request.get_json()
        current_user = get_jwt_identity()
        data = []
        for item in json_data:
            try:
                setting = setting_schema.load(data=item)
                data.append(setting)
            except ValidationError as errors:
                return {'message': 'Validation errors', 'errors': errors.messages}, HTTPStatus.BAD_REQUEST

        settings = Setting.get_by_user(current_user)
        if settings is None:
            settings = []

        update_settings = []
        m = {item.key: item for item in settings}
        for item in data:
            key = item['key']
            value = item['value']
            if key in m:
                setting = m[key]
                setting.value = value
            else:
                setting = Setting(key=key, value=value, user_id=current_user)
            update_settings.append(setting)

        Setting.save(update_settings)

        return setting_list_schema.dump(settings), HTTPStatus.CREATED
Esempio n. 3
0
    def last_settings():
        settings = Setting()

        return Response(json.dumps(
            settings.all(section=request.args.get('name')),
            default=json_util.default),
                        mimetype='application/json')
Esempio n. 4
0
    def store(
        data
    ):  ## TODO: Data viene de request.get_json(), se puede obtener auqí mismo
        setting = Setting()
        res_data = setting.store(data)

        if res_data is None:
            response = Response(json.dumps({'error': 'Item not added - {}'}),
                                status=400,
                                mimetype='application/json')
            return response

        return Response(json.dumps(res_data, default=json_util.default),
                        status=201,
                        mimetype='application/json')
Esempio n. 5
0
def delete_settings():
    form = UpdateSettingForm(request.args)
    if not form.validate():
        return form.errors, 400
    setting = Setting.objects().first()
    if setting is None:
        return jsonify(ok=False, msg="system setting is uninitialized")

    attribute = [
        "departments", "positions", "shield_types", "splice_types",
        "interface_protocol"
    ]
    index = form.nameString.index(form.name.data)

    if form.value.data in setting.__getattribute__(attribute[index]):
        field = ["department", "position", "shield_type", "type", "protocol"]
        documents = [User, User, Cable, Interface, Interface]

        count = len(
            documents[index].objects(**{field[index]: form.value.data}))
        if count:
            return jsonify(ok=False, msg=count)
        setting.__getattribute__(attribute[index]).remove(form.value.data)
        setting.update_user = current_user.id
        setting.save()
        return jsonify(ok=True, msg="success")
    return jsonify(ok=False, msg="not found"), 404
Esempio n. 6
0
    def get(self):
        current_user = get_jwt_identity()
        settings = Setting.get_by_user(current_user)
        if settings is None:
            return {'message': 'settings not found'}, HTTPStatus.NOT_FOUND

        result = setting_list_schema.dump(settings)
        return result, HTTPStatus.OK
Esempio n. 7
0
def hello_world():
    setting = Setting()
    post = Post()
    user = User()
    settings = setting.all()

    settings_formatted = {}

    for element in settings:
        settings_formatted[element.get('name')] = element.get('data').get('es')

    latest_ten_posts = post.all(q='sngularrocks')
    users = user.top_users()

    return render_template('index.html',
                           setting=settings_formatted,
                           posts=latest_ten_posts,
                           users=users)
Esempio n. 8
0
 def get(self):
     
     result = dict()
     
     disabled_contributions = Setting.get("disabled_contributions", False)
     
     if disabled_contributions:
         result["error"] = disabled_contributions
     
     else:
             
         name = uuid.uuid4().hex
         title = self.request.get('title')
         link = self.request.get('link')
         have = self.request.get('have')
         dont = self.request.get('dont')
         missing = self.request.get('missing')
         match_isbn = self.request.get('match_isbn')
         
         logging.debug("LibraryTestContributionHandler: %s" % (title,))
 
         existingLib = Library.find(title)
         
         if existingLib:
             result["existing"] = existingLib.toDict()
             logging.debug("Found Existing")
         else:
             logging.debug("Does not exist")
         
         try:
             lib = Library(name = name,
                     title = title,
                     link = link,
                     have = have,
                     dont = dont)
                     
             if match_isbn != '':
                 lib.match_isbn = True
             else:
                 lib.missing = missing
                 
             result["haveUrl"] = lib.siteUrl(have)
             result["dontUrl"] = lib.siteUrl(dont)
             result["library"] = lib.toDict()
             if not isbn.isValid(have):
                 raise Exception("Existing Book ISBN '%s' is not a valid!" % (have,))
             if not isbn.isValid(dont):
                 raise Exception("Missing Book ISBN '%s' is not a valid!" % (dont,))
             lib.validateLink()
             result["have"] = lib.process(have)
             result["dont"] = lib.process(dont)
             
         except Exception, ex:
             result["error"] = "%s" % (ex,)
Esempio n. 9
0
def get_settings():
    setting = Setting.objects().first()
    if setting is None:
        setting = Setting()
        setting.update_user = current_user.id
        setting.save()
    return setting
Esempio n. 10
0
 def up(worker_id):
     config = Providers.config()
     service = config.launch_service
     if service:
         task = Task()
         task.user_id = 0  # TODO: Create real users
         task.setting_id = Setting.get_default().id
         task.worker_id = worker_id
         task.is_enabled = True
         task.service_name = service
         task.params = Tasks.get_params(service)
         task.start_at = time.time()
         task.save()
Esempio n. 11
0
    def _load_settings(self):
        cursor = self.sqlconn.cursor(pymysql.cursors.DictCursor)

        cursor.execute('SELECT * FROM `tb_settings`')

        self.settings = {}

        for row in cursor:
            self.settings[row['setting']] = Setting.parse(row['type'], row['value'])
            if self.settings[row['setting']] is None:
                log.error('ERROR LOADING SETTING {0}'.format(row['setting']))

        for setting in self.default_settings:
            if setting not in self.settings:
                self.settings[setting] = self.default_settings[setting]

        cursor.close()
Esempio n. 12
0
def update_settings():
    form = UpdateSettingForm(request.form)
    if not form.validate():
        return form.errors, 400
    setting = Setting.objects().first()
    if setting is None:
        return jsonify(ok=False, msg="system setting is uninitialized")

    attribute = [
        "departments", "positions", "shield_types", "splice_types",
        "interface_protocol"
    ]
    index = form.nameString.index(form.name.data)
    if form.value.data in setting.__getattribute__(attribute[index]):
        return form.errors
    setting.__getattribute__(attribute[index]).append(form.value.data)
    setting.update_user = current_user.id

    setting.save()
    return jsonify(ok=True, msg="success")
Esempio n. 13
0
 def set_comunication_channel_id(comunication_channel_id):
     Setting.set_comunication_channel_id(comunication_channel_id)
Esempio n. 14
0
 def up():
     if Setting.get_count() == 0:
         instrument = Instrument.get_instrument_by_name("EUR_USD")
         if not instrument:
             InstrumentsFixture.up()
         model = Setting()
         model.user_id = 0  # TODO: Create real users
         model.name = "Default"
         model.is_default = True,
         model.created_at = time.time()
         model.updated_at = time.time()
         model.instrument_id = instrument.id
         model.candles_durations = json.dumps([180])
         model.analyzer_working_interval_sec = 5
         model.analyzer_collect_interval_sec = 1
         model.analyzer_bid_times = json.dumps([
             {
                 "time": 300,
                 "admission": 60
             },
         ]),
         model.analyzer_deep = 5
         model.analyzer_min_deep = 5
         model.analyzer_patterns_control = json.dumps([{
             "expire":
             0,
             "sequence_min_duration":
             1,
             "min_work_time":
             0
         }]),
         model.analyzer_candles_parent_relation = "parent"
         model.analyzer_expiry_time_bid_divider = 5
         model.analyzer_capacity_granularity = 1
         model.analyzer_capacity_type = "change"  # "change","potential"
         model.signaler_min_chance = 80
         model.signaler_min_repeats = 3
         model.signaler_delay_on_trend = 0
         model.signaler_put_max_change_cost = 0
         model.signaler_call_max_change_cost = 0
         model.signaler_min_ticks_count = 0
         model.signaler_trend_chance = 0
         model.save()
Esempio n. 15
0
def import_users(task_id):
    task = Task.objects(id=task_id).first()
    if task is None:
        return

    task.status = Task.STATUS_RUNNING
    task.save()

    wb = load_workbook(task.file.path)

    """计算需要导入用户的总数"""
    sheets = wb.sheetnames
    user_count = 0
    for sheet in sheets:
        ws = wb[sheet]
        user_count += ws.max_row - 1

    """缓存当前导入进度,用于前端调用接口获取"""
    storage_key = str(task_id)
    storage = task_status_storage[storage_key] = {
        'success': 0,
        'failed': 0,
        'total': user_count
    }

    settings = Setting.objects().first()
    if settings is None:
        settings = Setting()
        settings.save()

    failed_record = []
    for user, meta in load_users(wb, sheets):
        user.password = '******'
        if user.department not in settings.departments:
            settings.update(add_to_set__departments=user.department)
            settings.reload()
        if user.position not in settings.positions:
            settings.update(add_to_set__positions=user.position)
            settings.reload()
        try:
            user.save()
            storage['success'] += 1
        except NotUniqueError:
            storage['failed'] += 1
            meta['msg'] = '该邮箱已被注册'
            failed_record.append(meta)
        except Exception as error:
            storage['failed'] += 1
            meta['msg'] = error.errors
            failed_record.append(meta)

    wb.close()

    task.status = Task.STATUS_COMPLETED
    task.result = {
        'success': storage['success'],
        'failed': storage['failed'],
        'failed_record': failed_record,
        'total': storage['total']
    }
    task.save()
    task_status_storage.pop(storage_key)
    remove(task.file.path)
Esempio n. 16
0
    def get(self):
    
        # We are using the template module to output the page.
        disabled_contributions = Setting.get("disabled_contributions", False)
        data = {
            "admin_user": users.is_current_user_admin(),
            "disabled_contributions" : disabled_contributions,
            }
        debug = ''
        error = None
        preview = False

        if not disabled_contributions:

            try:
            
                for field in ["title", "link", "have", "dont"]:
                    data[field] = self.request.get(field)
                
                if not data["title"] and not data["link"]:
                    data["title"] = "DC - Library of Congress"
                    data["link"] = "http://www.loc.gov/search/?q=#{ISBN}&fa=digitized:false"
                    data["missing"] = "We did not find any matches for this search."
                    data["have"] = "0321337220"
                    data["dont"] = "0373691122"
                
                else:
                
                    if self.request.get("missing"):
                        data["missing"] = self.request.get("missing")
                    else:
                        data["match_isbn"] = True
                
                data["name"] = uuid.uuid4().hex
                data["is_community"] = True

                preview = self.request.get('preview')
                save = self.request.get('save')
            
                if save:
        
                    preview = True
        
                    challenge = self.request.get('recaptcha_challenge_field')
                    response  = self.request.get('recaptcha_response_field')
                    remoteip  = self.request.environ['REMOTE_ADDR']
                    
                    cResponse = captcha.submit(
                                 challenge,
                                 response,
                                 Setting.get("recaptcha_private", ''),
                                 remoteip)
                    if not cResponse.is_valid:
                        raise Exception("reCaptcha verification failed (" + cResponse.error_code + ")")
        
                    existingLib = Library.find(data["title"])
                                    
                    if existingLib:
                        raise Exception("Another library with this title already exists!")
                        
                    if not isbn.isValid(data["have"]):
                        raise Exception("Existing Book: '%s' is not a valid ISBN!" % (data["have"]))
                    if not isbn.isValid(data["dont"]):
                        raise Exception("Missing Book: '%s' is not a valid ISBN!" % (data["dont"]))
        
                    lib = Library.create(data)
                        
                    problems = lib.validate()
                    if problems:
                        raise Exception("Library didn't validate: " + problems)
                        
                    lib.remote_ip = remoteip
                    
                    lib.put()
                    
                    data["success"] = "Library '%s' was successfuly saved.\nThank you for your contribution." % (data["title"])
                
                if preview:
                    lib = Library.create(data)
                    data["haveUrl"] = lib.siteUrl(data["have"])
                    data["dontUrl"] = lib.siteUrl(data["dont"])
                else:
                    data["library_count"] = Library.count_all()
        
            except Exception, ex:
                error = "%s" % (ex,)
Esempio n. 17
0
 def setting(self):
     if not self._setting:
         self._setting = Setting.get_by_id(self.setting_id)
     return self._setting
Esempio n. 18
0
import os
import streamlit as st
from models import Menu
from models.setting import Setting

from views import SettingView
from views import DashboardView

if __name__ == "__main__":
    setting = Setting()

    st.sidebar.markdown("# Menu")
    view = st.sidebar.selectbox("Select Menu", Menu.get_menus())

    if not setting and view != Menu.SETTING.name:
        st.title('Welcome to BacklogBI')
        st.write(
            'Please select setting from side menu and input your settings!')
    elif view == Menu.DASHBOARD.name:
        d = DashboardView(setting)
        d.run()
    elif view == Menu.SETTING.name:
        s = SettingView(setting)
        s.run()
Esempio n. 19
0
async def levelup_notification(user_id):
        name = User.get_name(user_id)
        level = User.get_level(user_id)
        await Bot.send_message(Setting.get_comunication_channel_id(), user_id, ' hai completato il livello ' + str(level) + '!')
Esempio n. 20
0
 def __init__(self, **kwargs):
     self.headers = DV.HEADERS
     self.url = DV.URL + 'settings'
     self.body = Setting(**kwargs).do_dict()