Exemplo n.º 1
0
    def search(self, env):
        search_vars = var_parse(request.query)
        if 'key' in search_vars:
            try:
                data = Searcher(self.cfg, self.db).search(search_vars)

                results = {-2: [], -1: [], 0: [], 1: [], 2: [], 3: [], 4: []}
                for f in data['results']['data']:
                    if f.file_isdir:
                        results[-2].append(f)
                    else:
                        results[f.file_format].append(f)

                results[-1] = data['results']['data']

                data['results']['data'] = results

                return jinja2_template('main/search_results',
                                       env=env,
                                       data=data,
                                       exception=None)
            except SearchException as ex:
                return jinja2_template('main/search', env=env, message=str(ex))
            except Exception as ex:
                return jinja2_template('main/search',
                                       env=env,
                                       message='Something went wrong \:D/')

        return jinja2_template('main/search', env=env, message='')
Exemplo n.º 2
0
def edit_source(path, db):
    """Only admin users can see this"""
    aaa.require(role='admin', fail_redirect='/404')

    name = None
    action = None

    if '/' in path:
        spl = path.split('/')
        name = spl[0]
        action = spl[1]
    else:
        name = path

    source = db.query(Source).filter_by(name=name).first()

    if action:
        if action == 'crawl' and source:
            return jinja2_template('source_crawl.html',
                title='Admin',
                source_name = name,
                path=path,
                navigation=gen_navigation(admin=True),
                breadcrumbs=gen_breadcrumps('/sources/edit/' + name + '/crawl', 'admin/', lastslash=False, capitalize=True)
            )
        else:
            return redirect('/admin/sources')

    return jinja2_template('source_edit.html',
        title='Admin',
        path=path,
        navigation=gen_navigation(admin=True),
        breadcrumbs=gen_breadcrumps('/sources/edit/', 'admin/', lastslash=False, capitalize=True),
        source=source
    )
Exemplo n.º 3
0
def selectReadings(sessionID=None):
    respData = MultiDict(url=url, title='Blood Glucose', sessionID=sessionID)
    if sessionID is None or not Sessions.ifSessionExistsInDB(sessionID):
        return jinja2_template('Home.jinja2', respData, template_lookup=['templates'])
    Sessions.putSessionValueInDB(sessionID, 'sessionIDtoSelect', sessionID)

    if not Sessions.getSessionValueFromDB(sessionID, 'isSignedOn'):
        return jinja2_template('Signon.jinja2', respData, template_lookup=['templates'])

    with db_session:
        heldReadings = Readings.select(lambda c: c.am is not None and c.pm is None).order_by(1)
        heldReadingsList = list(heldReadings)
    numberOfHeldReadings = len(heldReadingsList)
    respData.update(MultiDict(numberOfHeldReadings=numberOfHeldReadings))
    if numberOfHeldReadings > 0:
        heldReadingDates = []
        index = 1
        for heldReading in heldReadingsList:
            heldReadingDates.append((f'D{index}', heldReading.date))
            index += 1

        respData.update(MultiDict(heldReadingDates=heldReadingDates))
        respData.update(MultiDict(heldData=None))
        return jinja2_template('SelectReading.jinja2', respData, template_lookup=['templates'])
    else:
        return jinja2_template('NoneHeld.jinja2', respData, template_lookup=['templates'])
Exemplo n.º 4
0
def do_files():
    s = bottle.request.environ.get('beaker.session')
    if 'username' not in s:
        redirect('/login')
    username = s['username']
    key_name = request.forms.get('keyName')
    test_client = client.Client(NCRYPTIFY_ID, NCRYPTIFY_SECRET, ISSUER, 5, username)

    operation = 'hide'
    if 'unhide' in request.forms:
        operation = 'unhide'

    file = request.files
    user_file = file.get('userFile')
    if user_file is None:
        error_msg = 'Unable to get file name'
        return jinja2_template('error.html', error_message=error_msg)

    filename = user_file.filename
    name, ext = os.path.splitext(filename)
    if operation == 'hide':
        target_filename = name + '-ffenc'
    else:
        target_filename = name[:-len('-ffenc')]

    if ext and ext != '':
        target_filename += ext

    if not os.path.exists(SAVE_PATH):
        os.makedirs(SAVE_PATH)

    file_path = "{path}/{file}".format(path=SAVE_PATH, file=filename)
    target_file_path = "{path}/{file}".format(path=SAVE_PATH, file=target_filename)

    if operation == 'hide':
        data_blocks = []
        byte_count = 0

        buf = user_file.file.read(BUF_SIZE)
        while buf:
            byte_count += len(buf)
            if byte_count > MAX_SIZE:
                return jinja2_template('error.html', error_message='Request entity too large (max: 5MB)')
            data_blocks.append(buf)
            buf = user_file.file.read(BUF_SIZE)
        data = ''.join(data_blocks)

        # Save file
        with open(file_path, 'wb') as open_file:
            open_file.write(data)
            open_file.close()

    # Handle exception
    try:
        if operation == 'hide':
            test_client.encrypt_file(key_name, file_path, target_file_path)
        else:
            test_client.decrypt_file(file_path, target_file_path)
    except Exception, e:
        return str(e)
Exemplo n.º 5
0
    def browse(self, path, env):
        env['load_dbtime'] = 0

        browser = Browser(db=self.db)
        try:
            browser.parse_incoming_path(path)

            start_dbtime = datetime.now()
            browser.fetch_files()
            env['load_dbtime'] = (datetime.now() -
                                  start_dbtime).total_seconds()

            browser.prepare_files()

            data = {
                'files': browser.files,
                'breadcrumbs': browser.breadcrumbs(),
                'action_fetches': browser.generate_action_fetches(),
                'env': browser.env
            }

            return jinja2_template('main/browse_dir', env=env, data=data)
        except Exception as ex:
            return jinja2_template('main/error',
                                   env=env,
                                   data={'error': 'no files were found'})

        return ''
