def manage_arduino(uuid: str): """Page to manage the arduino. We can read information and send open/close commands. """ if request.method == 'GET': if is_valid_uuid(uuid) is False: return render_template_string('Arduino not found') arduino_info = Sensor.query.filter_by(id=uuid).first() if arduino_info is None: return render_template_string('Arduino not found') return render_template('manage_arduino.html', info=arduino_info) elif request.method == 'POST': """When open/close button in this page gets pressed we publish a mqtt message to open/close the window. """ status = request.get_json()['status'] command = 'OFF' if status == 0 else 'ON' try: mqtt.publish(f'{uuid}/command', payload=f'{command}') except NameError: return "No broker enabled", 401 return "OK", 200
def addNewRoom(): global selected_house # Get the house name if selected_house == '': return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>Select a House</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400 room_name = sanitizeString(request.form.get( 'room_name')) if request.form.get('room_name') else None # Check if the room name is valid if room_name and room_name not in houses[selected_house]: houses[selected_house][room_name] = { MQTT_TOPIC_ALARM: '0', MQTT_TOPIC_HP: '0', MQTT_TOPIC_TEMPERATURE: '0', MQTT_TOPIC_CHANGES: '0:0', MQTT_TOPIC_LIMITS: '0:0:0:0' } # Create the new Room Topics createRoomTopics(selected_house, room_name, houses[selected_house][room_name]) return redirect(url_for('home')) return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>Invalid Room Name</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400
def process_contact( sending_profile, subscription, contact, customer, template, email: Email ): """Send test to contact.""" # Get tracking info for opens/clicks tracking_info = get_tracking_info( sending_profile, f"test_{subscription['_id']}", contact["test_uuid"], ) context = get_email_context( customer=customer, target=contact, url=tracking_info["click"], ) html = template["html"] + tracking_info["open"] email_body = render_template_string(html, **context) from_address = render_template_string( get_from_address(sending_profile, template["from_address"]), **context ) subject = render_template_string(template["subject"], **context) email.send( to_recipients=[contact["email"]], from_email=from_address, subject=subject, body=email_body, )
def get(self, tracking_id): """Get.""" decoded = decode_tracking_id(tracking_id) if len(decoded) > 2: if decoded[0] == "test": process_open_test(decoded[1], decoded[2]) return send_file("static/pixel.gif", mimetype="image/gif") else: return cycle_id, target_id = decoded cycle = cycle_manager.get(document_id=cycle_id, fields=["_id", "subscription_id"]) target = target_manager.get(document_id=target_id) if not cycle or not target: return render_template_string("404 Not Found"), 404 open_events = list( filter(lambda x: x["message"] == "opened", target.get("timeline", []))) if len(open_events) < 10: target_manager.add_to_list( document_id=target["_id"], field="timeline", data=get_timeline_entry("opened"), ) cycle_manager.update(document_id=cycle["_id"], data={"dirty_stats": True}) return send_file("static/pixel.gif", mimetype="image/gif")
def manageRoom(): # Redirect to the new web page with the selected room if selected_house != '' and selected_room != '': return redirect(url_for('roomManagement')) return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>Select a House and a Room to Manage</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400
def post_case_blocks(backend, client, case_blocks, form_extras=None, domain=None): """ Post case blocks. Extras is used to add runtime attributes to the form before sending it off to the case (current use case is sync-token pairing) """ if form_extras is None: form_extras = {} domain = domain or form_extras.pop('domain', None) submit_url = get_submit_url(backend, domain) now = json_format_datetime(datetime.utcnow()) if not isinstance(case_blocks, basestring): case_blocks = ''.join([ElementTree.tostring(cb) for cb in case_blocks]) form_xml = render_template_string(MOCK_FORM, **{ 'case_block': case_blocks, 'time': now, 'uid': form_extras.get('form_id', str(uuid4())), 'username': form_extras.get('username', 'bob'), 'user_id': form_extras.get('user_id', str(uuid4())), }) headers = {'Authorization': 'Basic ' + base64.b64encode('admin:secret')} headers.update(form_extras.get('headers', {})) result = client.post( submit_url, headers=headers, data=form_xml ) return result
def process_click_test(subscription_id, contact_id): """Process a click from the landing page.""" subscription = subscription_manager.get( document_id=subscription_id, fields=["test_results", "customer_id", "landing_page_url"], ) contact = next( filter(lambda x: x["test_uuid"] == contact_id, subscription["test_results"]) ) contact["timeline"] = contact.get("timeline", []) if len(contact["timeline"]) < 10: contact["timeline"].append(get_timeline_entry("clicked")) contact["clicked"] = True contact["opened"] = True subscription_manager.update_in_list( document_id=subscription_id, field="test_results.$", data=contact, params={"test_results.test_uuid": contact_id}, ) # If a landing page url exists for the subscription, redirect to it after click has been tracked if subscription.get("landing_page_url"): return redirect(subscription["landing_page_url"], 302) # Get landing page landing_page = get_landing_page(contact["template"]["_id"]) # Get customer customer = customer_manager.get(document_id=subscription["customer_id"]) # Get Jinja template context context = get_email_context(target=contact, customer=customer) return render_template_string(landing_page["html"], **context)
def extend_base_template(*args, **kwargs): """ Passes all of the kwargs required by the base template, then continues with rendering the template """ tab_contents = [ { "name": "Home", "route": "/" }, { "name": "Publications", "route": "/publications" }, { "name": "Blog", "route": "/blog" }, { "name": "Changelog", "route": "/changelog" }, ] if args[0].endswith(".html"): return render_template(*args, tab_contents=tab_contents, **kwargs) return render_template_string(*args, tab_contents=tab_contents, **kwargs)
def addNewHouse(): house_name = sanitizeString(request.form.get( 'house_name')) if request.form.get('house_name') else None if house_name and house_name not in houses: houses[house_name] = {} return redirect(url_for('home')) return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>Invalid House Name</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400
def do_mailtool(): form = MailtoolForm(request.form) if form.validate(): submit_button_label = request.form['submit'] if not form.recipients.data: # no recipients selected prts = session.query(Participant).all() return render_template("mailtool.html", title="Mail Tool", form=form, participants=prts, delay=delay_between_messages) if submit_button_label == "revise": # "revise" button clicked on confirm page prts = session.query(Participant).all() return render_template("mailtool.html", title="Mail Tool", form=form, participants=prts, delay=delay_between_messages) # dryrun = True: "Send" button clicked on confirm page # dryrun = False: "Preview" button clicked on first Mailtool page dryrun = (submit_button_label != "send") recipients = [int(rec) for rec in form.recipients.data.split(",")] bodies = [] participants = [] try: for recipient in recipients: prt = lp(recipient) # type: Participant ee = prt.extras if ee: e = ee[0] pay_now, pay_to_hotel, items = extras_cost(e) else: e, pay_now, pay_to_hotel, items = None, None, None, None bodies.append(render_template_string(form.body.data, prt=prt, extras=e, pay_now=pay_now, pay_to_hotel=pay_to_hotel, items=items)) participants.append(prt) emails = ehbmail.send(recipients, form.subject.data, bodies, "Mail Tool (%s)" % current_user.id, replyto=form.replyto.data, dryrun=dryrun, delay=delay_between_messages) except Exception as e: logger().error("Mailtool: Exception while attempting to send emails: %s" % repr(e)) flash("An error occurred while rendering or sending your emails: %s. Please check the Mail Archive to see what emails were actually sent." % str(e)) prts = session.query(Participant).all() return render_template("mailtool.html", title="Mail Tool", form=form, participants=prts, delay=delay_between_messages) if dryrun: return render_template("confirm_emails.html", title="Mail Tool", emails_with_participants=zip(emails, participants), form=form, num_emails=len(emails)) else: return render_template("admin.html", message="%d email(s) were sent." % (len(emails))) else: prts = session.query(Participant).all() return render_template("mailtool.html", title="Mail Tool", form=form, participants=prts, delay=delay_between_messages)
def render(self): for perm_name in self.perms: if not permissions.perm_manager.get_permission(perm_name).can(): return customhtml = None if self.customtemplate is not None: customhtml = render_template_string(self.customtemplate, menu=self) return render_template(self.template, menu=self, customhtml=customhtml)
def submitData(): global client, houses, selected_house, selected_room # Get alarm from form new_alarm = '1' if request.form.get('alarm') == 'on' else '0' # Cannot set the alarm on if the human presence is also on if new_alarm == '1' and houses[selected_house][selected_room][ MQTT_TOPIC_HP] == '1': return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>You cannot set the alarm with people in the room</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400 # Submit Alarm only if it is different from the current one alarm = houses[selected_house][selected_room][MQTT_TOPIC_ALARM] if alarm[0] != new_alarm: houses[selected_house][selected_room][MQTT_TOPIC_ALARM] = new_alarm sendMessageTo(client, getFeedKeyFromName(MQTT_TOPIC_ALARM), houses[selected_house][selected_room][MQTT_TOPIC_ALARM]) # Get heating/cooling from form and send it to the broker new_changes = request.form.getlist('changes')[0] if new_changes != houses[selected_house][selected_room][MQTT_TOPIC_CHANGES]: houses[selected_house][selected_room][MQTT_TOPIC_CHANGES] = new_changes sendMessageTo(client, getFeedKeyFromName(MQTT_TOPIC_CHANGES), new_changes) # Get limits from form new_min1, new_max1 = request.form.get('min1'), request.form.get('max1') new_min2, new_max2 = request.form.get('min2'), request.form.get('max2') # Check if the limits are valid if float(new_min1) > float(new_max1) or float(new_min2) > float(new_max2): return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>Maximum temperature must be greater than Minimum</h2><br><form action="/"><button type="submit">Home</button></form>' ), 400 new_limits = new_min1 + ':' + new_max1 + ':' + new_min2 + ':' + new_max2 # Submit Limits only if they are different from the current ones if new_limits != houses[selected_house][selected_room][MQTT_TOPIC_LIMITS]: houses[selected_house][selected_room][MQTT_TOPIC_LIMITS] = new_limits sendMessageTo(client, getFeedKeyFromName(MQTT_TOPIC_LIMITS), new_limits) return redirect(url_for('roomManagement'))
def get(self, tracking_id): """Get.""" decoded = decode_tracking_id(tracking_id) if len(decoded) > 2: if decoded[0] == "test": return process_click_test(decoded[1], decoded[2]) else: return cycle_id, target_id = decoded cycle = cycle_manager.get(document_id=cycle_id, fields=["_id", "subscription_id"]) target = target_manager.get(document_id=target_id) if not cycle or not target: return render_template_string("404 Not Found"), 404 click_events = list( filter(lambda x: x["message"] == "clicked", target.get("timeline", []))) if len(click_events) < 10: target_manager.add_to_list( document_id=target["_id"], field="timeline", data=get_timeline_entry("clicked"), ) cycle_manager.update(document_id=cycle["_id"], data={"dirty_stats": True}) # If a landing page url exists for the subscription, redirect to it after click has been tracked subscription = subscription_manager.get( document_id=cycle["subscription_id"], fields=["customer_id", "landing_page_url"], ) if subscription.get("landing_page_url"): return redirect(subscription["landing_page_url"], 302) customer = customer_manager.get( document_id=subscription["customer_id"]) landing_page = get_landing_page(target["template_id"]) context = get_email_context(target=target, customer=customer) return render_template_string(landing_page["html"], **context)
def preview_template(data, customer): """Preview template subject, from_address and html for reports.""" fake = Faker() target = { "email": fake.email(), "first_name": fake.first_name(), "last_name": fake.last_name(), "position": fake.job(), } context = get_email_context(customer=customer, target=target) return render_template_string(data, **context)
def as_ul(self, highlight_class="", normal_class="", grouped=True): if not grouped: return render_template_string(ul_tpl, nav_links=self.nav_links, project_name=self.project_name, highlight_class=highlight_class, normal_class=normal_class) else: nav_group_d = OrderedDict() for link in self.nav_links: if link.group not in nav_group_d: nav_group_d[link.group] = [False, []] nav_group_d[link.group][1].append(link) for link in self.nav_links: if link.enabled(): nav_group_d[link.group][0] = True break return render_template_string(ul_tpl_grouped, nav_group_d=nav_group_d, project_name=self.project_name, highlight_class=highlight_class, normal_class=normal_class)
def render_template(self, *args, **kargs): """ variation of View.render_template that prefers ``self.template`` on the filesystem, and failing that will use an embedded template literal at ``self._template`` """ try: return super(self.__class__,self).render_template(*args, **kargs) except jinja2.exceptions.TemplateNotFound, e: from flask.templating import render_template_string report("template {T} not found, using literal",T=self.template) return render_template_string(self._template, **kargs)
def render(self): for perm_name in self.perms: if not permissions.perm_manager.get_permission(perm_name).can(): return '' if self.need_authenticated and not current_user.is_authenticated: return '' customhtml = None if self.customtemplate: customhtml = render_template_string(self.customtemplate, item=self) return render_template(self.template, item=self, customhtml=customhtml)
def transfer_delete(): if request.method == 'GET': return render_template_string("""You need to click delete button at the end of the desired match. Return to the list of matches. <form action="{{ url_for('transfer') }}" method="get" role="form"> <div class="form-group"> <input value="Return" name="Return" type="submit" /><br><br> </div> <!-- End of form-group --> </form>""") else: id = request.form['id'] app.transfers.delete_transfer(id) return redirect(url_for('transfers'))
def transfer_delete(): if request.method == 'GET': return render_template_string( """You need to click delete button at the end of the desired match. Return to the list of matches. <form action="{{ url_for('transfer') }}" method="get" role="form"> <div class="form-group"> <input value="Return" name="Return" type="submit" /><br><br> </div> <!-- End of form-group --> </form>""") else: id = request.form['id'] app.transfers.delete_transfer(id) return redirect(url_for('transfers'))
def simple(): if not session: session['count'] = 0 if not session.get('mass'): session['mass'] = values() pr1 = session['mass']['rows'][0][1] pc1 = session['mass']['cols'][0][1] pr2 = session['mass']['rows'][1][1] pc2 = session['mass']['cols'][1][1] if request.method == "POST": answer = request.form.get('answer').strip().rstrip().split() try: user_pr1 = str(answer[0] + answer[1]) user_pr2 = str(answer[2] + answer[3]) user_pc1 = str(answer[0] + answer[2]) user_pc2 = str(answer[1] + answer[3]) except: session.clear() return render_template( "index.html", message="Not all fields are filled, try again", button='<a href="/" class="button">New Game</a>') if f(pc1, user_pc1) and f(pc2, user_pc2) and f(pr2, user_pr2) and f( pr1, user_pr1): session['count'] = int(session['count']) + 1 session['mass'].clear() return render_template( 'index.html', message="correct", count=int(session['count']), button='<a href="/" class="button">Next</a>') else: session.clear() return render_template( "index.html", message="Wrong! Try again.", button='<a href="/" class="button">New Game</a>') count = int(session['count']) if count == 200: return render_template_string("yetiCTF{[c]+o{2}[l]+_R3}") return render_template("index.html", count=count, pr1=pr1, pr2=pr2, pc1=pc1, pc2=pc2)
def list(): files = os.listdir('./templates') files.sort() # print(files) urls = [] for file in files: urls.append("<p><a href=\"/comic/{0}\">{1}</a></p>".format(file,file)) text1 = """<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> """ text2 = """</body> </html>""" return render_template_string(text1+" ".join(urls)+text2)
def roomManagement(): global client, houses, selected_house, selected_room # Get all the data from the selected room getHousesRooms() if not selected_house and not selected_room: return render_template_string( '<h1>❌ ERROR ❌</h1><br><h2>House or Room Not Found</h2><br><form action="/"><button type="submit">Home</button></form>' ), 404 data = houses[selected_house][selected_room] return render_template('room.html', house=selected_house, room=selected_room, temperature=data[MQTT_TOPIC_TEMPERATURE], human_presence=data[MQTT_TOPIC_HP], alarm=data[MQTT_TOPIC_ALARM], heating=data[MQTT_TOPIC_CHANGES].split(':')[0], cooling=data[MQTT_TOPIC_CHANGES].split(':')[1], min1=data[MQTT_TOPIC_LIMITS].split(':')[0], max1=data[MQTT_TOPIC_LIMITS].split(':')[1], min2=data[MQTT_TOPIC_LIMITS].split(':')[2], max2=data[MQTT_TOPIC_LIMITS].split(':')[3])
test3 = Blueprint("test3", __name__) @test3.route("/") def index(): return "test3" app.register_blueprint(test3, url_prefix="/test3") class FakePermission(object): def can(self): return False test4 = Blueprint("test4", __name__) @test3.route("/") def index(): return "test4" nav_bar.register(test1) nav_bar.register(test2, "/test2/index", group="test1") nav_bar.register(test3, "/test3/index", permissions=[FakePermission()]) nav_bar.register(test3, "/test3/index") nav_bar.register(test4, "/test4/index") with app.test_request_context("/test2/index.html"): from flask.templating import render_template_string print render_template_string('<html>{{nav_bar.as_ul("highlight", grouped=True)|safe}}</html>', nav_bar=nav_bar) print render_template_string('<html>{{nav_bar.as_ul("highlight")|safe}}</html>', nav_bar=nav_bar)
def test_filter_css(app): result = render_template_string('{{"http://example.com"|css}}') assert result == '<link href="http://example.com" rel="stylesheet">'
def test_filter_js(app): result = render_template_string('{{"http://example.com/"|js}}') assert result == '<script src="http://example.com/" ></script>'
def renderTemplate(self, parent_file, template, **params): template = open(os.path.join(os.path.dirname(parent_file), template), "r").read() return render_template_string(template, **params)
def api_map(): """List endpoints for api.""" logging.info("Landing page is running.") return render_template_string("404 Not Found"), 404
def migrate(): with open( os.path.join(os.getcwd(), "app", "utils", "data_dict_template.html"), "r") as fp: template = fp.read() tables_data = get_tables_data() with open(os.path.join(os.getcwd(), "data_dict.json"), "r") as fp: old_data = json.loads(fp.read()) if json.dumps(old_data) == json.dumps(tables_data): print("No Schema changes detected") return alembic_migrate() drop_ddl = "DROP VIEW IF EXISTS {};" def format_ddl(ddl: str) -> str: return "\n\t\t".join([line.strip() for line in ddl.splitlines()]) changed_views = [{ "new_ddl": format_ddl( tables_data.get(name, {}).get("ddl", drop_ddl.format(name))), "old_ddl": format_ddl(old_data.get(name, {}).get("ddl", drop_ddl.format(name))), } for name in set([ name for name, details in { **tables_data, **old_data }.items() if details["type"] == "view" ]) if tables_data.get(name, {}).get("ddl") != old_data.get( name, {}).get("ddl")] generate_op(changed_views) with open(os.path.join(os.getcwd(), "data_dict.json"), "w") as fp: fp.write(json.dumps( tables_data, indent=2, )) with open(os.path.join(os.getcwd(), "data_dict.html"), "w") as fp: fp.write( render_template_string( template, tables=dict(( table, { **table_details, **{ "constraints": dict(( constrain_type, [ constrain for constrain in table_details["constraints"] if constrain["type"] == constrain_type ], ) for constrain_type in sorted( set(const["type"] for const in table_details["constraints"]))) }, }, ) for table, table_details in tables_data.items()), ))
def renderTemplate(self, parent_file, template, **params): template = open(os.path.join(os.path.dirname(parent_file), template), 'r').read() return render_template_string(template, **params)
def view1(content: str): inc() return render_template_string(content)
def input(self, _in, out, source_path, output_path, **kw): out.write(render_template_string(_in.read(), **self.context))
def _process_base_template(self): self._template = "{{template}}" self._template = render_template_string(self._template,template=self._base_template) self._template = "{% extends '" + self._template + "' %}<br />{% block body %}{% endblock body %}<br />"
def render(self): return render_template_string(self._template,**self._context)
def index(): return render_template_string('{{ do_something() }}')
def render(self): return render_template_string(self._template, **self._context)
def dispatch_request(self): inc() return render_template_string('%s' % self.content)
def _process_base_template(self): self._template = "{{template}}" self._template = render_template_string(self._template, template=self._base_template) self._template = "{% extends '" + self._template + "' %}<br />{% block body %}{% endblock body %}<br />"
def build_message_body(detection): return render_template_string("email/person_found.html", detection=detection)