def query_export(self, request): request = request['unigrid'] entity = request['entities'] # array of requested fields fields = [] # array of all query entities for simple field search entities = [] # parse UniGridRequest. Get array of fields and array of entities for e in entity: self._process_entity_attrs(e, fields, entities) query = Session().query(*[f['ref'] for f in fields if f['selected']]) for e in entities: if 'join' in e: query = query.outerjoin((e['alias'], e['join'])) # filtration where = self._process_where(request.get('where', {}), fields) if where is not None: query = query.filter(where) # sorting for order in self._process_order(request.get('order', []), fields): query = query.order_by(order) class QueryIterable(object): def __init__(self, query): self.query = query def __iter__(self): return QueryIterator(self.query) class QueryIterator(object): offset = 0 chunk_size = 10000 def __init__(self, query): self.query = query def __iter__(self): return self def next(self): chunk = query.offset(self.offset).limit(self.chunk_size).all() self.offset += self.chunk_size if not chunk: raise StopIteration return bytes( '\n'.join([';'.join([str(f) for f in r]) for r in chunk]) + '\n', 'utf-8') __next__ = next # py3 compat res = Response(content_type='text/csv', headerlist=[('Content-disposition', 'attachment;filename=export.csv')]) res.app_iter = QueryIterable(query) return res
def user_manual_pdf(self, request): if not self.pdf: return Response(status='503 Service Unavailable') return Response( self.pdf, content_type='application/pdf', content_disposition='inline; filename={}.pdf'.format( request.translate(_("User manual")) ) )
def index_csv(self, request): is_global_admin = request.current_user and request.identity.has_global_admin_permissions optional_fields = TableRowOptionalFields() optional_fields.submitters = is_global_admin content = propositions_to_csv( self.propositions(request.q, is_global_admin), origin=request.app.settings.common.instance_name, optional_fields=optional_fields) response = Response(content, content_type='text/csv') response.content_disposition = 'attachment; filename="propositions.csv"' return response
def error(self, request): """Error view Return json object with error description if code raise Exception exception """ data = {'code': 500, 'error': str(self)} return Response(dumps(data), content_type='application/json', status=500)
def http_error(self, request): """HTTP error view If morepath or other code raise HTTPException exception, return json response with data about error """ data = {'code': self.code, 'error': str(self)} return Response(dumps(data), content_type='application/json', status=self.code)
def submit_login(self, request): try: self.find_user() except UserNotFound: return Response(status=404) except ValueError: return Response(status=400) if self.verify_password(insecure_empty_password_ok=request.app.settings. app.insecure_development_mode): @request.after def remember(response): identity = morepath.Identity(self.user.id, user=self.user) request.app.remember_identity(response, request, identity) return redirect("/") else: return LoginCell(self, request).show()
def cors_handler(request): # print(request) preflight = request.method == 'OPTIONS' if preflight: response = Response() else: response = handler(request) response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE') response.headers.add('Access-Control-Allow-Headers', 'authorization, content-type') return response
def view_dispatch_dates(self, request, form): """ Show dispatches dates for a given municipality. """ if form.submitted(request): layout = DefaultLayout(self, request) dates = [ r.date for r in form.municipality.pickup_dates.filter( PickupDate.date > date.today()) ] return render_macro(layout.macros['dispatch_dates'], request, { 'dates': dates, 'layout': layout }) return Response()
def submit_login(self, request): try: user_found = self.find_user() except ValueError: return Response(status=400) is_insecure_empty_password_ok = request.app.settings.app.insecure_development_mode if user_found and self.verify_password(is_insecure_empty_password_ok): @request.after def remember(response): identity = morepath.Identity(self.user.id, user=self.user) request.app.remember_identity(response, request, identity) request.flash(_("alert_logged_in"), "success") return redirect(self.back_url or "/") else: request.flash(_("alert_login_failed"), "danger") return LoginCell(self, request).show()
def view_login_post(self, request): # pylint: disable=unused-argument """Valida usuario y contraseña y genera JWT, que se envía en una cabecera Authorization""" email = request.json.get("email", "").lower() password = request.json.get("password") quien = model.Profesor.get(email=email) if (not quien or not password or not email or not bcrypt.verify(password, quien.password)): raise HTTPUnauthorized('Nombre de usuario o contraseña no válidos') identidad = morepath.Identity(email, nombre=quien.nombre, id=quien.id, role=quien.role) @request.after def enviar_jwt_a_cliente(response): # pylint: disable=unused-variable """Esta función se ejecutará una vez la petición ha sido procesada sin errores. Añadirá la cabecera Authority con el JWT""" request.app.remember_identity(response, request, identidad) fake_response = Response() request.app.remember_identity(fake_response, request, identidad) return fake_response.headers['Authorization']