Exemplo n.º 6
0
    def browse(self, path, env):
        env['load_dbtime'] = 0

        browser = Browser(db=self.db)
        try:
            browser.parse_incoming_path(path)

            start_dbtime = datetime.now()
            browser.fetch_files()
            env['load_dbtime'] = (datetime.now() - start_dbtime).total_seconds()

            browser.prepare_files()

            data = {
                'files': browser.files,
                'breadcrumbs': browser.breadcrumbs(),
                'action_fetches': browser.generate_action_fetches(),
                'env': browser.env
            }

            return jinja2_template('main/browse_dir', env=env, data=data)
        except Exception as ex:
            return jinja2_template('main/error', env=env, data={
                'error': 'no files were found'
            })

        return ''
Exemplo n.º 7
0
Arquivo: paste.py Projeto: ngx/pbin
def submit_new(conf, cache):
    '''
    Handle processing for a new paste.
    '''
    paste_data = {
        'code': bottle.request.POST.get('code', ''),
        'name': bottle.request.POST.get('name', '').strip(),
        'phone': bottle.request.POST.get('phone', '').strip(),
        'private': bottle.request.POST.get('private', '0').strip(),
        'syntax': bottle.request.POST.get('syntax', '').strip(),
        'forked_from': bottle.request.POST.get('forked_from', '').strip(),
        'webform': bottle.request.POST.get('webform', '').strip(),
        'origin_addr': bottle.request.environ.get('REMOTE_ADDR', 'undef').strip(),
        'recaptcha_answer': bottle.request.POST.get('g-recaptcha-response', '').strip()}
    cli_post = True if paste_data['webform'] == '' else False

    # Handle file uploads
    if type(paste_data['code']) == bottle.FileUpload:
        paste_data['code'] = '# FileUpload: {}\n{}'.format(
                paste_data['code'].filename,
                paste_data['code'].file.getvalue())

    # Validate data
    (valid, err) = sanity.validate_data(conf, paste_data)
    if not valid:
        return bottle.jinja2_template('error.html', code=200, message=err)

    # Check recapcha answer if not cli post
    if utils.str2bool(conf.get('bottle', 'check_spam')) and not cli_post:
        if not sanity.check_captcha(
                conf.get('bottle', 'recaptcha_secret'),
                paste_data['recaptcha_answer']):
            return bottle.jinja2_template('error.html', code=200, message='Invalid captcha verification. ERR:677')

    # Check address against blacklist
    if sanity.address_blacklisted(cache, paste_data['origin_addr']):
        return bottle.jinja2_template('error.html', code=200, message='Address blacklisted. ERR:840')

    # Stick paste into cache
    paste_id = _write_paste(cache, paste_data)

    # Set cookie for user
    bottle.response.set_cookie(
            'dat',
            json.dumps({
                'name': str(paste_data['name']),
                'syntax': str(paste_data['syntax']),
                'private': str(paste_data['private'])}))

    # Send user to page, or a link to page
    if cli_post:
        scheme = bottle.request.environ.get('REQUEST_SCHEME')
        host = bottle.request.get_header('host')
        return '{}://{}/{}\n'.format(scheme, host, paste_id)
    else:
        # Relay message to IRC
        if utils.str2bool(conf.get('bottle', 'relay_enabled')) and not sanity.address_greylisted(cache, paste_data['origin_addr']):
            irc.send_message(conf, cache, paste_data, paste_id)
        bottle.redirect('/' + paste_id)
Exemplo n.º 8
0
def login():
    if NCRYPTIFY_ID == None or NCRYPTIFY_ID == '' or NCRYPTIFY_SECRET == None or NCRYPTIFY_SECRET == '':
        error_msg = '''<p>Environment variables must be set before running the application:</p>
                       <p><b>NCRYPTIFY_ID</b> - an application ID, <b>NCRYPTIFY_SECRET</b> - secret</p>
                       <p>which can be created and obtained from the nCryptify Developer Portal</p>
                    '''
        return jinja2_template('error.html', error_message=error_msg)
    return jinja2_template('index.html')
