Example #1
0
    def do_GET(self):
        self._set_response()
        with open('./templates/index.html','r') as html_file:
            page = html_file.read()

        content = Environment(loader=BaseLoader).from_string(page).render({'cache':CACHE})

        self.wfile.write(content.encode('utf-8'))
Example #2
0
    def run(cls, task, config, subscription, event):
        options = subscription['config']
        headers = {}
        values = {
            'event_name': event['name'],
            'event': event['data'],
            'wazo_uuid': event['origin_uuid'],
        }

        url = Environment().from_string(options['url']).render(values)

        if subscription['owner_user_uuid'] and cls.url_is_localhost(url):
            # some services only listen on 127.0.0.1 and should not be accessible to users
            logger.warning(
                'Rejecting callback from user "%s" to url "%s": remote host is localhost!',
                subscription['owner_user_uuid'],
                url,
            )
            return

        body = options.get('body')

        if body:
            content_type = options.get('content_type', 'text/plain')
            # NOTE(sileht): parse_header will drop any erroneous options
            ct_mimetype, ct_options = cgi.parse_header(content_type)
            ct_options.setdefault('charset', 'utf-8')
            data = Environment().from_string(body).render(values)
        else:
            ct_mimetype = 'application/json'
            ct_options = {'charset': 'utf-8'}
            data = json.dumps(event['data'])

        data = data.encode(ct_options['charset'])

        headers['Content-Type'] = "{}; {}".format(
            ct_mimetype, "; ".join(map("=".join, ct_options.items())))

        verify = options.get('verify_certificate')
        if verify:
            verify = True if verify == 'true' else verify
            verify = False if verify == 'false' else verify

        with requests_automatic_hook_retry(task):
            session = requests.Session()
            session.trust_env = False
            with session.request(
                    options['method'],
                    url,
                    data=data,
                    verify=verify,
                    headers=headers,
                    timeout=REQUESTS_TIMEOUT,
            ) as r:
                r.raise_for_status()
                return requests_automatic_detail(r)
Example #3
0
    def recv_re(self, environ, start_response):
        title = "recipe form";

        form =  """ 
        <form action='recv_re_2'>
            Name: <input type='text' name='name' size='10'>
			<br>
        {% for i in range( r[0] ) %}
            Comp. name: <input type='text' name='Compname' size='10'>
            Amount: <input type='text' name='amount' size='10'>
            unit: <select name="unit">
                    <option value="oz"> oz</option>
                    <option value="gallon">gallon</option>
                    <option value="liter">liter</option>
                </select>
        {% endfor %}
        {{ maxi }}
            <input type='submit'>
        </form>
        <br>
        """
        error = ""
        content_type = 'text/html'

        #parsing vars
        formdata = environ['QUERY_STRING']
        results = urlparse.parse_qs(formdata)
        
        #Here we check that they are not blank
        #If they are we print an error message
        try:
            n = results['num'][0]
            bulbError =False 
        except KeyError:
            error = "<p style='color:red'>Please make fill all the blanks<a href='\recv_re'>go back!</a></p>" 
            bulbError = True
           
        #Here we check that the number is a digit
        if(bulbError):
            pass
        elif (not n.replace('.','',1).isdigit()):
            error = "<p style='text-color:red'>Please enter a number <a href='\recv_re'>go back!</a></p>" 

        
        #here we render the jinja template
        frm = Environment().from_string(form).render(r= [int(n)])

        data = begining%(title,title) +error + frm.encode('ascii','ignore') + end
        start_response('200 OK', list(html_headers))
        return [data]
