def chat_page(): appid = request.args.get('appid') appkey = request.args.get('appkey') customer_id = request.args.get('customer_id', '') app_name = request.args.get('app_name', '') user_name = request.args.get('name', '') if not appid or not appkey or not user_name: return render_template_string(error_html, error="appid、appkey、uid、user_name 为必填参数") data = { "appid": int(appid), "customer_id": customer_id, "name": user_name, } basic = base64.b64encode("%s:%s" % (appid, appkey)) headers = {'Content-Type': 'application/json; charset=UTF-8', 'Authorization': 'Basic ' + basic} url = config.GOBELIEVE_URL + "/customer/register" r = requests.post(url, headers=headers, data=json.dumps(data)) if r.status_code != 200: return render_template_string(error_html, error="获取权限失败") res = json.loads(r.content) client_id = res['data']['client_id'] store_id = res['data']['store_id'] token = res['data']['token'] print res['data'] return render_template("customer/chat.html", host=config.HOST, customerAppID=int(appid), customerID=int(client_id), customerToken=token, store_id=store_id, name=app_name, apiURL=config.APIURL)
def test_template_basics(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale="de_DE") t = lambda x: flask.render_template_string("{{ %s }}" % x) with app.test_request_context(): assert t("gettext('Hello %(name)s!', name='Peter')") == "Hallo Peter!" assert t("ngettext('%(num)s Apple', '%(num)s Apples', 3)") == u"3 Äpfel" assert t("ngettext('%(num)s Apple', '%(num)s Apples', 1)") == u"1 Apfel" assert ( flask.render_template_string( """ {% trans %}Hello {{ name }}!{% endtrans %} """, name="Peter", ).strip() == "Hallo Peter!" ) assert ( flask.render_template_string( """ {% trans num=3 %}{{ num }} Apple {%- pluralize %}{{ num }} Apples{% endtrans %} """, name="Peter", ).strip() == u"3 Äpfel" )
def main(): token = session.get('token', False) # if the user has a token they're logged in if token: # example request gets information about logged in user me = Client(token=token).users.me() return render_template_string(''' {%- if image_url -%} <img src="{{ image_url }}"> {%- endif %} <p>Hello {{ name }}.</p> <p><pre>{{ dump }}</pre></p> <p><a href="/logout">Logout</a></p>''', name=me['name'], image_url=me.get('photo', {}).get('image_60x60', None), dump=json.dumps(me, indent=2) ) # if we don't have a token show a "Sign in with Asana" button else: # get an authorization URL and anti-forgery "state" token (auth_url, state) = Client().session.authorization_url() # persist the state token in the user's session session['state'] = state # link the button to the authorization URL return render_template_string(''' <p><a href="{{ auth_url }}"><img src="https://luna1.co/7df202.png"></a></p>''', auth_url=auth_url )
def test_jinja_templates(app): """Test template rendering.""" InvenioI18N(app) assert app.jinja_env.filters['datetimeformat'] assert app.jinja_env.filters['toutc'] assert app.jinja_env.filters['tousertimezone'] dt = datetime(1987, 3, 5, 17, 12) dt_tz = datetime(1987, 3, 5, 17, 12, tzinfo=timezone('CET')) with app.test_request_context(): assert render_template_string( "{{dt|datetimeformat}}", dt=dt) == \ "Mar 5, 1987, 5:12:00 PM" assert render_template_string( "{{dt|toutc}}", dt=dt_tz) == \ "1987-03-05 16:12:00" assert render_template_string( "{{dt|tousertimezone}}", dt=dt_tz) == \ "1987-03-05 16:12:00+00:00" assert render_template_string("{{_('Translate')}}") == 'Translate' tpl = r"{% trans %}Block translate{{var}}{% endtrans %}" assert render_template_string(tpl, var='!') == 'Block translate!'
def user_remove(name = None): name = request.args.get('username', 0, type=str).lower() if name != None: result_string = rdb.remove_redditor(name)#'Hello, ' + name + '!\n\tHow are you?' return jsonify(result=render_template_string(result_string)) else: return jsonify(result=render_template_string('<div class="alert alert-danger">User '+name+'\'s broke something!</div>'))
def test_template_escaping(self): app = flask.Flask(__name__) with app.test_request_context(): rv = flask.render_template_string('{{ "</script>"|tojson|safe }}') assert rv == '"<\\/script>"' rv = flask.render_template_string('{{ "<\0/script>"|tojson|safe }}') assert rv == '"<\\u0000\\/script>"'
def index(slug_candidate): """ Render the template for the onionshare landing page. """ check_slug_candidate(slug_candidate) add_request(REQUEST_LOAD, request.path) # Deny new downloads if "Stop After First Download" is checked and there is # currently a download global stay_open, download_in_progress deny_download = not stay_open and download_in_progress if deny_download: r = make_response(render_template_string(open(common.get_resource_path('html/denied.html')).read())) for header, value in security_headers: r.headers.set(header, value) return r # If download is allowed to continue, serve download page r = make_response(render_template_string( open(common.get_resource_path('html/index.html')).read(), slug=slug, file_info=file_info, filename=os.path.basename(zip_filename), filesize=zip_filesize, filesize_human=common.human_readable_filesize(zip_filesize))) for header, value in security_headers: r.headers.set(header, value) return r
def main(args=None): if not args: return render_template_string(page, title=u'Common interwiki articles') c = conn('p50380g50592__interwikis_p', 's1.labsdb') c.execute('SELECT ell_title, ell_links FROM enwiki_langlinks WHERE ell_langs NOT LIKE ? LIMIT 200', ('% {} %'.format(args),)) r = c.fetchall() return render_template_string(page, title=u'Common interwiki articles missing in {}.wiki'.format(args), prefix=args, query=r)
def login_form(self): if 'do' in request.args and request.args['do'] == 'captcha_img': if 'captcha' not in session: abort(503) else: response = make_response(session['captcha'].image()) response.headers.add('Content-Type', 'image/png') return response if 'sq' in request.args: if not self.model.security_questions: self.model.security_questions = request.kenan.GetSecurityQuestions() print 'SEC Qs', self.model.security_questions request.response.data = render_template_string(request.templates['security_question_redirection'], security_questions=self.model.security_questions, templates=request.template_objects) return request.response if 'next' in request.args: next_page = request.args['next'] else: next_page = utils.extract_nextpage(request, self.wide) captcha_form = False if 'captcha_active' in session: captcha_form = True session['captcha'] = captcha(request.cookies['sessid']) self.log.info('Captcha Validation: %s', session['captcha']._generate_words()) session['next'] = next_page request.response.data = render_template_string(request.templates['login'], templates=request.template_objects, organizations=self.wide.organizations, captcha_form=captcha_form) return request.response
def test_from_isodatetime(app): """Test from_isodate filter.""" with app.test_request_context(): assert render_template_string( "{{ 'yes' if dt|from_isodatetime < now else 'no'}}", dt='2002-01-01T00:01:00', now=arrow.now()) == 'yes' assert render_template_string("{{ dt|from_isodatetime }}", dt='') \ == 'None' assert render_template_string( "{{ dt|from_isodatetime }}", dt=datetime(2002, 1, 1, 1, 1)) == \ '2002-01-01 01:01:00+00:00' pytest.raises( TypeError, render_template_string, "{{ 'yes' if dt < now else 'no'}}", dt='2002-01-01T00:01', now=arrow.now()) pytest.raises( ParserError, render_template_string, "{{ dt|from_isodatetime }}", dt='abcd-01-01T00:00:00') pytest.raises( ParserError, render_template_string, "{{ dt|from_isodatetime(strict=True) }}", dt='') # Test pre-1900 centuries. assert render_template_string( "{{ '0001-01-01T00:00:00'|from_isodatetime" " > '1500-01-01'|from_isodatetime }}") == \ "False"
def lost_password_form(self): if 'do' in request.args and request.args['do'] == 'captcha_img': if 'pw_captcha' not in session: abort(503) else: response = make_response(session['pw_captcha'].image()) response.headers.add('Content-Type', 'image/png') return response phase = int(request.args['phase']) if 'phase' in request.args else 1 if phase == 1: session.wipe(exception_keys=['_flashes']) session['confirmation_form_type'] = 'lost_password' request.response.data = render_template_string(request.templates['lost_password1'], templates=request.template_objects) elif phase == 2 and 'confirmation_email_address' in session: session['security_qa'] = security_qa = request.kenan.GetUserSecurityQuestion(session['confirmation_email_address']) if security_qa == False: self.log.info('Lost password for %s kenan security question query failed', session['confirmation_email_address']) session.destroy() flash(self.model.spiel('system_timeout', code='17ba0'), 'error') return redirect(url_for('lost_password_form')) request.response.data = render_template_string(request.templates['lost_password2'], security_qa=security_qa, templates=request.template_objects) elif phase == 3 and 'confirmation_answer_ok' in session: if 'pw_captcha' not in session: session['pw_captcha'] = captcha(request.gateway_session_id) self.log.info('Captcha Validation: %s', session['pw_captcha']._generate_words()) request.response.data = render_template_string(request.templates['lost_password3'], templates=request.template_objects) else: return redirect('/lost_password?phase=1') return request.response
def change_password_form(self): user = self.model.get_user_info_from_session() if not user: return abort(403) # only postpaid users allowed if user['domain'] not in ('postpaid.wifi.pldt.com.ph'): return abort(403) if 'sq' in request.args: if not self.model.security_questions: secqs = request.kenan.GetSecurityQuestions() if secqs == False: self.log.error('Security question fetch failed.') flash(self.model.spiel('system_timeout', code='63266'), 'error') return redirect('/pldt/status') self.model.security_questions = secqs request.log('SEQQ %s', self.model.security_questions) request.response.data = render_template_string(request.templates['change_security_qa'], security_questions=self.model.security_questions, templates=request.template_objects) return request.response else: request.response.data = render_template_string(request.templates['change_password'], templates=request.template_objects) return request.response
def main(cat=None): if cat: wiki = u'Wikipédia' c = conn(wiki) c.execute(u"""SELECT redir, COUNT(tl_from) marca, redireciona_para FROM (SELECT CONCAT(IF(r.page_namespace = 4, 'Wikipédia', 'Predefinição'), ':', r.page_title) redir, r.page_namespace ns, r.page_title title, CONCAT(IF(m.page_namespace = 4, 'Wikipédia', 'Predefinição'), ':', m.page_title) redireciona_para FROM categorylinks INNER JOIN page m ON cl_from = m.page_id INNER JOIN redirect ON (rd_namespace, rd_title) = (m.page_namespace, m.page_title) INNER JOIN page r ON rd_from = r.page_id WHERE cl_to = ? AND m.page_namespace IN (4, 10) ) marcas LEFT JOIN templatelinks ON (tl_namespace, tl_title) = (ns, title) GROUP BY redir ORDER BY marca""", (cat,)) r = c.fetchall() r = [(redir.decode('utf-8'), int(num), predef.decode('utf-8')) for redir, num, predef in r] if r: resp = {'wiki': wiki, 'link': link(wiki), 'lista': r} else: resp = {'aviso': u'A consulta não retornou resultados'} return render_template_string(page, title=u'Transclusões de redirecionamentos para predefinições da categoria ' + cat.replace(u'_', u' '), **resp) else: return render_template_string(page, title=u'Transclusões de redirecionametos para predefinições de uma categoria')
def classify_image(): global nr nr = nr + 1 try: data = flask.request.data # but data will be empty unless the request has the proper content-type header if not data: data = flask.request.form.keys()[0] # print data # data = urllib.decode(data) jdata = json.loads(data) data = jdata["json"] clazz = 'unknown' # jdata["class"] # learn if different from prediction net_name = 'speech' if "class" in jdata: clazz = jdata["class"] if "net" in jdata: net_name = jdata["net"] # data = bytearray(data) print len(data) image = np.asarray(data).astype(np.uint8) # egal? (np.float32) # (np.uint8) for imsave ! print "-------------------------" print image.shape if not clazz == 'unknown': skimage.io.imsave("/data/saved/classify_%s_%s.%d.png" % (net_name, clazz, nr), image) image = image[:, :, np.newaxis] result = app.clf.classify_image(image) if result[0]: print "YAY, got result %s" % result[2] return flask.render_template_string(str(result[2])) else: return flask.render_template_string("NONE") except Exception as err: logging.info('Upload image error: %s', err) traceback.print_exc(file=sys.stdout) return 'Upload image error: %s' % err
def main(cat=None): if cat: wiki = u'Wikipédia' c = conn(wiki) c.execute(u"""SELECT CONCAT(IF(page_namespace = 4, 'Wikipédia', 'Predefinição'), ':', page_title) p, COUNT(tl_title) t FROM (SELECT page_namespace, page_title FROM categorylinks INNER JOIN page ON cl_from = page_id WHERE cl_to = ? AND page_namespace IN (4, 10) ) predefs LEFT JOIN templatelinks ON (page_namespace, page_title) = (tl_namespace, tl_title) GROUP BY p ORDER BY t""", (cat,)) r = c.fetchall() r = [(u.decode('utf-8'), int(n)) for u, n in r] if r: resp = {'wiki': wiki, 'link': link(wiki), 'lista': r} else: resp = {'aviso': u'A consulta não retornou resultados'} return render_template_string(page, title=u'Transclusões de predefinições da categoria ' + cat.replace(u'_', u' '), **resp) else: return render_template_string(page, title=u'Transclusões de predefinições de uma categoria')
def send_doc(path): siteURL = current_app.config.get('SITE_URL') location = current_app.config.get('DOCS') if location is None: abort(404) if location[0:4]=='http': url = location + path req = requests.get(url, stream = True,headers={'Connection' : 'close'}) if req.headers['Content-Type'][0:9]=='text/html': return render_template_string(generate_template(current_app.config,'content.html'), siteURL=siteURL if siteURL is not None else request.url_root[0:-1], html=req.text, entry=None) else: return Response(stream_with_context(req.iter_content()), headers = dict(req.headers)) else: dir = os.path.abspath(location) if path.endswith('.html'): glob = StringIO() try: with open(os.path.join(dir,path), mode='r', encoding='utf-8') as doc: peeked = doc.readline() if peeked.startswith('<!DOCTYPE'): return send_from_directory(dir, path) glob.write(peeked) for line in doc: glob.write(line) return render_template_string(generate_template(current_app.config,'content.html'), siteURL=siteURL if siteURL is not None else request.url_root[0:-1], html=glob.getvalue(), entry=None) except FileNotFoundError: abort(404) return send_from_directory(dir, path)
def handler(path): root = "./data" service = path.split('/', 1)[0] if service in awsServices: action = request.form['Action'] if 'Action' in request.form else '' path = os.path.join(path.split('/', 1)[0], action) data_path = os.path.join(root, path) if os.path.isfile(data_path): contents = readDataFile(data_path) root = etree.fromstring(contents) filters = getFilters(request.form) if hasattr(awsServices[service], 'filter'): awsServices[service].filter(action, root, filters) return render_template_string(etree.tostring(root), remote_address=request.environ['REMOTE_ADDR']) return "" else: path = os.path.join('imds', path) data_path = os.path.join(root, path) if (os.path.isdir(data_path)) and path.endswith('/'): return '\n'.join(os.listdir(data_path)) elif os.path.isfile(data_path): contents = readDataFile(data_path) return render_template_string(contents, remote_address=request.environ['REMOTE_ADDR']) return imdsNotFoundXml
def vote(): v1_choice = request.args.get('video1') v2_choice = request.args.get('video2') v3_choice = request.args.get('video3') try: cuing_exp = CuingExperiment(userid=session['userid']) cuing_exp.log_event('vote', {'v1_choice': v1_choice, 'v2_choice': v2_choice, 'v3_choice': v3_choice}) return render_template_string(""" <html> <head> <title>Thank you</title> </head> <body> <p>Thank you for your selection</p> <p><a href="/">Back</a></p> </body> </html> """) except ValueError: return render_template_string(""" <html> <head> <title>Oops!</title> </head> <body> <p>Something went wrong</p> <p><a href="/">Back</a></p> </body> </html> """)
def bid(): bid_string = request.args.get('bid') bid_string = bid_string.replace(',', '') # get rid of commas try: bid_amount = int(bid_string) anchoring_exp = AnchoringExperiment(userid=session['userid']) anchoring_exp.log_event('bid', {'bid_amount': bid_amount}) return render_template_string(""" <html> <head> <title>Nice bid!</title> </head> <body> <p>You bid {{ bid }}. We'll be in touch if they accept your offer!</p> <p><a href="/">Back</a></p> </body> </html> """, bid=money_format(bid_amount)) except ValueError: return render_template_string(""" <html> <head> <title>Bad bid!</title> </head> <body> <p>You bid {{ bid }}. That's not a number, so we probably won't be accepting your bid.</p> <p><a href="/">Back</a></p> </body> </html> """, bid=bid_string)
def confirmation_form(self, formtype): if 'do' in request.args and request.args['do'] == 'resendactivationcode': if 'confirmation_mobile_number' in session: previous_confirmation = self.model.get_confirmation(session['confirmation_mobile_number'], formtype) if previous_confirmation: sms_string = self.model.spiel('activation_code') % (previous_confirmation['code']) self.log.debug('SMS: Resending "%s" to %s', sms_string, session['confirmation_mobile_number']) if not self.wide.sms.send(session['confirmation_mobile_number'], sms_string): self.log.error('smsc.send returned False') flash(self.model.spiel('system_timeout', code='9e6a5'), 'error') return redirect(url_for('login_form')) return redirect(url_for('%s_form' % (formtype)) + '?phase=2') return redirect(url_for('%s_form' % (formtype)) + '?phase=1') phase = int(request.args['phase']) if 'phase' in request.args else 1 self.log.info('Confirmation form phase %s type %s', phase, formtype) # if phase != 1 and 'confirmation_form_type' in session and session['confirmation_form_type'] != formtype: # self.log.debug('Jumping between lost_password and register?. Destroying session.') # session.destroy() # return redirect(url_for('login_form')) if phase == 1: session['confirmation_form_type'] = formtype request.response.data = render_template_string(request.templates['%s1' % (formtype)], templates=request.template_objects) elif phase == 2 and 'confirmation_mobile_number' in session: request.response.data = render_template_string(request.templates['%s2' % (formtype)], templates=request.template_objects) elif phase == 3 and 'confirmation_activation_ok' in session: request.response.data = render_template_string(request.templates['%s3' % (formtype)], templates=request.template_objects) else: return redirect(url_for('%s_form' % (formtype)) + '?phase=1') return request.response
def render(part, fmt, url=None): """ Attempt to render the PostPart <part> into MIME format <fmt>, which is usually 'text/plain' or 'text/html'. There are fall-backs for these two formats - otherwise you may have to handle a null return. """ if not url: url = url_for("content.raw", part_id=part.mime_part.id) ret = None renderer = renderer_exists(part.mime_part.type) if renderer: ret = renderer(part, fmt, url) if ret is not None: # might be empty string! return ret defaults = { "text/html": { True: lambda p: render_template_string("{{t}}", t=p.mime_part.text_preview), False: lambda p: render_template_string('<a href="{{u}}">(link)</a>', u=url), }, "text/plain": { True: lambda p: p.mime_part.text_preview, False: lambda p: render_template_string("Link: {{u}}", u=url), }, } if fmt in defaults: display_inline = bool(part.inline and part.mime_part.text_preview) return defaults[fmt][display_inline](part) return None
def auth(): data = dict(request.args.items()) if data['status'] == 'ok': response = make_response(render_template_string(HTML_TEMPLATE, **data)) for k, v in data.items(): response.set_cookie(k, v) return response return make_response(render_template_string(HTML_TEMPLATE, error=data['message']))
def template(): local_spec = spec.copy() for item in ('css', 'js', 'html'): if item in spec: local_spec[item] = flask.render_template_string( spec[item], **spec) return flask.render_template_string( spec['template'], **local_spec)
def test_pid_url(app): """Test pid_url.""" assert render_template_string( "{{ '10.123/foo'|pid_url }}") == "https://doi.org/10.123/foo" assert render_template_string( "{{ 'asfasdf'|pid_url }}") == "" assert render_template_string( "{{ 'arXiv:1512.01558'|pid_url(scheme='arxiv') }}") \ == "http://arxiv.org/abs/arXiv:1512.01558"
def _render(self, template, raises=None): val = u'm\xf6p' utfval = val.encode('utf-8') func = lambda x: x.encode('utf-8').decode('utf-8') if raises: self.assertRaises(raises, lambda: render_template_string(template, val=utfval, func=func)) else: self.assertEqual(render_template_string(template, val=val, func=func), render_template_string(template, val=utfval, func=func))
def test_jinja2_env(self): with app.app_context(): key = render_template_string("{{ idempotent_key() }}") input = render_template_string("{{ idempotent_input() }}") # This should not raise an error uuid.UUID(hex=key) self.assertIn('name="__idempotent_key"', input) self.assertIn('type="hidden"', input)
def test_local_doi(app): """Test template test.""" app.config['ZENODO_LOCAL_DOI_PREFIXES'] = ['10.123', '10.5281'] assert render_template_string( "{{ '10.123/foo' is local_doi }}") == "True" assert render_template_string( "{{ '10.1234/foo' is local_doi }}") == "False" assert render_template_string( "{{ '10.5281/foo' is local_doi }}") == "True"
def _render(template, raises=None): val = u'm\xf6p' utfval = val.encode('utf-8') func = lambda x: x.encode('utf-8').decode('utf-8') if raises: with pytest.raises(raises): render_template_string(template, val=utfval, func=func) else: assert (render_template_string(template, val=val, func=func) == render_template_string(template, val=utfval, func=func))
def xss_post_page(xss_id): if xss_id == '404': return render_template_string('') print '[+] XSS Payload Request: ID: ', xss_id, xss = Xss.query.filter_by(id=xss_id).scalar() if xss is None: return render_template_string("404") print xss.content, '|', xss.id, '|', xss.title return render_template('post.html', xss=xss)
def test_missing_arg(self): with SessionScope(db): title = AppText(name='landing title') title.custom_text = '_expanded_ {0}' db.session.add(title) db.session.commit() with pytest.raises(ValueError): render_template_string('<html></head><body>' '{{ app_text("landing title") }}' '<body/><html/>')
def index(): return render_template_string(index_template)
def home(): # youtube https://www.youtube.com/watch?v=AyLWeiJOdyw btn = '''<form method="post" action="/download?url=http://v.youku.com/v_show/id_XMzAyMzk2NzkxNg==.html?spm=a2hww.20023042.m_226600.5~5!2~5~5~5~5~A&f=49716696"> <button type="submit">Download!</button> </form>''' return render_template_string(btn)
def render_html(text, flatpages, page): prerendered_body = render_template_string(Markup(text)) return pygmented_markdown(prerendered_body, flatpages)
def config(redirect_url=None, custom_init='', custom_options='', **kwargs): """Initialize dropzone configuration. .. versionadded:: 1.4.4 :param redirect_url: The URL to redirect when upload complete. :param custom_init: Custom javascript code in ``init: function() {}``. :param custom_options: Custom javascript code in ``Dropzone.options.myDropzone = {}``. :param **kwargs: Mirror configuration variable, lowercase and without prefix. For example, ``DROPZONE_UPLOAD_MULTIPLE`` becomes ``upload_multiple`` here. """ if custom_init and not custom_init.strip().endswith(';'): custom_init += ';' if custom_options and not custom_options.strip().endswith(','): custom_options += ',' upload_multiple = kwargs.get( 'upload_multiple', current_app.config['DROPZONE_UPLOAD_MULTIPLE']) parallel_uploads = kwargs.get( 'parallel_uploads', current_app.config['DROPZONE_PARALLEL_UPLOADS']) if upload_multiple in [True, 'true', 'True', 1]: upload_multiple = 'true' else: upload_multiple = 'false' size = kwargs.get('max_file_size', current_app.config['DROPZONE_MAX_FILE_SIZE']) param = kwargs.get('input_name', current_app.config['DROPZONE_INPUT_NAME']) redirect_view = kwargs.get( 'redirect_view', current_app.config['DROPZONE_REDIRECT_VIEW']) if redirect_view is not None or redirect_url is not None: redirect_url = redirect_url or url_for(redirect_view) redirect_js = ''' this.on("queuecomplete", function(file) { // Called when all files in the queue finish uploading. window.location = "%s"; });''' % redirect_url else: redirect_js = '' max_files = kwargs.get('max_files', current_app.config['DROPZONE_MAX_FILES']) click_upload = kwargs.get( 'upload_on_click', current_app.config['DROPZONE_UPLOAD_ON_CLICK']) button_id = kwargs.get('upload_btn_id', current_app.config['DROPZONE_UPLOAD_BTN_ID']) in_form = kwargs.get('in_form', current_app.config['DROPZONE_IN_FORM']) cancelUpload = kwargs.get('cancel_upload', current_app.config['DROPZONE_CANCEL_UPLOAD']) removeFile = kwargs.get('remove_file', current_app.config['DROPZONE_REMOVE_FILE']) cancelConfirmation = kwargs.get( 'cancel_confirmation', current_app.config['DROPZONE_CANCEL_CONFIRMATION']) uploadCanceled = kwargs.get( 'upload_canceled', current_app.config['DROPZONE_UPLOAD_CANCELED']) if click_upload: if in_form: action = get_url( kwargs.get('upload_action', current_app.config['DROPZONE_UPLOAD_ACTION'])) click_listener = ''' dz = this; // Makes sure that 'this' is understood inside the functions below. document.getElementById("%s").addEventListener("click", function handler(e) { e.currentTarget.removeEventListener(e.type, handler); e.preventDefault(); e.stopPropagation(); dz.processQueue(); }); this.on("queuecomplete", function(file) { // Called when all files in the queue finish uploading. document.getElementById("%s").click(); }); ''' % (button_id, button_id) click_option = ''' url: "%s", autoProcessQueue: false, // addRemoveLinks: true, ''' % action else: click_listener = ''' dz = this; document.getElementById("%s").addEventListener("click", function handler(e) {dz.processQueue();}); ''' % button_id click_option = ''' autoProcessQueue: false, // addRemoveLinks: true, ''' upload_multiple = 'true' parallel_uploads = max_files if isinstance( max_files, int) else parallel_uploads else: click_listener = '' click_option = '' allowed_file_type = kwargs.get( 'allowed_file_type', current_app.config['DROPZONE_ALLOWED_FILE_TYPE']) allowed_file_custom = kwargs.get( 'allowed_file_custom', current_app.config['DROPZONE_ALLOWED_FILE_CUSTOM']) if allowed_file_custom: allowed_type = allowed_file_type else: allowed_type = allowed_file_extensions[allowed_file_type] default_message = kwargs.get( 'default_message', current_app.config['DROPZONE_DEFAULT_MESSAGE']) invalid_file_type = kwargs.get( 'invalid_file_type', current_app.config['DROPZONE_INVALID_FILE_TYPE']) file_too_big = kwargs.get('file_too_big', current_app.config['DROPZONE_FILE_TOO_BIG']) server_error = kwargs.get('server_error', current_app.config['DROPZONE_SERVER_ERROR']) browser_unsupported = kwargs.get( 'browser_unsupported', current_app.config['DROPZONE_BROWSER_UNSUPPORTED']) max_files_exceeded = kwargs.get( 'max_file_exceeded', current_app.config['DROPZONE_MAX_FILE_EXCEED']) timeout = kwargs.get('timeout', current_app.config['DROPZONE_TIMEOUT']) if timeout: custom_options += 'timeout: %d,' % timeout enable_csrf = kwargs.get('enable_csrf', current_app.config['DROPZONE_ENABLE_CSRF']) if enable_csrf: if 'csrf' not in current_app.extensions: raise RuntimeError( "CSRFProtect is not initialized. It's required to enable CSRF protect, \ see docs for more details.") csrf_token = render_template_string('{{ csrf_token() }}') custom_options += 'headers: {"X-CSRF-Token": "%s"},' % csrf_token return Markup( '''<script> Dropzone.options.myDropzone = { init: function() { %s // redirect after queue complete %s // upload queue when button click %s // custom init code }, %s // click upload options uploadMultiple: %s, parallelUploads: %d, paramName: "%s", // The name that will be used to transfer the file maxFilesize: %d, // MB acceptedFiles: "%s", maxFiles: %s, dictDefaultMessage: `%s`, // message display on drop area dictFallbackMessage: "%s", dictInvalidFileType: "%s", dictFileTooBig: "%s", dictResponseError: "%s", dictMaxFilesExceeded: "%s", dictCancelUpload: "%s", dictRemoveFile: "%s", dictCancelUploadConfirmation: "%s", dictUploadCanceled: "%s", %s // custom options code }; </script> ''' % (redirect_js, click_listener, custom_init, click_option, upload_multiple, parallel_uploads, param, size, allowed_type, max_files, default_message, browser_unsupported, invalid_file_type, file_too_big, server_error, max_files_exceeded, cancelUpload, removeFile, cancelConfirmation, uploadCanceled, custom_options))
def stream_data(): printLog('kwargs: {0}'.format(request.args)) dl_url = request.args.get('url') # printLog('download url: {0}'.format(dl_url)) if dl_url: # event = manager.Event() # 客户端关闭链接事件 # printLog('prepare to download') parent_conn, child_conn = multiprocessing.Pipe(False) result = pool.apply_async(start_download, args=(dl_url, child_conn)) # 开启子进程下载video if parent_conn.poll(timeout=15): # 尝试拉取数据 child_conn.close() # 在此关闭子进程的写管道,减少引用,又防止过早释放导致传入子进程的写管道为空 def stream_generate(pipe): # 生成器,返回小块的数据 while pipe.poll( timeout=15 ): # 设置超时时间太短在网速慢的情况下会造成传输中断(>=5),太长又会在有异常后造成并发量大 try: recv_data = pipe.recv() # 接收子进程发送来的数据 except EOFError: printLog('Nothing left or the other end was closed') return ('Nothing left or the other end was closed' ) # 子进程端管道已关闭 printLog('recv data from child_conn') if isinstance(recv_data, dict): # 接收到的为状态数据 youDLer_status = recv_data if youDLer_status['status'] == 'error': printLog('recv youtube-dl error message') return 'recv youtube-dl error message' else: index = youDLer_status['fragment_index'] - 1 # printLog('recv youtube-dl data with index: {0}'.format(index)) file_nto_read = youDLer_status[ 'filename'] + '.part-Frag' + str(index) printLog( 'send chunk data: {0}'.format(file_nto_read)) with open(file_nto_read, 'rb') as f: yield f.read() elif isinstance(recv_data, Exception): # 接收到的为异常 printLog( 'an exception occur at sub-process: {0}'.format( recv_data)) return 'an exception occur at sub-process' else: printLog('unknow exception occur at sub-process') return 'unknow exception occur at sub-process' else: printLog('poll sub-process data timeout') return 'poll sub-process data timeout' resp = Response(stream_with_context(stream_generate(parent_conn)), content_type='text/event-stream') resp.call_on_close(on_close) return resp else: printLog('poll data timeout') return render_template_string("poll data timeout") # 第一次拉取数据就超时 else: printLog('video url error!') return render_template_string('video url error!') # 参数错误
def _getBody(self, params): # Legacy handling for pages that do not use Jinja inheritance. tpl = "{% extends 'rb/base.html' %}{% block content %}{{ _body | safe }}{% endblock %}" body = to_unicode(self._getPageContent(params)) return render_template_string(tpl, _body=body, **self._kwargs)
def home(): """Homepage route""" all_labels = ["No labels yet"] ##### # s3 getting a list of photos in the bucket ##### s3_client = boto3.client('s3') prefix = "photos/" response = s3_client.list_objects( Bucket=config.PHOTOS_BUCKET, Prefix=prefix ) photos = [] if 'Contents' in response and response['Contents']: photos = [s3_client.generate_presigned_url( 'get_object', Params={'Bucket': config.PHOTOS_BUCKET, 'Key': content['Key']} ) for content in response['Contents']] form = PhotoForm() url = None if form.validate_on_submit(): image_bytes = util.resize_image(form.photo.data, (300, 300)) if image_bytes: ####### # s3 excercise - save the file to a bucket ####### key = prefix + util.random_hex_bytes(8) + '.png' s3_client.put_object( Bucket=config.PHOTOS_BUCKET, Key=key, Body=image_bytes, ContentType='image/png' ) # http://boto3.readthedocs.io/en/latest/guide/s3.html#generating-presigned-urls url = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': config.PHOTOS_BUCKET, 'Key': key}) ####### # rekcognition exercise ####### rek = boto3.client('rekognition') response = rek.detect_labels( Image={ 'S3Object': { 'Bucket': config.PHOTOS_BUCKET, 'Name': key } }) all_labels = [label['Name'] for label in response['Labels']] return render_template_string(""" {% extends "main.html" %} {% block content %} <h4>Upload Photo</h4> <form method="POST" enctype="multipart/form-data" action="{{ url_for('home') }}"> {{ form.csrf_token }} <div class="control-group"> <label class="control-label">Photo</label> {{ form.photo() }} </div> <div class="control-group"> <div class="controls"> <input class="btn btn-primary" type="submit" value="Upload"> </div> </div> </form> {% if url %} <hr/> <h3>Uploaded!</h3> <img src="{{url}}" /><br/> {% for label in all_labels %} <span class="label label-info">{{label}}</span> {% endfor %} {% endif %} {% if photos %} <hr/> <h4>Photos</h4> {% for photo in photos %} <img width="150" src="{{photo}}" /> {% endfor %} {% endif %} {% endblock %} """, form=form, url=url, photos=photos, all_labels=all_labels)
def test2_multiprocess(): return render_template_string('test2 response')
def page_not_found(e): template = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Page not found error!</title> <!-- Bootstrap Core CSS --> <link href="static/css/bootstrap.min.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="static/css/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="static/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Custom CSS --> <link href="static/css/startmin.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" style="background-color:#00C8A1" role="navigation"> <div class="navbar-header"> <a class="navbar-brand" href="#" style="color:white;">Hacking assessment</a> </div> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- Sidebar --> <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> </div> </div> </nav> <!-- Page Content --> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-12"> </div> </div> <h1 class="page-header">Page not found!</h1> <pre> the page you where looking for at <b>{0}</b>, was not found! </pre> </p>Please follow this link to return to <a href="/dashboard/1" style="color:blue;">home</a> </div> </div> </div> <!-- jQuery --> <script src="static/js/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="static/js/bootstrap.min.js"></script> <!-- Metis Menu Plugin JavaScript --> <script src="static/js/metisMenu.min.js"></script> <!-- Custom Theme JavaScript --> <script src="static/js/startmin.js"></script> </body> </html> """.format(request.url) return render_template_string(template)
def getx(): return render_template_string('{{request.args.get("x")}}')
def test_markdown_linkify_within_pre(self): '''Markdown filter should not transform urls into <pre> anchors''' text = '<pre>http://example.net/</pre>' with self.app.test_request_context('/'): result = render_template_string('{{ text|markdown }}', text=text) self.assertEqual(result.strip(), '<pre>http://example.net/</pre>')
def getx_safe(): # it is actually unsafe! return render_template_string('{{request.args.get("x")|safe}}')
def getargs(): return render_template_string('{{request.args}}')
def psiturk_js(): ''' psiTurk js route ''' return render_template_string(PSITURK_JS_CODE)
def render(self, template): """Helper method to render a snippet of a form""" return render_template_string(template, form=self.form).strip()
def mardown_template_block(): test = '*test*' text = '{% filter markdown %}{{ test }}{% endfilter %}' return render_template_string(text, test=test)
def admin(): return render_template_string("hy")
def create_person(): cur = conn.cursor() institutes = {} departments = {} labs = {} cur.execute('SELECT id, name, type from organizations') for row in cur.fetchall(): if row[2] == 'institute': institutes[row[1]] = row[0] elif row[2] == 'department': departments[row[1]] = row[0] elif row[2] == 'lab': labs[row[1]] = row[0] else: pass # what do we do cur.close() if request.method == 'POST': cur = conn.cursor() try: first_name = request.form['first_name'].strip() last_name = request.form['last_name'].strip() email = request.form['email'].strip() phone = request.form['phone'].strip() institute = request.form['institute'].strip() department = request.form['department'].strip() lab = request.form['lab'].strip() if first_name is '' or last_name is '': flash('First and last name are required') return redirect(request.url) cur.execute( 'INSERT INTO people (display_name, email, phone) VALUES (%s, %s, %s) RETURNING id', (first_name + ' ' + last_name, email, phone)) id = cur.fetchone()[0] cur.execute( 'INSERT INTO names (person_id, first_name, last_name) VALUES (%s, %s, %s)', (id, first_name, last_name)) if institute is not '': if institute in institutes: cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (institutes[institute], id)) else: cur.execute( 'INSERT INTO organizations (name, type) VALUES (%s, %s) RETURNING id', (institute, 'institute')) org_id = cur.fetchone()[0] cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (org_id, id)) if department is not '': if department in departments: cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (departments[department], id)) else: cur.execute( 'INSERT INTO organizations (name, type) VALUES (%s, %s) RETURNING id', (department, 'department')) org_id = cur.fetchone()[0] cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (org_id, id)) if lab is not '': if lab in labs: cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (labs[lab], id)) else: cur.execute( 'INSERT INTO organizations (name, type) VALUES (%s, %s) RETURNING id', (lab, 'lab')) org_id = cur.fetchone()[0] cur.execute( 'INSERT INTO associations (organization_id, person_id) VALUES (%s, %s)', (org_id, id)) conn.commit() flash('Person created successfully') except psycopg2.IntegrityError as e: conn.rollback() if e.pgcode == psycopg2.errorcodes.UNIQUE_VIOLATION: flash('First and Last name pair must be unique') else: print(e) flash('Other integrity error') except Exception as e: print(e) conn.rollback() flash('Error creating a new person') finally: cur.close() return redirect(request.url) return render_template_string(''' <!doctype html> <head> <title>Create a new Person</title> </head> <body> <h1>Create a new Person</h1> <a href="/">Back to Home</a> {% with messages = get_flashed_messages() %} {% if messages %} {% for message in messages %} {{ message }} <br/> {% endfor %} {% endif %} {% endwith %} <form method=post enctype=multipart/form-data> <label>First Name</label> <input type=text name=first_name required> <label>Last Name</label> <input type=text name=last_name required> <label>Email</label> <input type=email name=email> <label>Phone Number</label> <input type=tel name=phone> <label>Institute</label> <input list=institutes name=institute> <datalist id=institutes> {% for inst in instituteList %} <option value="{{inst}}"> {% endfor %} </datalist> <label>Department</label> <input list=departments name=department> <datalist id=departments> {% for dept in departmentList %} <option value="{{dept}}"> {% endfor %} </datalist> <label>Labs</label> <input list=labs name=lab> <datalist id=labs> {% for labItem in labList %} <option value="{{labItem}}"> {% endfor %} </datalist> <input type=submit value=Create> </form> </body> ''', instituteList=institutes.keys(), departmentList=departments.keys(), labList=labs.keys())
def test_markdown_linkify_email_within_pre(self): '''Markdown filter should not transform emails into <pre> anchors''' text = '<pre>[email protected]</pre>' with self.app.test_request_context('/'): result = render_template_string('{{ text|markdown }}', text=text) self.assertEqual(result.strip(), '<pre>[email protected]</pre>')
def test_undefined_raising(template): with pytest.raises(UndefinedError): render_template_string(template, d={})
def mardown_template_filter(): text = '~~testing markdown filter~~ *test*' return render_template_string('{{ text|markdown }}', text=text)
def traffic_story(item, **kwargs): # The place is used to determine the state the the requests will be limited to if 'place' in item and len(item.get('place')): state = item.get('place')[0].get('qcode').upper() else: return # Current time in UTC to restrict the query to incidents that are currently active today = utcnow() # Also include incidents that started in the last 24 hours yesterday = today - timedelta(hours=24) service = get_resource_service('traffic_incidents') req = ParsedRequest() areas = get_areas().get('features') incidents_map = dict() incidents_html = '' roadworks_html = '' # Scan the areas in the state. for area in [ a for a in areas if a.get('properties', {}).get('state', '').upper() == state ]: base_query = { '$and': [{ 'state': state }, { 'end_date': { '$gt': today } }, { 'start_date': { '$lt': today, '$gt': yesterday } }, { 'incident_type': { '$ne': 'This message is for test purposes only , please ignore' } }, { 'geometry': { '$geoIntersects': { '$geometry': { 'type': 'Polygon', 'coordinates': area.get('geometry').get('coordinates') } } } }] } incident_query = deepcopy(base_query) # Append clauses that will exclude road works incident_query['$and'] += [{ 'incident_type': { '$ne': 'Roadworks' } }, { 'incident_description': { '$not': re.compile('.*{}.*'.format('Maintenance work'), re.IGNORECASE) } }, { 'incident_description': { '$not': re.compile('.*{}.*'.format('Roadworks'), re.IGNORECASE) } }] incidents = service.get_from_mongo(req=req, lookup=incident_query) if incidents.count(): incidents_html += '<p><b>{}</b></p>'.format( area['properties']['area']) for i in incidents: message = i.get('incident_description').replace( 'lorr(y/ies)', 'truck') message = message.replace('Accident(s)', 'Accident') incidents_html += '<p>{}</p>'.format(message) roadworks_query = deepcopy(base_query) # Append a clause that restrict to roadworks only roadworks_query['$and'].append({ '$or': [{ 'incident_type': 'Roadworks' }, { 'incident_description': re.compile('.*{}.*'.format('Maintenance work'), re.IGNORECASE) }, { 'incident_description': re.compile('.*{}.*'.format('Roadworks'), re.IGNORECASE) }] }) roadworks = service.get_from_mongo(req=req, lookup=roadworks_query) if roadworks.count(): roadworks_html += '<p><b>{}</b></p>'.format( area['properties']['area']) for i in roadworks: roadworks_html += '<p>{}</p>'.format( i.get('incident_description')) incidents_map[ 'incidents'] = 'No incidents at this time.' if incidents_html == '' else incidents_html incidents_map[ 'roadworks'] = 'No roadworks at this time.' if roadworks_html == '' else roadworks_html item['body_html'] = render_template_string(item.get('body_html', ''), **incidents_map) update = {'source': 'Intelematics'} ingest_provider = get_resource_service('ingest_providers').find_one( req=None, source='Intelematics') if ingest_provider: update['ingest_provider'] = ingest_provider.get(config.ID_FIELD) update['body_html'] = item['body_html'] get_resource_service('archive').system_update(item[config.ID_FIELD], update, item) item['source'] = 'Intelematics' # If the macro is being executed by a scheduled template then publish the item as well if 'desk' in kwargs and 'stage' in kwargs: get_resource_service('archive_publish').patch( id=item[config.ID_FIELD], updates={ ITEM_STATE: CONTENT_STATE.PUBLISHED, 'auto_publish': True }) return get_resource_service('archive').find_one( req=None, _id=item[config.ID_FIELD]) return item
def index(): return render_template_string(app.template_string, args=app.args)
def yaml_form(): templatepath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'delete.html')) with open(templatepath, 'r') as templatefile: return render_template_string(templatefile.read())
def admin_index(): return flask.render_template_string('{{ a }}{{ b }}{{ c }}')
def test_multiprocess2(): result = pool.apply_async(start_test2, (10, )) return render_template_string('test1 multiprocess {0}'.format( result.get()))
def test_undefined_silent(template): assert render_template_string(template, d={'bar': {}}) == 'ok'
def test_multiprocess(): q = multiprocessing.Queue() p = multiprocessing.Process(target=start_test, args=(q, 10)) p.start() return render_template_string('test multiprocess {0}'.format(q.get()))
def index(): return render_template_string(html)
def advertisement(): """ This is the url we give for the ad for our 'external question'. The ad has to display two different things: This page will be called from within mechanical turk, with url arguments hitId, assignmentId, and workerId. If the worker has not yet accepted the hit: These arguments will have null values, we should just show an ad for the experiment. If the worker has accepted the hit: These arguments will have appropriate values and we should enter the person in the database and provide a link to the experiment popup. """ user_agent_string = request.user_agent.string user_agent_obj = user_agents.parse(user_agent_string) browser_ok = True for rule in string.split( CONFIG.get('HIT Configuration', 'browser_exclude_rule'), ','): myrule = rule.strip() if myrule in ["mobile", "tablet", "touchcapable", "pc", "bot"]: if (myrule == "mobile" and user_agent_obj.is_mobile) or\ (myrule == "tablet" and user_agent_obj.is_tablet) or\ (myrule == "touchcapable" and user_agent_obj.is_touch_capable) or\ (myrule == "pc" and user_agent_obj.is_pc) or\ (myrule == "bot" and user_agent_obj.is_bot): browser_ok = False elif (myrule == "Safari" or myrule == "safari"): if "Chrome" in user_agent_string and "Safari" in user_agent_string: pass elif "Safari" in user_agent_string: browser_ok = False elif myrule in user_agent_string: browser_ok = False if not browser_ok: # Handler for IE users if IE is not supported. raise ExperimentError('browser_type_not_allowed') if not ('hitId' in request.args and 'assignmentId' in request.args): raise ExperimentError('hit_assign_worker_id_not_set_in_mturk') hit_id = request.args['hitId'] assignment_id = request.args['assignmentId'] mode = request.args['mode'] if hit_id[:5] == "debug": debug_mode = True else: debug_mode = False already_in_db = False if 'workerId' in request.args: worker_id = request.args['workerId'] # First check if this workerId has completed the task before (v1). nrecords = Participant.query.\ filter(Participant.assignmentid != assignment_id).\ filter(Participant.workerid == worker_id).\ count() if nrecords > 0: # Already completed task already_in_db = True else: # If worker has not accepted the hit worker_id = None try: part = Participant.query.\ filter(Participant.hitid == hit_id).\ filter(Participant.assignmentid == assignment_id).\ filter(Participant.workerid == worker_id).\ one() status = part.status except exc.SQLAlchemyError: status = None if status == STARTED and not debug_mode: # Once participants have finished the instructions, we do not allow # them to start the task again. raise ExperimentError('already_started_exp_mturk') elif status == COMPLETED: use_psiturk_ad_server = CONFIG.getboolean('Shell Parameters', 'use_psiturk_ad_server') if not use_psiturk_ad_server: # They've finished the experiment but haven't submitted the HIT # yet.. Turn asignmentId into original assignment id before sending it # back to AMT return render_template('thanks-mturksubmit.html', using_sandbox=(mode == "sandbox"), hitid=hit_id, assignmentid=assignment_id, workerid=worker_id) else: # `thanks.html` was taken out in v2 with the introduction of the psiturk ad server # but put back in in v2.1.2 because "local thanks page needed when reloading the # local ad and a worker has already completed the task." As far as I, @deargle, can interpret, # a user, be they an AMT worker or not, should not typically reach this page unless # they're fooling around with URLs. # # Show them a thanks message and tell them to go away. return render_template('thanks.html') elif already_in_db and not debug_mode: raise ExperimentError('already_did_exp_hit') elif status == ALLOCATED or not status or debug_mode: # Participant has not yet agreed to the consent. They might not # even have accepted the HIT. with open('templates/ad.html', 'r') as temp_file: ad_string = temp_file.read() ad_string = insert_mode(ad_string, mode) return render_template_string(ad_string, hitid=hit_id, assignmentid=assignment_id, workerid=worker_id) else: raise ExperimentError('status_incorrectly_set')