Exemplo n.º 9
0
Arquivo: app.py Projeto: aes512/pbin
def submit_paste():
    '''
    Put a new paste into the database
    '''
    r = re.compile('^[- !$%^&*()_+|~=`{}\[\]:";\'<>?,.\/a-zA-Z0-9]{1,48}$')
    paste = {
        #'code': bottle.request.POST.get('code', '').strip(),
        'code': bottle.request.POST.get('code', ''),
        'title': bottle.request.POST.get('title', '').strip(),
        'name': bottle.request.POST.get('name', '').strip(),
        'private': bottle.request.POST.get('private', '0').strip(),
        'syntax': bottle.request.POST.get('syntax', '').strip(),
        'forked_from': bottle.request.POST.get('forked_from', '').strip()}

    # Validate data
    if max(0, bottle.request.content_length) > bottle.request.MEMFILE_MAX:
        return bottle.jinja2_template('error.html', code=200, message='This request is too large to process.')
    for k in ['code', 'private', 'syntax', 'title', 'name']:
        if paste[k] == '':
            return bottle.jinja2_template('error.html', code=200, message='All fields need to be filled out.')
    for k in ['title', 'name']:
        if not r.match(paste[k]):
            return bottle.jinja2_template('error.html', code=200, message='Invalid input detected.')

    # Check post for spam
    if bottle.request.POST.get('phone', '').strip() != '':
        return bottle.jinja2_template('error.html', code=200, message='Your post triggered our spam filters!')
    if str2bool(conf.get('bottle', 'check_spam')):
        if not spam_free(paste['code']):
            return bottle.jinja2_template('error.html', code=200, message='Your post triggered our spam filters!')

    # Public pastes should have an easy to type key
    # Private pastes should have a more secure key
    id_length = 1
    if str2bool(paste['private']):
        id_length = 8

    # Pick a unique ID
    paste_id = binascii.b2a_hex(os.urandom(id_length))

    # Make sure it's actually unique or else create a new one and test again
    while cache.exists(paste_id):
        id_length += 1
        paste_id = binascii.b2a_hex(os.urandom(id_length))

    cache.set(paste_id, json.dumps(paste))
    cache.expire(paste_id, 345600)

    dat = {
      'name': str(paste['name']),
      'syntax': str(paste['syntax']),
      'private': str(paste['private'])}
    bottle.response.set_cookie('dat', json.dumps(dat))

    if str2bool(conf.get('bottle', 'relay_enabled')):
        send_irc(paste, paste_id)

    bottle.redirect('/' + paste_id)
Exemplo n.º 10
0
def signon(sessionID):
    numberOfHeldReadings=numberOfPartials()
    Sessions.putSessionValueInDB(sessionID, "numberOfHeldReadings", numberOfHeldReadings)
    respData = MultiDict(url=url, title='Blood Glucose', sessionID=sessionID)
    respData.update(MultiDict(numberOfHeldReadings=numberOfHeldReadings))
    if Sessions.getSessionValueFromDB(sessionID, 'isSignedOn'):
        return jinja2_template('Admin.jinja2', respData, template_lookup=['templates'])
    else:
        return jinja2_template('Signon.jinja2', respData, template_lookup=['templates'])
Exemplo n.º 11
0
Arquivo: app.py Projeto: ngx/pbin
def view_diff(orig, fork):
    '''
    View the diff between a paste and what it was forked from
    '''
    if not cache.exists('paste:' + orig) or not cache.exists('paste:' + fork):
        return bottle.jinja2_template('error.html', code=200,
                                      message='At least one paste could not be found.')

    diff = paste.gen_diff(cache, orig, fork)
    return bottle.jinja2_template('page.html', data=diff)
Exemplo n.º 12
0
def jobs_new():
    job_type = bottle.request.query.get('type')
    if Job.is_valid_type(job_type):
        form_cls = CreateJobController.forms[job_type]
        form = form_cls()

        return bottle.jinja2_template('job_{0}.html'.format(job_type.lower()),
                                      form=form,
                                      job_type=job_type)

    return bottle.jinja2_template('job_wizard.html')
Exemplo n.º 13
0
def enter(sessionID):
    sessionID = Sessions.initializeSession(sessionID, request, response)
    respData = MultiDict(url=url, title='Blood Glucose')
    isSignedOn = Sessions.getSessionValueFromDB(sessionID, 'isSignedOn')
    respData.update(MultiDict(sessionID=sessionID, numberOfHeldReadings=numberOfPartials()))
    respData.update(MultiDict(dbFileName=dbFileName))
    if isSignedOn:
        with db_session:
            maxReadingDate = max(r.date for r in Readings)
        respData.update(MultiDict(maxDate=maxReadingDate))
        return jinja2_template('EnterReading.jinja2', respData, template_lookup=['templates'])
    else:
        return jinja2_template('Signon.jinja2', respData,  template_lookup=['templates'])
Exemplo n.º 14
0
def adminCommon(request, response, sessionID=None):
    Sessions.purgeOldSessions()
    sessionID = Sessions.initializeSession(sessionID, request, response)
    Sessions.putSessionValueInDB(sessionID, 'currentDB', str(dbPath))
    respData = MultiDict(url=url, title='Blood Glucose', sessionID=sessionID)
    respData.update(MultiDict(numberOfHeldReadings=numberOfPartials()))
    isSignedOn = Sessions.getSessionValueFromDB(sessionID, 'isSignedOn')
    if isSignedOn:
        template = jinja2_template('Admin.jinja2', respData, template_lookup=['templates'])
    else:
        template = jinja2_template('Signon.jinja2', respData, template_lookup=['templates'])
    log('adminCommon', 'made new session', sessionID=sessionID)
    return template
Exemplo n.º 15
0
def signonPost():
    sessionID = request.forms.sessionID
    if isNone(sessionID):
        sessionID = HTTPCookie.getSessionCookie(request)
    syscode = System.getCode()
    formcode = request.forms.get('code')
    isSignedOn = verify_password(syscode, formcode)
    Sessions.putSessionValueInDB(sessionID, 'isSignedOn', isSignedOn)
    respData = MultiDict(url=url, title='Blood Glucose', sessionID=sessionID)
    respData.update(MultiDict(numberOfHeldReadings=numberOfPartials()))
    if isSignedOn:
        return jinja2_template('Admin.jinja2', respData, template_lookup=['templates'])
    else:
        respData.update(MultiDict(tryAgain=True))
        return jinja2_template('Signon.jinja2', respData, template_lookup=['templates'])
