def handle_error(request, response, exception): c = {"exception": str(exception), "url": request.url} if config.send_mail_developer is not False: # send email subject = config.app_name + " error." email_body_path = "emails/error.txt" message = "This error was looking for you: " + c["exception"] + " from " + c["url"] if c["exception"] is not "Error saving Email Log in datastore": template_val = {"app_name": config.app_name, "message": message} email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template( email_body_path, **template_val ) email_url = webapp2.uri_for("taskqueue-send-email") for dev in config.DEVELOPERS: taskqueue.add( url=email_url, params={"to": dev[1], "subject": subject, "body": email_body, "sender": config.contact_sender}, ) status_int = hasattr(exception, "status_int") and exception.status_int or 500 template = config.error_templates[status_int] t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c) logging.error(str(status_int) + " - " + str(exception)) response.write(t) response.set_status(status_int)
def handle_error(request, response, exception): c = { 'exception': str(exception), 'url': request.url, } if config.send_mail_developer is not False: # send email subject = config.app_name + " error." email_body_path = "emails/error.txt" message = 'This error was looking for you: ' + c['exception'] + ' from ' + c['url'] if c['exception'] is not 'Error saving Email Log in datastore': template_val = { "app_name" : config.app_name, "message" : message, } email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(email_body_path, **template_val) email_url = webapp2.uri_for('taskqueue-send-email') for dev in config.DEVELOPERS: taskqueue.add(url = email_url, params={ 'to': dev[1], 'subject' : subject, 'body' : email_body, 'sender' : config.contact_sender, }) status_int = hasattr(exception, 'status_int') and exception.status_int or 500 template = config.error_templates[status_int] t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c) logging.error(str(status_int) + " - " + str(exception)) response.write(t) response.set_status(status_int)
def handle_error(request, response, exception): exc_type, exc_value, exc_tb = sys.exc_info() c = {"exception": str(exception), "url": request.url} if request.app.config.get("send_mail_developer") is not False: # send email subject = "[{}] ERROR {}".format( request.app.config.get("environment").upper(), request.app.config.get("app_name") ) lines = traceback.format_exception(exc_type, exc_value, exc_tb) message = ( "<strong>Type:</strong> " + exc_type.__name__ + "<br />" + "<strong>Description:</strong> " + c["exception"] + "<br />" + "<strong>URL:</strong> " + c["url"] + "<br />" + "<strong>Traceback:</strong> <br />" + "<br />".join(lines) ) email_body_path = "emails/error.txt" if c["exception"] is not "Error saving Email Log in datastore": template_val = {"app_name": request.app.config.get("app_name"), "message": message} email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template( email_body_path, **template_val ) email_url = webapp2.uri_for("taskqueue-send-email") for dev in request.app.config.get("developers"): taskqueue.add( url=email_url, params={ "to": dev[1], "subject": subject, "body": email_body, "sender": request.app.config.get("contact_sender"), }, ) status_int = hasattr(exception, "status_int") and exception.status_int or 500 template = request.app.config.get("error_templates")[status_int] t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c) logging.error(str(status_int) + " - " + str(exception)) response.write(t) response.set_status(status_int)
def __init__(self, request, response): self.initialize( request, response ) # ログインしてなかったらログイン画面に飛ばす if users.is_current_user_admin() == False: self.redirect( users.create_login_url(self.request.uri) ) return # サイドバー HTML を jinja2 の globals に登録 sidebar_str = jinja2.get_jinja2().render_template( 'sidebar.html', **{ "customObjects": config.CUSTOM_OBJECTS, }) jinja2.get_jinja2().environment.globals["sidebar"] = sidebar_str
def error(request, response, exception): logging.exception(exception) params = { 'error': exception } jinja = jinja2.get_jinja2() response.write(jinja.render_template('error.html', **params))
def list( self, class_name ): # 文字列からモデルクラス、エンティティ取得 classPath_str = "models."+ class_name.capitalize() klass = webapp2.import_string( classPath_str ) # entities = klass.query( klass.is_deleted==False ).order( -klass.created_at ) entities = klass.query() entities_json = [] for entity in entities: entities_json.append( entity.toDict() ) # プロパティ情報を dict に入れる props = [] for prop in klass.__dict__["_properties"]: props.append({ "name": prop, "className": getattr(klass,prop).__class__.__name__, }) # logging.info( props ) res = jinja2.get_jinja2().render_template( 'admin/list.html', **{ "entities": entities, "entities_json": json.encode( entities_json ), "props": props, "class_name": class_name, }) self.response.out.write( res )
def handle_404(request, response, exception): logging.exception(exception) renderer = jinja2.get_jinja2() response.write(renderer.render_template('errors/404.html')) response.set_status(404)
def handle_error(request, response, exception): c = { 'exception': str(exception) } status_int = hasattr(exception, 'status_int') and exception.status_int or 500 template = config.error_templates[status_int] t = jinja2.get_jinja2(app=app).render_template(template, **c) response.write(t) response.set_status(status_int)
def jinja2(self): # Returns a Jinja2 renderer cached in the app registry. jinja2_obj = jinja2.get_jinja2(app=self.app) jinja2_obj.environment.filters['format_currency'] = self.format_currency return jinja2_obj
def render(self, name, value, attrs=None): # TODO: handle other data types # this currently only works for issubclass(self.property.item_type, db.Key) objects = [] object_classes = self.object_classes keys = value or [] for key in keys: if not key: continue # Turn string keys into Key objects if isinstance(key, basestring): key = db.Key(key) obj = db.get(key) objects.append((key, obj)) object_classes[obj.__class__.__name__] = obj.__class__ final_attrs = self.build_attrs(attrs, name=name) flat_attrs = flatatt(final_attrs) from .handlers import AdminHandler handler = AdminHandler() from webapp2_extras import jinja2 return jinja2.get_jinja2().render_template( 'widgets/ajax_list_property.html', flat_attrs=flat_attrs, objects=objects, object_classes=object_classes, get_item_edit_url=partial(self._get_item_edit_url, handler=handler), name=name, paged_selector=partial(self._paged_selector, handler=handler), )
def test_set_jinja2(self): app = webapp2.WSGIApplication() self.assertEqual(len(app.registry), 0) jinja2.set_jinja2(jinja2.Jinja2(app), app=app) self.assertEqual(len(app.registry), 1) j = jinja2.get_jinja2(app=app) self.assertTrue(isinstance(j, jinja2.Jinja2))
def jinja2(self): """Cached property holding a Jinja2 instance. Returns: A Jinja2 object for the current app. """ return jinja2.get_jinja2(app=self.app)
def handler(request, response, exception): logging.exception(exception) app = webapp2.get_app() j = jinja2.get_jinja2(app=app) rv = j.render_template("errors/" + str(code) + ".html") response.write(rv) response.set_status(code)
def handle_500(request, response, exception): t = jinja2.get_jinja2(app=application).render_template( 'errors/500.html', **{ 'exception': exception.message, # 'application': Config.get('application'), }) response.write(t)
def ErrorHandler(request, response, exception, code): """A webapp2 implementation of error_handler.""" logging.info('ErrorHandler code %s' % code) logging.info('Exception: %s' % exception) response.set_status(code) response.headers['Access-Control-Allow-Origin'] = \ request.headers.get('Origin', '*') response.headers['Access-Control-Allow-Methods'] = \ 'GET, POST, OPTIONS, PUT' response.headers['Access-Control-Allow-Credentials'] = 'true' response.headers['Access-Control-Allow-Headers'] = \ 'Content-Type,X-Requested-With' # Default UA string is for unit tests. user_agent_string = request.headers.get( 'USER_AGENT', settings.USER_AGENT) ua_dict = user_agent_parser.Parse(user_agent_string) logging.info('UA: %s' % ua_dict) tpl_data = { 'error_code': code, 'error_code_text': httplib.responses[code], 'error_message': exception, 'user_agent': ua_dict } jinja2_instance = jinja2.get_jinja2() rendered = jinja2_instance.render_template('error.html', **tpl_data) response.write(rendered)
def jinja2(self): from webapp2_extras import jinja2 # Returns a Jinja2 renderer cached in the app registry. j = jinja2.get_jinja2(app=self.app) j.environment.variable_start_string = '@{' j.environment.variable_end_string = '}@' return j
def jinja2(self): def factory(app): config = jinja2.default_config config['template_path'] = app.config['template_path'] config['environment_args']['line_statement_prefix'] = '%' return jinja2.Jinja2(app, config) return jinja2.get_jinja2(factory=factory, app=self.app)
def jinja2(self): """ xxx todo """ j = jinja2.get_jinja2(app=self.app) # not good. j.environment.globals.update({ 'uri_for': self.uri_for, }) return j
def jinja2(self): jinja2.default_config['template_path'] = configuration.VIEW_PATH jinja2.default_config['globals'] = { 'get_route': get_route } return jinja2.get_jinja2(app=self.app)
def handle_404(request, response, exception): t = jinja2.get_jinja2(app=application).render_template( 'errors/404.html', **{ 'exception': exception.status, 'application': Config.get('application'), }) response.write(t) response.set_status(exception.status_int)
def handle_error(request, response, exception): c = { 'exception': str(exception) } status_int = hasattr(exception, 'status_int') and exception.status_int or 500 template = config.error_templates[status_int] t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c) logging.error(str(status_int) + " - " + str(exception)) response.write(t) response.set_status(status_int)
def show_404(request, response, exception): z=request.get('z') from webapp2_extras import jinja2 jr=jinja2.get_jinja2(lambda app: jinja2.Jinja2(app=app, config={'environment_args':{'autoescape':False},'filters':{}})) context = {'z':z} response.write(jr.render_template('404.html', **context)) response.set_status(404)
def handle_error(request, response, exception): exc_type, exc_value, exc_tb = sys.exc_info() c = { 'exception': str(exception), 'url': request.url, } if request.app.config.get('send_mail_developer') is not False: # send email subject = "[{}] ERROR {}".format(request.app.config.get('environment').upper(), request.app.config.get('app_name')) lines = traceback.format_exception(exc_type, exc_value, exc_tb) ua = httpagentparser.detect(request.user_agent) _os = ua.has_key('flavor') and 'flavor' or 'os' operating_system = str(ua[_os]['name']) if "name" in ua[_os] else "-" if 'version' in ua[_os]: operating_system += ' ' + str(ua[_os]['version']) if 'dist' in ua: operating_system += ' ' + str(ua['dist']) browser = str(ua['browser']['name']) if 'browser' in ua else "-" browser_version = str(ua['browser']['version']) if 'browser' in ua else "-" message = '<strong>Application ID:</strong> ' + app_identity.get_application_id() + "<br />" + \ '<strong>Application Version:</strong> ' + os.environ['CURRENT_VERSION_ID'] + "<br />" + \ '<hr><strong>User Agent:</strong> ' + str(request.user_agent) + "<br />" + \ '<strong>IP Address:</strong> ' + str(request.remote_addr) + "<br />" + \ '<strong>Operating System:</strong> ' + str(operating_system) + "<br />" + \ '<strong>Browser:</strong> ' + str(browser) + "<br />" + \ '<strong>Browser Version:</strong> ' + str(browser_version) + "<br />" + \ '<hr><strong>Error Type:</strong> ' + exc_type.__name__ + "<br />" + \ '<strong>Description:</strong> ' + c['exception'] + "<br />" + \ '<strong>Method:</strong> ' + str(os.environ['REQUEST_METHOD']) + "<br />" + \ '<strong>URL:</strong> ' + c['url'] + "<br />" + \ '<strong>Referer:</strong> ' + str(request.referer) + "<br />" + \ '<strong>Traceback:</strong> <br />' + '<br />'.join(lines) if c['exception'] is not 'Error saving Email Log in datastore': email_url = webapp2.uri_for('taskqueue-send-email') for dev in request.app.config.get('developers'): taskqueue.add(url=email_url, params={ 'to': dev[1], 'subject': subject, 'body': message, 'sender': request.app.config.get('contact_sender'), }) status_int = hasattr(exception, 'status_int') and exception.status_int or 500 template = request.app.config.get('error_templates')[status_int] t = jinja2.get_jinja2(app=webapp2.get_app()).render_template(template, **c) logging.error("Error {}: {}".format(status_int, exception)) response.write(t) response.set_status(status_int)
def handle_error(request, response, exception): exc_type, exc_value, exc_tb = sys.exc_info() c = { 'exception': str(exception), 'url': request.url, 'long_exception': ''.join(traceback.format_exception(exc_type, exc_value, exc_tb)) } if request.app.config.get('send_mail_developer') is not False: # send email subject = "[{}] ERROR {}".format(request.app.config.get('environment').upper(), request.app.config.get('app_name')) lines = traceback.format_exception(exc_type, exc_value, exc_tb) message = '<strong>Type:</strong> ' + exc_type.__name__ + "<br />" + \ '<strong>Description:</strong> ' + c['exception'] + "<br />" + \ '<strong>URL:</strong> ' + c['url'] + "<br />" + \ '<strong>Traceback:</strong> <br />' + '<br />'.join(lines) email_body_path = "emails/error.txt" if c['exception'] is not 'Error saving Email Log in datastore': template_val = { "app_name" : request.app.config.get('app_name'), "message" : message, } email_body = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(email_body_path, **template_val) email_url = webapp2.uri_for('taskqueue-send-email') for dev in request.app.config.get('developers'): taskqueue.add(url = email_url, params={ 'to': dev[1], 'subject' : subject, 'body' : email_body, 'sender' : request.app.config.get('contact_sender'), }) status_int = hasattr(exception, 'status_int') and exception.status_int or 500 template = request.app.config.get('error_templates')[status_int] t = jinja2.get_jinja2(factory=jinja2_factory, app=webapp2.get_app()).render_template(template, **c) logging.error(str(status_int) + " - " + str(exception)) # logging.error(traceback.format_exception(exc_type, exc_value, exc_tb)) response.write(t) response.set_status(status_int)
def jinja2(self): """Returns a Jinja2 renderer cached in the app registry""" j = jinja2.get_jinja2(app=self.app) j.environment.filters['date'] = jinja2_date_filter # fix Angular template, jinja template conflict j.environment.variable_start_string = '{{ ' j.environment.variable_end_string == ' }}' return j
def get(self, artist): logging.info(artist) qry = artist_db.ArtistProfile.query(artist_db.ArtistProfile.user_name == artist).get() if qry: j2 = jinja2.get_jinja2() template = j2.render_template('artist.html') self.response.write(template) else: self.redirect('/')
def get(): # Make sure configuration is imported before we ever initialize, which should only happen once per request import config_jinja global SHARED_APP if SHARED_APP is None: SHARED_APP = webapp2.WSGIApplication(debug=App.is_dev_server) return jinja2.get_jinja2(app=SHARED_APP)
def sitemap(request): """ Generate sitemap.xml. Processes GET and POST requests. """ keys = Snippet.all(keys_only=True).order("-date") jinja = jinja2.get_jinja2(app=webapp2.get_app()) return create_response({"Content-Type": "text/xml; charset=utf-8"}, jinja.render_template("sitemap.xml", keys=keys))
def RenderResponse(self, template, **context): """Use Jinja2 instance to render template and write to output. Args: template: filename (relative to $PROJECT/templates) that we are rendering context: keyword arguments corresponding to variables in template """ jinja2_renderer = jinja2.get_jinja2(app=self.app) rendered_value = jinja2_renderer.render_template(template, **context) self.response.write(rendered_value)
def render_response(self, template, **context): """ Render given template with jinja2 tempalte engine to body. Template is the filename of the template in the tempaltes directory. Keyword arguments are mapped to templates variables. """ # context['is_dev'] = is_dev() # Renders a template and writes the result to the response. body = jinja2.get_jinja2(app=self.app).render_template(template, **context) self.response.write(body)
def get(self): # get users nickname to add on list search def getUsers(): us = User.query() toret = [] for u in us: toret.append(u.nickname) user_list = json.dumps(toret) return user_list jinja = jinja2.get_jinja2(app=self.app) user = users.get_current_user() user_id = user.user_id() if user == None: self.redirect(users.create_logout_url("/")) else: msg =self.request.get("msg") if msg == "": msg = None user_info = User.query(User.id_user == user_id) labels = { "user_info" : user_info, "user_logout": users.create_logout_url("/"), "usersearch": getUsers(), "msg": msg } self.response.write(jinja.render_template("profile.html", **labels))
def get(self): try: id = self.request.GET['section_id'] except: self.redirect("/error?msg=Key missing for deletion.") return user = users.get_current_user() if user: user_name = user.nickname() access_link = users.create_logout_url("/") try: section = ndb.Key(urlsafe=id).get() chapter = Chapter.get_by_id(section.chapter) story = Story.get_by_id(chapter.story) except: self.redirect("/error?msg=Key was not found.") return template_values = { "info": AppInfo, "user_name": user_name, "access_link": access_link, "story": story, "chapter": chapter, "section": section } jinja = jinja2.get_jinja2(app=self.app) self.response.write( jinja.render_template("delete_section.html", **template_values)) else: self.redirect("/")
def post(self): login.logging_user(self) recetas = Recipe.query() recipe_id = self.request.get("id") comments_author = self.request.get("author") comments_content = self.request.get("content") comments_title = self.request.get("title-commment") if comments_author != "" and comments_content != "" and recipe_id != "" and comments_title != "": comentario = Comment(author=comments_author, comment=comments_content, recipe_id=recipe_id, title=comments_title) comentario.put() time.sleep(0.5) comentarios = Comment.query(Comment.recipe_id == str(recipe_id)) receta_actual = None for receta in recetas: if str(receta.key.id()) == recipe_id: receta_actual = receta template_values = { 'receta_actual': receta_actual, 'comentarios': comentarios } jinja = jinja2.get_jinja2(app=self.app) self.response.write( jinja.render_template("recipeView.html", **template_values))
def post(self): jinja = jinja2.get_jinja2(app=self.app) template_values = manageUsers(self) id = self.request.GET['id'] viaje = ndb.Key(urlsafe=id).get() viaje.origen = self.request.get("origen").strip() viaje.destino = self.request.get("destino").strip() viaje.horaSalida = self.request.get("horaSalida").strip() viaje.duracion = int(self.request.get("duracion").strip()) viaje.plazas = int(self.request.get("plazas").strip()) viaje.modelo = self.request.get("modelo").strip() viaje.color = self.request.get("color").strip() viaje.propietario = template_values["user"].nickname() viaje.put() sleep(1) viajes = Viaje.query() template_values['viajes'] = viajes self.response.write( jinja.render_template("listTravels.html", **template_values));
def post(self): user = users.get_current_user() if user: if not users.is_current_user_admin(): id_libroCientifico = self.request.get("edIdLibroCientifico", "ERROR") id_comentario = self.request.get("edIdComentario", "ERROR") comentario = ndb.Key(urlsafe=id_comentario).get() url = "/verLibroCientifico?id_libroCientifico="+id_libroCientifico mensaje = "El comentario para el libro: "+comentario.libro+" ha sido eliminado con exito" comentario.key.delete() sust = { "mensaje": mensaje, "url": url } jinja = jinja2.get_jinja2(app=self.app) self.response.write(jinja.render_template("mensajeConfirmacion.html", **sust)) else: self.redirect("/") return else: self.redirect("/") return
def post(self): # cargar primera zona current_zone_id = "intro" from classes.zone_manager import zones lang = current_lang() # crear o sobreescribir usuario user = load_user() user.zone = "intro" user.pollen = 20 save_user(user) main_menu_fields = {"es": "Menu principal", "en": "Main menu"} pollen_fields = {"es": "Polen hostil en cavidad nasal", "en": "Hostile pollen in nasal cavity"} # crear pagina current_zone = zone(zones[current_zone_id][lang]["name"], zones[current_zone_id][lang]["text"], zones[current_zone_id][lang]["image"], zones[current_zone_id][lang]["options"]) # cargar imagen template_values = { "zone_title": current_zone.name, "zone_text": current_zone.text, "zone_img": current_zone.image, "zone_buttons": current_zone.options, "main_menu": main_menu_fields[lang], "pollen_percent": user.pollen, "pollen": pollen_fields[lang] } jinja = jinja2.get_jinja2(app=self.app) self.response.write(jinja.render_template("zone.html",**template_values))
def post(self): # Recupera del formulario titulo = self.request.get("edTitulo", "ERROR") autor = self.request.get("edAutor", "ERROR") campo = self.request.get("edCampo", "ERROR") id_libroCientifico = self.request.get("edIdLibroCientifico", "ERROR") # Guarda los datos libroCientifico = ndb.Key(urlsafe=id_libroCientifico).get() libroCientifico.titulo = titulo libroCientifico.autor = autor libroCientifico.campo = campo libroCientifico.put() url = "/verLibroCientifico?id_libroCientifico=" + libroCientifico.key.urlsafe( ) mensaje = "El libro '" + titulo + "' ha sido editado con exito" sust = {"mensaje": mensaje, "url": url} jinja = jinja2.get_jinja2(app=self.app) self.response.write( jinja.render_template("mensajeConfirmacion.html", **sust))
def get(self): id = self.request.GET["id"] user = ndb.Key(urlsafe=id).get() noReadMsg = Notification.query(Notification.user == user.username, Notification.read == 0) for i in noReadMsg: if i.read == 0: noReadMsg = 0 break follow = Follow.query(Follow.usernameToFollow == user.username) values = { "username": user.username, "name": user.name, "surname": user.surname, "creaks": user.creaks, "follow": user.follow, "followers": user.followers, "id": id, "follows": follow, "noReadMsg": noReadMsg } jinja = jinja2.get_jinja2(app=self.app) self.response.write(jinja.render_template("showfollowers.html", **values)) return
def get(self): usr = users.get_current_user() if usr: login_logout_url = users.create_logout_url("/") else: login_logout_url = users.create_login_url("/") people_list = [ Person('Denys', 'Danylko', 18), Person('Serhii', 'Konar', 19), Person('Daniil', 'Novik', 20) ] plantilla_sust = { "login_logout_url": login_logout_url, "usr": usr, "fecha": strftime("%Y-%m-%d", gmtime()), "hora": strftime("%H:%M:%S", gmtime()), "people": people_list } jinja = jinja2.get_jinja2(app=self.app) self.response.write( jinja.render_template("index.html", **plantilla_sust))
def get(self): user = users.get_current_user() access_link = users.create_logout_url("/") if user: api_key = TMDB.tmdb_api_key url = "https://api.themoviedb.org/3/tv/popular?api_key=" + api_key + "&language=en-US" result = urlfetch.fetch(url, method=urlfetch.GET) json_response = json.loads(result.content) tvshows = json_response.get("results") template_values = { "info": AppInfo, "user": user, "access_link": access_link, "tvshows": tvshows, "popular": True } jinja = jinja2.get_jinja2(app=self.app) self.response.write( jinja.render_template("tv/tvshows.html", **template_values)) else: self.redirect("/")
def get(self): try: id = self.request.GET['id'] except KeyError: self.redirect("/") return try: lugar = ndb.Key(urlsafe=id).get() except: self.redirect("/") return user = users.get_current_user() admin = users.is_current_user_admin() if user: usuario = user.nickname() log = users.create_logout_url('/') else: usuario = "none" log = users.create_login_url('/') jinja = jinja2.get_jinja2(app=self.app) lugar.key.delete() lugares = Lugar.query() time.sleep(0.1) values = { "usuario": usuario, "lugares": lugares, "logout": log, "admin": admin } self.response.write(jinja.render_template("lugar_list.html", **values))
def get_jinja2(app=None): return jinja2.get_jinja2(factory=jinja2_factory, app=app)
def post(self): jinja = jinja2.get_jinja2(app=self.app) # Check if the client is logged in if self.session.get('session_role') == 'client': # If it's logged in, get the session variables, show the home page # Get the search field search = self.request.get("search", "") # Comic search = search.encode("utf8") # Set the default language of the app if self.session['session_idiom'] == "spa": lang = spa # Spanish strings elif self.session['session_idiom'] == "eng": lang = eng # English strings else: lang = eng # Default english self.session['page_name'] = "/user_search" # Current page name # Initializing variables comics = list() all_comics = ComicBook.query() # Variables to be sent to the HTML page values = { "lang": lang, # Language strings "session_name": self.session.get('session_name'), # User name "session_role": self.session.get('session_role'), # User role "session_picture": self.get_session_image( self.session.get('session_name')), # User picture "session_genre": self.session.get('session_genre'), # User genre "comics": comics, # Comics "all_comics": all_comics # All comics (for the user search) } # Check if there is a field to search if search != "" and len(search) > 0: # Get the key sent in the search field key = ndb.Key(urlsafe=search) # Get the comics with that key comic = key.get() # Check if the comics exists if comic and comic is not None: comics.append(comic) # Comics list self.get_own_comics( comics) # Get the comics added by the user values["comics"] = comics # Search results # If not exists, shows a message else: values["ok_message"] = lang[ "search_not_results"] # Ok message (No matches found) del key, comic # Delete variables to free memory # If not exists, shows a message else: values["ok_message"] = lang[ "search_not_results"] # Ok message (No matches found) del search, comics, lang # Delete variables to free memory self.response.write( jinja.render_template("/elements/user_search_results.html", **values)) # Go to the comics home page # If it isn't logged in, redirect to the login page else: self.redirect("/login")
def jinja2(self): return jinja2.get_jinja2(factory=jinja2_factory)
def jinja2(self): return jinja2.get_jinja2()
def jinja2(self): """ Returns: jinja2.Jinja2 """ return jinja2.get_jinja2(app=self.app)
def jinja2(self): jinja2.default_config.update( template_path=self.app.config.get('template_path', 'templates')) return jinja2.get_jinja2(app=self.app)
def render_error(response, status, context, template='error.html'): renderer = jinja2.get_jinja2(app=webapp2.get_app()) response.write(renderer.render_template(template, **context)) response.set_status(status)
def post(self): jinja = jinja2.get_jinja2(app=self.app) # Retrieve the email written in the form email = self.request.get("email", "") email = email.encode("utf8") # Default values to be sent to the HTML page values = { "lang": lang, # Strings } # Check if the client sent an email, if not shows an error message (HTML and JS shouldn't allow this) if len(email) == 0: # Values to be sent to the HTML page values["error_message"] = lang[ "must_email"] # Error message (An email is required) del email # Delete variables to free memory self.response.write(jinja.render_template( "index.html", **values)) # Go to the login page # If client sent an email else: # Check if the user exists user = User.query(User.email == email) # It the user exists if user and user.count() > 0: user = list(user.fetch()) user = user[0] # Creating and encrypting a random password password = randomPassword() # Create the email to recuperate the password message = mail.EmailMessage( sender= "*****@*****.**", # Email sender, it has to be a Google account subject=lang["subject"]) # Email subject message.to = email # Email receiver message.body = lang["greeting"] + user.name + lang[ "body"] + password + lang["end"] # Email body # Set the user new password in the db user.password = encryptPassword(password) user.put() time.sleep(1) # Send the email message.send() del user, email, message, password # Delete variables to free memory self.redirect("/login") # Redirect to the login page # If the user doesn't exist, show an error message else: # Values to be sent to the HTML page values["error_message"] = lang[ "email_not_exist"] # Error message (Email doesn't exist) del user, email # Delete variables to free memory self.response.write( jinja.render_template("index.html", **values)) # Go to the login page
def get(self): jinja = jinja2.get_jinja2(app=self.app) # Check if the admin is logged in. If it's logged in, show the home page if self.session.get('session_role') == 'admin': # Initialize variables pages_to_show = self.session.get( 'pages_to_show') # Number of pages that shows the pagination pages = list( ) # Pages for the pagination (it's a list because of django for templates) self.session[ 'current_number_page'] = 1 # Session current number page all_keys = list() # All user keys keys_page_list = list() # User keys currently in the page # Get all db users (Limited to the number given by the session variable [10 by default]) users = User.query().order(User.name) # All users ordered by name all_users = copy.copy(users) # ALL users (for the search field) all_users = all_users.fetch() num_total = len(all_users) # Total number of elements self.session['page_name'] = "/users" # Current page name self.session['num_elems_page'] = 10 # Amount of elements # Get ALL the user keys (they are necessary to do the order and filter) for user in users: all_keys.append(user.key.urlsafe()) del user # If the total number of elements is above 0 do the pagination if num_total > 0: # Get the number of pages for the pagination num_elems_page = self.session.get( 'num_elems_page') # Number of elements (users) per page num_pages = num_total / num_elems_page # Number of pages users = users.fetch( self.session.get('num_elems_page')) # Ordered by name # If there are less elements than session["num_elems_page"] if num_pages == 0: num_pages = 1 # At least one page # Else else: # If the rest of the division is above 0 if (num_total % num_elems_page) > 0: num_pages = (num_total / num_elems_page ) + 1 # It's necessary other page else: num_pages = (num_total / num_elems_page ) # It doesn't need other page self.session['last_page'] = num_pages # Last page # Set the pages for the pagination for i in range(1, num_pages + 1): pages.append(i) # Set number of pages for the pagination (pagination only shows 3 pages) current_number_page = 1 # If the current page is 1 if current_number_page == 1: pages = pages[0:pages_to_show] # Shows pages 1,2,3 # If the current page is the final page elif current_number_page == num_pages: # Shows the last three pages if (num_pages - pages_to_show) >= 0: pages = pages[(num_pages - pages_to_show):] else: pages = pages[0:pages_to_show] # Else else: pages = pages[(current_number_page - 1):( current_number_page + 1)] # Show the current, last and next pages self.session['pages'] = pages # Pages for the pagination # Setting the keys list to allow the use of the "Delete page" button for user in users: keys_page_list.append(user.key.urlsafe()) del user del num_elems_page, num_pages, current_number_page, pages # Delete variables to free memory # If num_total < 0 else: users = all_users # Set the default language of the app if self.session['session_idiom'] == "spa": lang = spa # Spanish strings elif self.session['session_idiom'] == "eng": lang = eng # English strings else: lang = eng # Default english # Variables to be sent to the HTML page values = { "lang": lang, # Language strings "session_name": self.session.get('session_name'), # User name "session_role": self.session.get('session_role'), # User role "session_picture": self.get_session_image( self.session.get('session_name')), # User picture "session_genre": self.session.get('session_genre'), # User genre "users": users, # Users "current_number_page": 1, # Current number page "pages": self.session.get('pages'), # Pages for the pagination "last_page": self.session.get('last_page'), # Last page number "keys_page_list": keys_page_list, # Users keys that are currently in the page "all_keys": all_keys, # All user keys "all_users": all_users # ALL users (for the search field) } del num_total, pages_to_show, keys_page_list, all_keys, lang, users, all_users # Delete variables to free memory self.session_store.save_sessions(self.response) # Save sessions self.response.write( jinja.render_template("/users/default.html", **values)) # Go to the users home page # If it isn't logged in, redirect to the login page else: self.redirect("/login")
def post(self): jinja = jinja2.get_jinja2(app=self.app) # Check if the admin is logged in. If it's logged in, show the home page if self.session.get('session_role') == 'admin': pages_to_show = self.session.get( 'pages_to_show') # Number of pages that shows the pagination pages = list( ) # Pages for the pagination (it's a list because of django for templates) # Retrieve the page number page_number = self.request.get( "page", self.session.get('current_number_page')) page_number = int(page_number) # If the page number sent by HTML is above 0 if page_number > 0: # Initialize variables all_keys = list() # New user keys list users = list() # Users list aux3 = list() # All user keys support list all_users = list() # ALL users (for the search field) # Set the offset for the query (offset allows to ignore an amount of query results given by its value) num_elems_page = self.session.get('num_elems_page') offset = num_elems_page * (page_number - 1) # Get ALL keys from ALL users (I do this because I want to maintain the ordinations and filters done in the list) aux_all_keys = self.request.get("all_keys", "") # All user keys list # Check if the users keys are empty if len(aux_all_keys) > 2: # Transform the HTML string in a list aux_all_keys = self.transform_keys(aux_all_keys) # It's necessary to compare the HTML with the query list in order to obtain the desired list, like I said users = User.query() all_users = copy.copy( users) # ALL users (for the search field) all_users = all_users.fetch() aux = list() for user in users: # Get ALL the keys aux.append(user.key.urlsafe()) del user for key in aux_all_keys: # Compare the "list" given by HTML with aux for making the new all keys list (all_keys) for key2 in aux: if key == str(key2): key2 = ndb.Key(urlsafe=key) all_keys.append(key2) aux3.append(key2.urlsafe()) break del key2 del key del aux # Delete variables to free memory # Get all db users (Limited to the number given by the session variable [10 by default]) # Not ordered because it has to respect if the user used some ordination or filter users = User.query(User.key.IN(all_keys)).fetch( num_elems_page, offset=offset) num_total = len(aux_all_keys) # Total number of elements # Setting all the user keys all_keys = aux3 del aux3 # Delete variables to free memory # If the total number of elements is above 0 do the pagination if num_total > 0: # Get the number of pages for the pagination num_pages = num_total / num_elems_page # Number of pages # If the page number sent by html is less than the last possible page if page_number <= (num_pages + 1): # Update the session current number page self.session['current_number_page'] = page_number current_number_page = page_number # If there are less elements than session["num_elems_page"] if num_pages == 0: num_pages = 1 # At least one page # Else else: # If the rest of the division is above 0 if (num_total % num_elems_page) > 0: num_pages = (num_total / num_elems_page ) + 1 # It's necessary other page else: num_pages = (num_total / num_elems_page ) # It doesn't need other page self.session['last_page'] = num_pages # Last page # Set the pages for the pagination for i in range(1, num_pages + 1): pages.append(i) # If the current page is 1 if current_number_page == 1: pages = pages[0:pages_to_show] # Shows pages 1,2,3 # If the current page is the final page elif current_number_page == num_pages: # Shows the last three pages if (num_pages - pages_to_show) >= 0: pages = pages[(num_pages - pages_to_show):] else: pages = pages[0:pages_to_show] # Else else: pages = pages[(current_number_page - 2):( current_number_page + 1)] # Show the current, last and next pages self.session[ 'pages'] = pages # Pages for the pagination # Set the default language of the app if self.session['session_idiom'] == "spa": lang = spa # Spanish strings elif self.session['session_idiom'] == "eng": lang = eng # English strings else: lang = eng # Default english # Setting the keys list to allow the use of the "Delete page" button keys_page_list = list() for user in users: keys_page_list.append(user.key.urlsafe()) del user # Variables to be sent to the HTML page values = { "lang": lang, # Language strings "session_name": self.session.get('session_name'), # User name "session_role": self.session.get('session_role'), # User role "session_picture": self.get_session_image( self.session.get( 'session_name')), # User picture "session_genre": self.session.get('session_genre'), # User genre "users": users, # Users "current_number_page": self.session.get( 'current_number_page'), # Current number page "pages": self.session.get( 'pages'), # Pages for the pagination "last_page": self.session.get('last_page'), # Last page number "keys_page_list": keys_page_list, # Users keys that are currently in the page "all_keys": all_keys, # All user keys "all_users": all_users # ALL user (for the search field) } del pages_to_show, page_number, num_elems_page, num_total, offset, \ num_pages, current_number_page, pages, keys_page_list, users, aux_all_keys, all_keys,\ all_users # Delete variables to free memory self.session_store.save_sessions( self.response) # Save sessions self.response.write( jinja.render_template( "/users/default.html", **values)) # Go to the users home page # If it isn't less redirect to users home page else: del pages_to_show, page_number, pages, num_elems_page, num_total, offset, users, num_pages, \ aux_all_keys, all_users # Delete variables to free memory self.redirect("/users") # If the total number is not above 0, redirect to the users home page else: del pages_to_show, page_number, pages, offset, users, num_elems_page, aux_all_keys # Delete variables to free memory self.redirect("/users") # If it isn't above redirect to users home page else: del pages_to_show, page_number, pages # Delete variables to free memory self.redirect("/users") # If it isn't logged in, redirect to the login page else: self.redirect("/login")
def post(self): jinja = jinja2.get_jinja2(app=self.app) # Check if the admin is logged in if self.session.get('session_role') == 'admin': # If it's logged in, get the session variables, show the home page # Get the comic attributes author_key = self.request.get("author", "") # Author key author_key = ndb.Key(urlsafe=author_key) role = self.request.get_all("role[]") # Author roles key = self.request.get("key", "") key = ndb.Key(urlsafe=key) comic = key.get() # Get the comic with that key keys_page_list = self.request.get( "keys_page_list", "") # Comic keys (only comics in the current page) aux_all_keys = self.request.get( "all_keys", "") # All the comic keys (for the order field) # Initialize variables aux = list() # Support variable aux3 = list() # Support variable all_comics = list() # List with all comics (for the search field) # Transform the HTML string in a list all_keys = copy.copy(aux_all_keys) aux_all_keys = self.transform_keys(aux_all_keys) comics = ComicBook.query() for comic2 in comics: # Get ALL the keys aux.append(comic2.key.urlsafe()) del comic2 for key3 in aux_all_keys: # Compare the "list" given by HTML with aux for making the new all keys list (all_keys) for key2 in aux: if key3 == str(key2): key2 = ndb.Key(urlsafe=key2) aux3.append(key2) break del key2 del key3 # Get all db comics offset = (self.session.get('current_number_page') - 1) * self.session.get('num_elems_page') comics = ComicBook.query(ComicBook.key.IN(aux3)).fetch( self.session.get('num_elems_page'), offset=offset) # Set the default language of the app if self.session['session_idiom'] == "spa": lang = spa # Spanish strings elif self.session['session_idiom'] == "eng": lang = eng # English strings else: lang = eng # Default english # Variables to be sent to the HTML page values = { "lang": lang, # Language strings "session_name": self.session.get('session_name'), # User name "session_role": self.session.get('session_role'), # User role "session_picture": self.get_session_image( self.session.get('session_name')), # User picture "session_genre": self.session.get('session_genre'), # User genre "comics": comics, # Comics "current_number_page": self.session.get('current_number_page'), # Current number page "pages": self.session.get('pages'), # Pages for the pagination "last_page": self.session.get('last_page'), # Last page number "keys_page_list": keys_page_list, # Comics keys that are currently in the page "all_keys": all_keys, # All comic keys "all_comics": all_comics, # ALL comic (for the search field) "authors": self.get_authors() # Authors for adding them to the comics } # If the key is from an comic if comic and comic is not None and len( role) > 0 and author_key is not None: # Adding the author roles = "" if str(role).find("all") == -1: for i in range(0, len(role)): roles += lang[role[i]] + ", " roles = roles[:len(roles) - 2] roles = roles.capitalize() else: roles = lang["script"] + ", " + lang[ "drawing"] + ", " + lang["labels"] + ", " + lang[ "inked"] + ", " + lang["colors"] + ", " + lang[ "cover"] roles = roles.capitalize() id = ComicBook_Author.query().order( -ComicBook_Author.id_aux).fetch(1) if len(id) > 0: id = id[0].id_aux + 1 else: id = 1 comic_author = ComicBook_Author(author=author_key.get(), role=roles, id_aux=id) comic_author.put() if len(comic.authors) > 0: comic.authors.append(comic_author) else: comic.authors = [comic_author] aux2 = comic.put() time.sleep(1) # If the modification was successful if aux2 is not None: # Variables to be sent to the HTML page values["ok_message"] = lang[ "author_added_successfully"] # Ok message (Author added successfully) # Get all db Comics (Limited to the number given by the session variable [10 by default]) comics = ComicBook.query(ComicBook.key.IN(aux3)).fetch( self.session.get('num_elems_page'), offset=offset) values["comics"] = comics # Else show an error message else: # Variables to be sent to the HTML page values["error_message"] = lang[ "error_add"] # Error message (The addition couldn't be done) del aux2, comic_author, roles, id # Delete variables to free memory # Else show an error message else: # Values to be sent to the HTML page values["error_message"] = lang[ "must_insert_all_author_attributes"] # Error message (You must insert all author attributes) all_comics = ComicBook.query().fetch( ) # ALL comics (for the search field) values["all_comics"] = all_comics del lang, key, comic, keys_page_list, aux_all_keys, aux, aux3, \ all_comics, offset, all_keys, author_key, role, comics # Delete variables to free memory self.session_store.save_sessions(self.response) # Save sessions self.response.write( jinja.render_template("/comics/default.html", **values)) # Go to the comics home page # If it isn't logged in, redirect to the login page else: self.redirect("/login")
def render_response(self, template, **context): renderer = jinja2.get_jinja2(app=self.app) rendered_value = renderer.render_template(template, **context) self.response.write(rendered_value)
def jinja2(self): return jinja2.get_jinja2(app=self.app)
def jinja2(self): return jinja2.get_jinja2(factory=jinja2_factory, app=self.app)
def __init__(self, request, response): # Set self.request, self.response and self.app. self.initialize(request, response) self.jinja = jinja2.get_jinja2(app=self.app)
def jinja2(self): # Returns a Jinja2 renderer cached in the app registry. return jinja2.get_jinja2(app=self.app)
def handle_500(request, response, exception): context = {} templater = jinja2.get_jinja2(app=app) #response.write('The page you were trying to found has moved or does not exist!') response.write(templater.render_template('error500.html', **context)) response.set_status(404)
def get(self): jinja = jinja2.get_jinja2(app=self.app) # Check if the client is logged in. If it's logged in, show the home page if self.session.get('session_role') == 'client': user = User.query(User.name == self.session.get( "session_name")).fetch() # Current user # If users exists, get borrowings if user and len(user) > 0: self.session['page_name'] = "/borrowings" # Current page name user = user[0] # Get db borrowings all = Borrowing.query() # Db borrowed comics borrow_comics = copy.copy(all) borrow_comics = borrow_comics.filter( Borrowing.is_borrowed == True) borrow_comics = borrow_comics.filter( Borrowing.who_borrow == user.key) aux = list() for borrow_comic in borrow_comics: aux2 = borrow_comic.comic.get() aux3 = borrow_comic.who_want.get() aux2.owner_name = aux3.name aux.append(aux2) del borrow_comic, aux2, aux3 borrow_comics = aux # Db asked comics orders = copy.copy(all) orders = orders.filter(Borrowing.is_borrowed == False) orders = orders.filter(Borrowing.who_borrow == user.key) aux = list() for order in orders: aux2 = order.comic.get() aux3 = order.who_want.get() aux2.owner_name = aux3.name aux.append(aux2) del order, aux2, aux3 orders = aux # Db comics that user ask for own = copy.copy(all) own = own.filter(Borrowing.is_borrowed == True) own = own.filter(Borrowing.who_want == user.key) aux = list() for elem in own: aux2 = elem.comic.get() aux3 = elem.who_borrow.get() aux2.owner_name = aux3.name aux.append(aux2) del elem, aux2, aux3 own = aux # Set the default language of the app if self.session['session_idiom'] == "spa": lang = spa # Spanish strings elif self.session['session_idiom'] == "eng": lang = eng # English strings else: lang = eng # Default english all_comics = ComicBook.query().fetch() # Variables to be sent to the HTML page values = { "lang": lang, # Language strings "session_name": self.session.get('session_name'), # User name "session_role": self.session.get('session_role'), # User role "session_picture": self.get_session_image( self.session.get('session_name')), # User picture "session_genre": self.session.get('session_genre'), # User genre "borrow_comics": borrow_comics, # Borrowed comics "orders": orders, # Asked comics "own": own, # Comics that current user ask for "all_comics": all_comics, # ALL comic (for the users search field) } del lang, user, all, borrow_comics, orders, aux, all_comics, own self.session_store.save_sessions( self.response) # Save sessions self.response.write( jinja.render_template( "/borrowings/default.html", **values)) # Go to the borrowings home page # Else redirect to the login page else: del user # Delete variables to free memory self.redirect("/login") # If it isn't logged in, redirect to the login page else: self.redirect("/login")
def get(self): values = {} jinja = jinja2.get_jinja2(app=self.app) self.response.write(jinja.render_template("register.html", **values)) return