Example #4
0
    def recv_li(self, environ, start_response):
        title = "liquor form";

        #couldn't use jinja2 in begining because it is used in many
        #place and I would have to change all of them
        form = begining%(title,title) + """
        <form action='recv_li'>
        Manufacturer: <input type='text' name='mnf' size='10'>
        Liquor: <input type='text' name='liq' size='10'>
        Type: <input type='text' name='type' size='10'>
        <input type='submit'>
        </form>
        <br>
        """

        formdata = environ['QUERY_STRING']
        results = urlparse.parse_qs(formdata)
        
        try:
            mnf = results['mnf'][0]
            liq = results['liq'][0]
            typ = results['type'][0]
            bulbError = False 
        except KeyError:
            error = "<p style='color:red'>Please make fill all the blanks</p>" 
            bulbError = True
            
        if (bulbError):
            pass
        else:
            error = ""
            db.add_bottle_type(mnf, liq, typ)

        content_type = 'text/html'

        cnt = """ 
        {% for typ in _bottle_types_db %}
             <li>{{ typ[0] }}, {{ typ[1] }}, {{ typ[2] }}</li>
        {% endfor %}
        </ul> 
        """

        lst = Environment().from_string(cnt).render( _bottle_types_db = db._bottle_types_db)

        data = form + error +"<ul>" + lst.encode('ascii','ignore') + end
        start_response('200 OK', list(html_headers))
        return [data]
Example #5
0
    def http_callback(subscription, event):
        options = subscription['config']
        headers = {}
        values = {
            'event_name': event['name'],
            'event': event['data'],
            'wazo_uuid': event['origin_uuid'],
        }

        url = options['url']
        template = url
        url = Environment().from_string(template).render(values)

        if subscription['owner_user_uuid'] and url_is_localhost(url):
            # some services only listen on 127.0.0.1 and should not be accessible to users
            logger.warning(
                'Rejecting callback from user "%s" to url "%s": remote host is localhost!',
                subscription['owner_user_uuid'], url)
            return

        content_type = options.get('content_type')

        body = options.get('body')
        if body:
            template = body
            body = Environment().from_string(template).render(values)
            body = body.encode('utf-8')
        else:
            body = json.dumps(event['data'])
            content_type = 'application/json'

        if content_type:
            headers['Content-Type'] = content_type

        verify = options.get('verify_certificate')
        if verify:
            verify = True if verify == 'true' else verify
            verify = False if verify == 'false' else verify

        requests.request(options['method'],
                         url,
                         data=body,
                         verify=verify,
                         headers=headers)
Example #6
0
def render_templatefile(path, **kwargs):
    with open(path, 'rb') as fp:
        raw = fp.read().decode('utf8')
    content = Environment(lstrip_blocks=True, trim_blocks=True).from_string(
        string.Template(raw).substitute(**kwargs)).render({
            'val_header':
            kwargs['val_header'],
            'default_val':
            kwargs['default_val'],
            'ingestion_timestamp':
            kwargs['ingestion_timestamp'],
            'feed_expo':
            kwargs['feed_expo']
        })
    render_path = path[:-len('.tmpl')] if path.endswith('.tmpl') else path
    with open(render_path, 'wb') as fp:
        fp.write(content.encode('utf8'))
    if path.endswith('.tmpl'):
        os.remove(path)
def getPontos(atleta):
    try:
        result = atleta["pontos"]
    except KeyError:
        result = "N"
    return result

now= (datetime.datetime.now() - datetime.timedelta(hours=0)).strftime("%d/%m %H:%M")

data = [(t["cartola"], t["nome"], t["parcial"], getApelidos(t), getPontosTime(t)) for t in sorted(timessoma, key=lambda x: x["parcial"], reverse=True)]

parciaishtml= Environment(loader=FileSystemLoader(THIS_DIR), trim_blocks=True).get_template("template.html").render(data=data, timestamp=now)


with open("parciais.html", 'w') as f:
    f.write(parciaishtml.encode("UTF-8"))














Example #8
0
def render(tpl_path, context):
    path, filename = os.path.split(tpl_path)
    return jinja2.Environment(loader=jinja2.FileSystemLoader(
        path or './')).get_template(filename).render(context)


path = '/data/dotmaps/'
dotmap_cities = [
    d for d in os.listdir(path)
    if os.path.isdir(path + d) and d != 'index_files'
]

print dotmap_cities

dotmaps = []
for d in dotmap_cities:
    dotmaps.append({'link': d, 'name': d})
context = {'num': len(dotmap_cities), 'dotmaps': dotmaps}

template = open('./dotmap_index_template.html').read()
template = template.decode('utf-8')
txt = Environment().from_string(template).render(context)