Exemplo n.º 16
0
def _generate_mapcache_config(gene, version):
    for layer in gene.layers.values():
        if layer["type"] == "wms" or "wms_url" in layer:
            params = {}
            params.update(layer.get("params", {}))
            if "FORMAT" not in params:
                params["FORMAT"] = layer["mime_type"]
            if "LAYERS" not in layer.get("params", {}):
                params["LAYERS"] = layer["layers"]
            if "TRANSPARENT" not in layer.get("params", {}):
                params["TRANSPARENT"] = "TRUE" if layer["mime_type"] == "image/png" else "FALSE"
            layer["params"] = params

    config = jinja2_template(
        pkgutil.get_data("tilecloud_chain", "mapcache_config.jinja").decode("utf-8"),
        layers=gene.layers,
        grids=gene.grids,
        mapcache=gene.config["mapcache"],
        version=version,
        min=min,
        len=len,
        sorted=sorted,
    )

    with open(gene.config["mapcache"]["config_file"], "w") as f:
        f.write(config)
Exemplo n.º 17
0
def dashboard_handler(db):
    schema_data = db.api_view

    schema_root = {
        "namespaces_count": len(set([i['api_namespace'] for i in schema_data])),
        "schemas": sorted(list(set([i['api_namespace'] for i in schema_data]))),
        "namespaces": []
    }

    for schema in set([i['api_namespace'] for i in schema_data]):
        schema_views = [d for d in schema_data
                        if d['api_namespace'] == schema and
                        d['api_type'] == 'view']
        schema_udf = [d for d in schema_data
                        if d['api_namespace'] == schema and
                        d['api_type'] == 'UDF']
        schema_info = {
            "name": schema,
            "functions": [{'name': i['api_name'], 'uri': i['api_endpoint'],
                     'args': i['api_params'] or [], 'desc': i['api_desc']} for i in schema_udf],
            "views": [{'name': i['api_name'], 'uri': i['api_endpoint'],
                     'args': i['api_params'] or [], 'desc': i['api_desc']} for i in schema_views]
        }
        # schema_info['json_data'] = simplejson.dumps(schema_info)
        schema_root["namespaces"].append(schema_info)
    return bottle.jinja2_template('app.html', {'JSDATA': simplejson.dumps(schema_root["namespaces"])})
Exemplo n.º 18
0
def formtest():
    if request.method == 'POST':
        name = request.forms.get('name')
        age = request.forms.get('age')
        return jinja2_template('form_result.html', {'name': name, 'age': age})
    else:
        return static_file('form.html', root='G:/python_pj/templates/')
Exemplo n.º 19
0
def manage_user(page = 1):
    """
        查看用户信息
    """
    log.info("manage_user")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    users = list(db.user.find())
    paginator = Paginator(users,10,0)
    try:
        users = paginator.page(page)
    except (EmptyPage, InvalidPage):
        users = paginator.page(paginator.num_pages)
    page_range,num_pages = paginator.page_range,paginator.num_pages
    show_firstpage = False if int(page) == 1 else True
    show_lastpage = False if int(page) == num_pages else True
    show_pages = 5
    if num_pages <= show_pages:#当数量不足时
        newpage_range = page_range
    else:
        newpage_range = list()
        if int(page) + show_pages > num_pages:#用于显示后几位
            for pagenum in range(num_pages - show_pages + 1,num_pages + 1):
                newpage_range.append(pagenum)
        else:
            for pagenum in range(int(page),int(page)+show_pages):
                newpage_range.append(pagenum)

    return jinja2_template('manage-user.html',user = user,app = chermongapp,
        users = users,show_firstpage=show_firstpage,show_lastpage=show_lastpage,
        num_pages=num_pages,page_range=newpage_range)
Exemplo n.º 20
0
Arquivo: app.py Projeto: ngx/ngxcc
def view_page(filename):
    '''
    Returns a page identified by its name and type
    '''
    if not os.path.exists('data/{}'.format(filename)):
        bottle.abort(404, 'The page you requested does not exist')

    hash_key = sha1(filename + time.ctime(os.path.getmtime('data/{}'.format(filename)))).hexdigest()
    data = cache.get(hash_key)

    if not data:
        try:
            source_file = codecs.open('data/{}'.format(filename), 'r', encoding='utf8')
            text = source_file.readlines()
            source_file.close()
        except IOError:
            bottle.abort(404, 'The page you requested does not exist')
        text = markdown(''.join(text))
        page = bottle.jinja2_template('page.html', text=text)

        cache.set(hash_key, json.dumps(page))
        cache.expire(hash_key, 604800)
    else:
        page = json.loads(data)
   
    return page
Exemplo n.º 21
0
def edit(page = 1):
    """
        进行互评
    """
    log.info("edit")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    schoolid,option = request.query.get('schoolid'),request.query.get('option')
    db.assessment.update({'schoolid':user['schoolid'],"pro-others.schoolid":schoolid},{"$set":{"pro-others.$.option":option}})
    pro_others = list(db.assessment.find_one({'schoolid':user['schoolid']},fields = ['pro-others'])['pro-others'])
    options = list(db.options.find())#因为返回的是一个类似的list的cursor,但是它只能循环一次,所以将它转换为list
    
    paginator = Paginator(pro_others,10,0)
    pro_others = paginator.page(page)
    page_range,num_pages = paginator.page_range,paginator.num_pages
    show_firstpage = False if int(page) == 1 else True
    show_lastpage = False if int(page) == num_pages else True
    show_pages = 5 
    if num_pages <= show_pages:#当数量不足时
        newpage_range = page_range
    else:
        newpage_range = list()
        if int(page) + show_pages > num_pages:#用于显示后几位
            for pagenum in range(num_pages - show_pages + 1,num_pages + 1):
                newpage_range.append(pagenum)
        else:
            for pagenum in range(int(page),int(page)+show_pages):
                newpage_range.append(pagenum)
    
    return jinja2_template('edit-assessment.html',user = user,app = chermongapp,
        options = options,pro_others = pro_others,show_firstpage=show_firstpage,
        show_lastpage=show_lastpage,num_pages=num_pages,page_range=newpage_range)
Exemplo n.º 22
0
    def alarm():
        global DEVICES

        if request.method == 'POST':
            ip = '127.0.0.1'
            port = 10300

            print('init socket...')

            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect((ip, port))
                s.settimeout(500)
            except socket.error as exc:
                print('Caught exception socket.error: {0}'.format(exc))
                sys.exit(0)
            print("init socket successfull")


            d = json.dumps(request.json).encode("ascii")
            #print('data:', d)

            # prepare XML data request
            xml_message = "<?xml version='1.0' encoding='UTF-8'?> <request version='1.0' type='json-data'><json-data><![CDATA[ {0} ]]></json-data> <jobtype>alarm</jobtype> </request>".format(d.decode('ascii'))
            #print(xml_message)

            s.send(bytes(xml_message, 'utf-8'))
            #print('data sent')

            s.close()
        else:
            print('GET request of the page, do nothing')

        return bottle.jinja2_template('alarm', title=_("Alarm View"), devices=DEVICES)
Exemplo n.º 23
0
def source_add(db):
    #"""Only admin users can see this"""
    aaa.require(role='admin', fail_redirect='/login')
    errors = []

    form = Forms.sources_add(request.forms)

    if request.method == 'POST':
        validate = form.validate()
        if not validate:
            for k, v in form.errors.iteritems():
                errors.append(FlashMessage(k, v[0], mtype='danger'))
        else:
            i = Source()
            for bu,te in form.data.iteritems():
                setattr(i,bu,te)

            dom = DataObjectManipulation()
            i = dom.sanitize(i)

            upload_errors = []

            if 'thumbnail' in request.files:
                upload = request.files['thumbnail']
                verified = verify_upload(upload)

                if isinstance(verified, dict):
                    name, ext = os.path.splitext(upload.filename)
                    path = 'static/user_upload/icon_%s%s' % (form.data['name'], ext)

                    if not os.path.isdir('static/user_upload'):
                        os.popen('mkdir static/user_upload')
                    if os.path.isfile(path):
                        os.remove(path)

                    try:
                        save_path = 'static/user_upload/icon_%s.png' % form.data['name']
                        verified['img'].save(save_path)
                        i.thumbnail_url = '/' + save_path
                    except Exception as e:
                        errors.append(FlashMessage('icon', 'unknown error, pick another image', mtype='danger'))

                elif isinstance(verified, Debug):
                    errors.append(FlashMessage('icon', verified.message, mtype='danger'))
                else:
                    errors.append(FlashMessage('icon', 'unknown error, pick another image', mtype='danger'))

            if not errors:
                db.add(i)
                db.commit()
                return redirect('..')

    return jinja2_template('source_add.html',
        form_obj=form._fields,
        title='t',
        navigation=gen_navigation(admin=True),
        form=Forms.sources_add(),
        flashmessages=errors,
        breadcrumbs=gen_breadcrumps('/sources/add', 'admin/', lastslash=False, capitalize=True)
    )
Exemplo n.º 24
0
def get_capabilities(layers: List[Layer], tile_matrix_set: TileMatrixSet, wmts_gettile: str) -> str:
    """
    layers is an array of dict that contains:

    extension: the tiles extension like 'png'
        dimension_key: the used dimension key
        dimension_default: the default dimension value
        dimension_values: the possible dimension value
        matrix_set: the matrix set name
    tile_matrix_set a dict that constants the tile matrix set definition:
        name: the name of the tile matrix set
        srs: projection like 'EPSG:21781'
        units: units like 'meters'
        resolutions: array of floats for used resolutions
        bbox: array of floats, the use bbox where the tiles is generated
        tile_size: the size of the tiles (int)
        yorigin: 'top' if the tiles origin is at top
    """
    return cast(
        str,
        jinja2_template(
            wmts_get_capabilities_template,
            layers=layers,
            matrix_sets=matrix_sets(tile_matrix_set),
            wmts_gettile=wmts_gettile,
            tile_matrix_set=tile_matrix_set["name"],
        ),
    )
Exemplo n.º 25
0
def projects():
    
    # 项目目录列表
    project_dirs = os.listdir('./projects')
    
    return jinja2_template('app/app.html',
                           projects=project_dirs)
Exemplo n.º 26
0
def _generate_mapcache_config(gene):
    for layer in gene.layers.values():
        if layer['type'] == 'wms' or 'wms_url' in layer:
            params = {}
            params.update(layer.get('params', {}))
            if 'FORMAT' not in params:
                params['FORMAT'] = layer['mime_type']
            if 'LAYERS' not in layer.get('params', {}):
                params['LAYERS'] = layer['layers']
            if 'TRANSPARENT' not in layer.get('params', {}):
                params['TRANSPARENT'] = 'TRUE' \
                    if layer['mime_type'] == 'image/png' else 'FALSE'
            layer['params'] = params

    config = jinja2_template(
        pkgutil.get_data("tilecloud_chain",
                         "mapcache_config.jinja").decode('utf-8'),
        layers=gene.layers,
        grids=gene.grids,
        mapcache=gene.config['mapcache'],
        min=min,
        len=len,
        sorted=sorted,
    )

    with open(gene.config['mapcache']['config_file'], 'w') as f:
        f.write(config)