f = open('/data/dotmaps/index.html', 'w')
f.write(txt.encode('utf-8'))
f.close()

uid = pwd.getpwnam("www-data").pw_uid
gid = grp.getgrnam("www-data").gr_gid
os.chown('/data/dotmaps/index.html', uid, gid)
Example #9
0
    def recv_re_2(self, environ, start_response):
        title = "recipe form";

        error = ""

        #parsing vars
        formdata = environ['QUERY_STRING']
        results = urlparse.parse_qs(formdata)

        try:
            name = results['name'][0]
            Compname = results['Compname']
            amnt = results['amount']
            unit = results['unit']
            bulbError =False 
        except KeyError:
            error = "<p style='color:red'>Please make fill all the blanks</p>" 
            bulbError = True

        if(bulbError):
            pass
        elif (not amnt[0].replace('.','',1).isdigit()):
            error = "<p style='text-color:red'>Please enter a number</p>" 
        else:
            totalA = []
            i = 0
            for a in amnt:
                amount = a + ' '+ unit[i]
                ml_amount = db.convert_to_ml(amount)
                content_type = 'text/html'
                m = '%.3f' %ml_amount + ' ' + 'ml'
                totalA.append(m)
                i += 1
            print 'totalA', totalA

        cmpt = []
        i = 0
        for c in Compname:
            cmpt.append((c,totalA[i]))
            i += 1

        print 'cmpt:',cmpt
        r = recipes.Recipe(name, cmpt)
        db.add_recipe(r)

        content_type = 'text/html'

        cnt = """ 
        <ul>
        {% for key in recipes %}
            <li> {{ key }} </li>
        {% endfor %}
        </ul> 
        """

        lst = Environment().from_string(cnt).render(recipes = db._recipes_db)
        
        data = begining%(title,title) +error + lst.encode('ascii','ignore') + end
            
        start_response('200 OK', list(html_headers))
        return [data]
Example #10
0
    def recv_in(self, environ, start_response):
        title = "inv. form";

        #couldn't use jinja2 in begining because it is used in many
        #place and I would have to change all of them
        form = begining%(title,title) + """
        <form action='recv_in'>
        Manufacturer: <input type='text' name='mnf' size='10'>
        Liquor: <input type='text' name='liq' size='10'>
        Amount: <input type='text' name='amount' size='10'>
        unit: <select name="unit">
                <option value="oz"> oz</option>
                <option value="gallon">gallon</option>
                <option value="liter">liter</option>
            </select>
        <input type='submit'>
        </form>
        <br>
        """
        error = ""

        formdata = environ['QUERY_STRING']
        results = urlparse.parse_qs(formdata)

        try:
            mnf = results['mnf'][0]
            liq = results['liq'][0]
            num = results['amount'][0]
            unit = results['unit'][0]
            bulbError =False 
        except KeyError:
            error = "<p style='color:red'>Please make fill all the blanks</p>" 
            bulbError = True
            
        if(bulbError):
            pass
        elif (not num.replace('.','',1).isdigit()):
            error = "<p style='text-color:red'>Please enter a number</p>" 
        else:
            amount = num + ' '+ unit
            ml_amount = db.convert_to_ml(amount)
            content_type = 'text/html'

            try:
                db.add_to_inventory(mnf, liq, amount)
            except db.LiquorMissing:
                error = " <p style='background:red'>Error: This liquor type is not found in our records, please add it in the liquor types form</p>"

        content_type = 'text/html'

        cnt = """ 
        <tr>
        <td><strong>Manufacturer</strong></td>
        <td><strong>Liquor</strong></td>
        <td><strong>Amount</strong></td>
        </tr>

        {% for key in inventory %}
             <tr>
             <td>{{ key[0] }}</td>
             <td>{{ key[1] }}</td>
             <td>{{ inventory[key] }} ml</td>
             </tr>
        {% endfor %}
        </table> 
        """

        lst = Environment().from_string(cnt).render( inventory = db._inventory_db)

        data = form + error +"<table border='1'  margin='50px'>" + lst.encode('ascii','ignore') + end
        start_response('200 OK', list(html_headers))
        return [data]