Exemplo n.º 27
0
def user_page(id, page = 1):
    u""" ユーザーツイート一覧画面を表示 """
    PAGE_MAX = 12
    user = api.tweet_user(id)
    tweets, count = api.user_newer(id, offset=(PAGE_MAX * (page - 1)), limit=PAGE_MAX)
    pagination = paginate(page, count, PAGE_MAX)
    return jinja2_template('html/user.html', {'tweets':tweets, 'user':user, 'pagination':pagination})
Exemplo n.º 28
0
def _generate_mapcache_config(gene):
    from tilecloud_chain.mapcache_config_template import mapcache_config_template

    if not gene.validate_mapcache_config():
        exit(1)  # pragma: no cover

    for layer in gene.layers.values():
        if layer["type"] == "wms" or "wms_url" in layer:
            if "FORMAT" not in layer["params"]:
                layer["params"]["FORMAT"] = layer["mime_type"]
            if "LAYERS" not in layer["params"]:
                layer["params"]["LAYERS"] = ",".join(layer["layers"])
            if "TRANSPARENT" not in layer["params"]:
                layer["params"]["TRANSPARENT"] = "TRUE" if layer["mime_type"] == "image/png" else "FALSE"
    config = jinja2_template(
        mapcache_config_template,
        layers=gene.layers,
        grids=gene.grids,
        mapcache=gene.config["mapcache"],
        min=min,
        len=len,
    )

    f = open(gene.config["mapcache"]["config_file"], "w")
    f.write(config)
    f.close()
Exemplo n.º 29
0
def main():
    username = request.get_cookie("username", settings.cookie_secret)
    password = request.get_cookie("password", settings.cookie_secret)
    ok = api.check(username, password)
    if not ok:
        redirect("/login")
    meeting_list = api.meeting_list()

    owners = []
    for meeting in meeting_list:
        if username.lower() in settings.admins or username.lower() in meeting.get("moderator_users"):
            owners.append(meeting)
        is_running = api.is_running(meeting.get("id"))
        if is_running:
            meeting["status"] = "running"
        else:
            meeting["status"] = "stopped"

    if username.lower() in settings.admins:
        is_admin = True
        users = api.suggest("")
    else:
        is_admin = users = None
    message = request.params.get("message")
    return jinja2_template(
        "main.html",
        message=message,
        is_admin=is_admin,
        owners=owners,
        meeting_list=meeting_list,
        username=username,
        users=users,
    )
Exemplo n.º 30
0
        def generate_sitemap():
            """The view for generating the sitemap in xml format.
            :return: sitemap in xml format.
            """
            response.add_header('Content-Type', 'application/xml')

            links_for_sitemap = [link for link in app.routes if link.config.get('add_to_sitemap')]

            sitemap_links = []
            for link in links_for_sitemap:
                resource_keys = [item for item in re.findall(r'(<\w+:?\w+>)', link.rule)]

                if resource_keys:
                    result = create_dynamic_link(self.domain, self.site_name, link, resource_keys)
                    sitemap_links.extend(result)
                else:
                    result = create_static_link(self.domain, self.site_name, link)
                    sitemap_links.append(result)

            return jinja2_template('''<?xml version="1.0" encoding="UTF-8"?>
                    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                        {% for url in sitemap_links %}
                        <url>
                            <loc>{{url}}</loc>
                            <changefreq>{{changefreq}}</changefreq>
                            <priority>{{priority}}</priority>
                        </url>
                        {% endfor %}
                    </urlset>
            ''', {'sitemap_links': sitemap_links, 'changefreq': self.changefreq, 'priority': self.priority})
Exemplo n.º 31
0
def _generate_mapcache_config(gene):
    from tilecloud_chain.mapcache_config_template import mapcache_config_template

    if not gene.validate_mapcache_config():
        exit(1)  # pragma: no cover

    for layer in gene.layers.values():
        if layer['type'] == 'wms' or 'wms_url' in layer:
            if 'FORMAT' not in layer['params']:
                layer['params']['FORMAT'] = layer['mime_type']
            if 'LAYERS' not in layer['params']:
                layer['params']['LAYERS'] = ','.join(layer['layers'])
            if 'TRANSPARENT' not in layer['params']:
                layer['params']['TRANSPARENT'] = 'TRUE' if layer['mime_type'] == 'image/png' else 'FALSE'
    config = jinja2_template(
        mapcache_config_template,
        layers=gene.layers,
        grids=gene.grids,
        mapcache=gene.config['mapcache'],
        min=min
    )

    f = open(gene.config['mapcache']['config_file'], 'w')
    f.write(config)
    f.close()
Exemplo n.º 32
0
def view_paste(paste_id):
    """
    Return page with paste_id
    """
    paste_id = paste_id
    if not cache.exists('paste:' + paste_id):
        bottle.redirect('/')

    p = json.loads(cache.get('paste:' + paste_id))

    # Syntax hilighting
    try:
        lexer = get_lexer_by_name(p['syntax'], stripall=False)
    except:
        lexer = get_lexer_by_name('text', stripall=False)
    formatter = HtmlFormatter(linenos=True, cssclass="paste")
    linker = modules.kwlinker.get_linker_by_name(p['syntax'])
    if linker is not None:
        lexer.add_filter(linker)
        p['code'] = highlight(p['code'], lexer, formatter)
        p['code'] = modules.kwlinker.replace_markup(p['code'])
    else:
        p['code'] = highlight(p['code'], lexer, formatter)
    p['css'] = HtmlFormatter().get_style_defs('.code')

    return bottle.jinja2_template('view.html', paste=p, pid=paste_id)
Exemplo n.º 33
0
def get_wmts_capabilities(gene, cache, exit_=False):
    if _validate_generate_wmts_capabilities(cache, exit_):
        server = gene.config.get('server')

        base_urls = _get_base_urls(cache)
        _fill_legend(gene, cache, server, base_urls)

        return jinja2_template(
            pkgutil.get_data("tilecloud_chain",
                             "wmts_get_capabilities.jinja").decode('utf-8'),
            layers=gene.layers,
            grids=gene.grids,
            getcapabilities=urljoin(
                base_urls[0],
                (server.get('wmts_path', 'wmts') +
                 '/1.0.0/WMTSCapabilities.xml' if server else cache.get(
                     'wmtscapabilities_file', '1.0.0/WMTSCapabilities.xml'))),
            base_urls=base_urls,
            base_url_postfix=(server.get('wmts_path', 'wmts') +
                              '/') if server else '',
            get_tile_matrix_identifier=get_tile_matrix_identifier,
            server=server is not None,
            has_metadata=gene.metadata is not None,
            metadata=gene.metadata,
            has_provider=gene.provider is not None,
            provider=gene.provider,
            enumerate=enumerate,
            ceil=math.ceil,
            int=int,
            sorted=sorted,
        )
Exemplo n.º 34
0
def averages():
    # sessionID = HTTPCookie.getSessionCookie(request)
    respData = dict(url=url, title='Blood Glucose',
                    timestamp=time.time())  #, sessionID=sessionID)
    return jinja2_template('Averages.jinja2',
                           respData,
                           template_lookup=['templates'])
Exemplo n.º 35
0
    def goto(self, path, env):
        try:
            uid = int(path)

            f = self.findex.get_files_objects(id=uid)

            if not f:
                raise Exception()

            f = f[0]

            h = self.db.query(Resources).filter_by(
                id=f.resource_id
            ).first()

            if f and h:
                data = {
                    'file': f,
                    'host': h
                }
            else:
                raise Exception()

            return jinja2_template('main/browse_goto', env=env, data=data)
        except Exception as ex:
            return 'error :( we could always stay here'
Exemplo n.º 36
0
def bbs_top():
    bbs = Bbs()
    data = bbs.get_all_threads()
    settings_dict = {
        'autoescape': False,
        }
    return jinja2_template('bbs.html', data=data, template_settings=settings_dict)
Exemplo n.º 37
0
def view_paste(paste_id):
    """
    Return page with paste_id
    """
    paste_id = paste_id
    if not cache.exists('paste:' + paste_id):
        bottle.redirect('/')

    p = json.loads(cache.get('paste:' + paste_id))

    # Syntax hilighting
    try:
        lexer = get_lexer_by_name(p['syntax'], stripall=False)
    except:
        lexer = get_lexer_by_name('text', stripall=False)
    formatter = HtmlLineFormatter(linenos=True, cssclass="paste")
    linker = modules.kwlinker.get_linker_by_name(p['syntax'])
    if linker is not None:
        lexer.add_filter(linker)
        p['code'] = highlight(p['code'], lexer, formatter)
        p['code'] = modules.kwlinker.replace_markup(p['code'])
    else:
        p['code'] = highlight(p['code'], lexer, formatter)
    p['css'] = HtmlLineFormatter().get_style_defs('.code')

    return bottle.jinja2_template('view.html', paste=p, pid=paste_id)
Exemplo n.º 38
0
def logout():
    '''
        退出
    '''
    log.info("logout")
    response.delete_cookie(key='user',secret='chermong')
    return jinja2_template('login.html')
Exemplo n.º 39
0
def index():
    uname = request.session.get('user_name')

    tweet = {'id': '1', 'tweet': 'tweet'}

    tweets = (tweet, tweet)

    return jinja2_template('users/index', uname=uname, tweets=tweets)
Exemplo n.º 40
0
def view_diff(orig, fork):
    """
    View the diff between a paste and what it was forked from
    """
    if not cache.exists('paste:' + orig) or not cache.exists('paste:' + fork):
        return bottle.jinja2_template('error.html', code=200,
                                      message='One of the pastes could not be found.')

    po = json.loads(cache.get('paste:' + orig))
    pf = json.loads(cache.get('paste:' + fork))
    co = po['code'].split('\n')
    cf = pf['code'].split('\n')
    lo = '<a href="/' + orig + '">' + orig + '</a>'
    lf = '<a href="/' + fork + '">' + fork + '</a>'

    diff = difflib.HtmlDiff().make_table(co, cf, lo, lf)
    return bottle.jinja2_template('page.html', data=diff)
Exemplo n.º 41
0
def check_height():
    email = request.forms["email_name"]
    height = request.forms["height_name"]
    total, avg_height = get_from_database(email, height)
    message = "The average height is {} out of {} persons".format(
        avg_height, total)
    sent_email(email, message)
    return jinja2_template('successful.html')
def browse_home():
    '''The root of a RESTful interface to browse zip codes.'''

    c = conn.cursor()
    c.execute('select * from zip_codes limit 30')
    all_rows = c.fetchall()

    return bottle.jinja2_template('browse_home.tpl', all_zips = all_rows)
Exemplo n.º 43
0
 def leader_template(user=user, code=asm, feedback=None):
     return jinja2_template(
         'leaderboard.html', {
             'leaders': get_leaders(db),
             'user': user,
             'code': code,
             'feedback': feedback,
         })
Exemplo n.º 44
0
def get_form():
    # Cookieの値をUnicodeで取得するため、getunicode()メソッドを使う
    # https://bottlepy.org/docs/dev/tutorial.html#introducing-formsdict
    # https://bottlepy.org/docs/dev/api.html#bottle.FormsDict
    # handle = request.get_cookie('handle') #=> 「あ」がセットされてしまう
    handle = request.cookies.getunicode('handle', default='')
    messages = read_messages()
    return jinja2_template('bbs.html', handle=handle, messages=messages)
Exemplo n.º 45
0
def newer_page(page):
    u""" 新着ツイートをもっと見る 画面を表示 """
    PAGE_MAX = 12
    tweets, count = api.newer(offset=(PAGE_MAX * page), limit=PAGE_MAX)
    # HOME 画面で PAGE_MAX 個表示しているので、数を引いておく
    pagination = paginate(page, count - PAGE_MAX, PAGE_MAX)
    return jinja2_template('html/newer.html', {'tweets':tweets, 'pagination':pagination})
    return str(count / PAGE_MAX)
Exemplo n.º 46
0
def view_diff(orig, fork):
    """
    View the diff between a paste and what it was forked from
    """
    if not cache.exists('paste:' + orig) or not cache.exists('paste:' + fork):
        return bottle.jinja2_template('error.html', code=200,
                                      message='One of the pastes could not be found.')

    po = json.loads(cache.get('paste:' + orig))
    pf = json.loads(cache.get('paste:' + fork))
    co = po['code'].split('\n')
    cf = pf['code'].split('\n')
    lo = '<a href="/' + orig + '">' + orig + '</a>'
    lf = '<a href="/' + fork + '">' + fork + '</a>'

    diff = difflib.HtmlDiff().make_table(co, cf, lo, lf)
    return bottle.jinja2_template('page.html', data=diff)
Exemplo n.º 47
0
def about_author():
    """
       关于作者
    """
    log.info("about_author")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    return jinja2_template('about-author.html',user = user,app = chermongapp)
Exemplo n.º 48
0
def index():
    """
        显示主页面
    """
    log.info("index")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    return jinja2_template('index.html',user = user,app = chermongapp)
Exemplo n.º 49
0
def changepasswd():
    """
       修改密码
    """
    log.info("changepasswd")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    return jinja2_template('changepasswd.html',user = user,app = chermongapp)
Exemplo n.º 50
0
def user_lookup():
    """
        查看用户信息
    """
    log.info("user_lookup")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    return jinja2_template('userprofile.html',user = user,app = chermongapp)
Exemplo n.º 51
0
def complex():
    return jinja2_template(
        'complex.html', {
            'complex_dict': {
                'dict_key': 'dict_value'
            },
            'complex_list': ['list1', 'list2']
        })
Exemplo n.º 52
0
def about_copyright():
    """
       关于版权声明
    """
    log.info("about_copyright")
    user = request.get_cookie('user',secret="chermong")
    user = db.user.find_one({'name':user})
    return jinja2_template('about-copyright.html',user = user,app = chermongapp)
Exemplo n.º 53
0
def hide():
    s = bottle.request.environ.get('beaker.session')
    if 'username' not in s:
        redirect('/login')
    username = s['username']
    keyname_fpe = s['keyname_fpe']
    keyname_blob = s['keyname_blob']
    return jinja2_template('hide.html', username=username, text_to_hide='', ssn_to_hide='', tel_to_hide='', secrets_to_hide='', key_name_fpe=keyname_fpe, key_name_blob=keyname_blob)
Exemplo n.º 54
0
def leaderboard(db):
    user = request.get_cookie('user')
    if user is None:
        user = ''
    return jinja2_template('leaderboard.html', {
        'leaders': get_leaders(db),
        'user': user,
        'code': '',
    })
def post_top():
    print(request.forms.get('handle'))
    message = Message(
        # get()だと文字化けするため、getunicode()を使う
        title=request.forms.getunicode('title'),
        handle=request.forms.getunicode('handle'),
        message=request.forms.getunicode('message'),
    )
    return jinja2_template('bbs', message=message)
Exemplo n.º 56
0
        def handle_error(error):
            if request.is_ajax:
                response.status = error.status
                response.content_type = 'application/json'
                return json.dumps({'message': error.body})

            variables = self.__template_variables(f'{error.status}')
            variables['page_title'] = f'{error.status} Error'
            return jinja2_template('views/error.html', variables)
Exemplo n.º 57
0
def jobs_retry(job_id):
    if bottle.request.method == 'POST':
        job = Job.objects.get(job_id=job_id)
        if not job.is_finished:
            job.retry()

        return bottle.redirect('/jobs/')

    return bottle.jinja2_template('job_retry.html', job_id=job_id)
Exemplo n.º 58
0
def count():
    print('count')
    global DEVICES

    # the data will be locally accesed, we need to know our server host
    current_host = request.get_header('host')
    print(current_host)

    return bottle.jinja2_template('m9bstatustablegroupm9b', title=_("M9B Number of Devices Status"), host=current_host)
Exemplo n.º 59
0
    def run_main():
        request.session['test'] = request.session.get('test',0) + 1
        request.session.save()
        logger.debug("Session: %d", request.session['test'])

        request.session['profile_firstname'] = 'NA'
        request.session['profile_lastname'] = 'NA'

        return bottle.jinja2_template('locationview', title=_("Location View"), devices=DEVICES)
Exemplo n.º 60
0
def run_search(db):
    '''
    Run the search and return the results page
    '''
    search_terms = bottle.request.GET.get('q', None)

    if not search_terms:
        return bottle.jinja2_template('noresults.html')

    try:
        rows = db.execute(documents.select().match(search_terms.strip()))
    except:
        return 'Database error: please try your request again.'

    if rows.rowcount > 0:
        return bottle.jinja2_template('results.html', rows=rows)
    else:
        return bottle.jinja2_template('noresults.html')