Example #1
0
def test_exception_without_traceback():
    try:
        raise Exception("msg1")
    except Exception as e:
        # filter_hidden_frames should skip this since it has no traceback
        e.__context__ = Exception("msg2")
        get_current_traceback()
Example #2
0
def nsapi_status():
    logger.info('[%s][status] nsapi_run: %s', request.remote_addr,
                mc.get('nsapi_run'))
    result = []
    result.append('<html><head><title>NS Storingen</title></head><body>')
    result.append('<h2>NS api status</h2>')
    try:
        should_run = mc.get('nsapi_run')
        result.append("nsapi_run: %s" % mc['nsapi_run'])
    except KeyError:
        result.append("nsapi_run not found")
    result.append('<h2>Disruptions</h2>')
    try:
        prev_disruptions = mc.get('prev_disruptions')
        disruptions = ns_api.list_from_json(prev_disruptions['unplanned'])
        for disruption in disruptions:
            message = format_disruption(disruption)
            logger.debug(message)
            result.append(u'<h3>' + message['header'] + '</h3>')
            if message['message']:
                if message['timestamp']:
                    result.append('<p>' + message['timestamp'] + '</p>')
                result.append('<pre>' + message['message'] + '</pre>')
            else:
                result.append('<pre>Nothing to see here</pre>')
    except TypeError:
        result.append('No disruptions found')
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        #abort(500)
    result.append('<h2>Delays</h2>')
    try:
        prev_delays = mc.get('1_trips')
        delays = ns_api.list_from_json(prev_delays)
        for delay in delays:
            message = format_trip(delay)
            if not message['message']:
                message['message'] = 'Geen bijzonderheden'
            result.append('<h3>' + message['header'] + '</h3>')
            result.append('<pre>' + message['message'] + '</pre>')
    except TypeError:
        result.append('No trips found')
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        #abort(500)
    result.append('</body></html>')
    return u'\n'.join(result)
Example #3
0
def nsapi_status():
    logger.info('[%s][status] nsapi_run: %s', request.remote_addr, mc.get('nsapi_run'))
    result = []
    result.append('<html><head><title>NS Storingen</title></head><body>')
    result.append('<h2>NS api status</h2>')
    try:
        should_run = mc.get('nsapi_run')
        result.append("nsapi_run: %s" % mc['nsapi_run'])
    except KeyError:
        result.append("nsapi_run not found")
    result.append('<h2>Disruptions</h2>')
    try:
        prev_disruptions = mc.get('prev_disruptions')
        disruptions = ns_api.list_from_json(prev_disruptions['unplanned'])
        for disruption in disruptions:
            message = format_disruption(disruption)
            logger.debug(message)
            result.append(u'<h3>' + message['header'] + '</h3>')
            if message['message']:
                if message['timestamp']:
                    result.append('<p>' + message['timestamp'] + '</p>')
                result.append('<pre>' + message['message'] + '</pre>')
            else:
                result.append('<pre>Nothing to see here</pre>')
    except TypeError:
        result.append('No disruptions found')
        track = get_current_traceback(skip=1, show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        #abort(500)
    result.append('<h2>Delays</h2>')
    try:
        prev_delays = mc.get('1_trips')
        delays = ns_api.list_from_json(prev_delays)
        for delay in delays:
            message = format_trip(delay)
            if not message['message']:
                message['message'] = 'Geen bijzonderheden'
            result.append('<h3>' + message['header'] + '</h3>')
            result.append('<pre>' + message['message'] + '</pre>')
    except TypeError:
        result.append('No trips found')
        track = get_current_traceback(skip=1, show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        #abort(500)
    result.append('</body></html>')
    return u'\n'.join(result)
Example #4
0
def rest_go_procedure_list_continue():
    try:
        response = procedure.list_procedure(session, request)
        if response:
            items = response['Items']
            # 마지막 값을 가지고 있으면 다음 조회 가능 하도록 하고 없으면 없는 값 셋
            if 'LastEvaluatedKey' in response:
                esk_worship_date = response['LastEvaluatedKey']['worship_date']
                esk_church_id = response['LastEvaluatedKey']['church_id']
            else:
                esk_worship_date = None
                esk_church_id = None
            return jsonify({
                'items': items,
                'esk_worship_date': esk_worship_date,
                'esk_church_id': esk_church_id
            })
        else:
            return jsonify({
                'items': None,
                'esk_worship_date': None,
                'esk_church_id': None
            })
    except Exception as e:
        #app.logger.error(e)
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        app.logger.error(track.log())
    return jsonify({
        'items': None,
        'esk_worship_date': None,
        'esk_church_id': None
    })
Example #5
0
def file_transmuter():
    # Receive a file, process, return elaborated file
    print("ANTES DE NADA")
    try:
        date_format = "%Y%m%d-%H%M%S"

        if len(request.files) > 0:
            for k in request.files:
                buffer = bytes(request.files[k].stream.getbuffer())
                break
        else:
            buffer = bytes(io.BytesIO(request.get_data()).getbuffer())

        import uuid
        filename = "mb_" + str(uuid.uuid4())

        file_type = magic.from_buffer(buffer, mime=True)

        extension = ""
        if file_type == "application/excel":
            extension = ".xlsx"
        elif file_type == "application/octet-stream":
            import xlrd
            # Try opening as Excel
            try:
                data = xlrd.open_workbook(file_contents=buffer)
                extension = ".xlsx"
            except Exception:
                pass
        elif file_type == "text/x-modules":
            extension = ".py"
        elif file_type == "image/png":
            extension = ".png"

        print("ANTES DE PROCESAR")
        # Process the file
        buffer = process_file(buffer)

        # Write the resulting file
        extension2 = ".xlsx"
        with open(app.config['UPLOAD_FOLDER'] + filename + extension2,
                  "wb") as f:
            f.write(buffer)
        # Redirect to the resulting file
        return Response(
            url_for('send_static_files', path=filename + extension2))
        # return redirect(url_for('send_static_files', path=filename+extension))

        # resp = Response(buffer, mimetype=file_type)
        # resp.headers["Content-type"] = file_type
        # resp.headers["Content-Disposition"] = "attachment; filename=" + filename + extension

        # return resp
    except Exception as e:
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        abort(500)
Example #6
0
def handle_error(e):
    track = get_current_traceback(
        skip=1,
        show_hidden_frames=True,
        ignore_system_exceptions=False
    )
    logging.error(track.plaintext)
    return jsonify(error=str(e)), 500
Example #7
0
def pages(name):
    try:
        return render_template(name)
    except Exception:
        track = get_current_traceback(skip=1, show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        abort(500)
Example #8
0
def internal_server_error(e):
	base = os.path.dirname(os.path.abspath(__file__))
	f = open('%s/logs/error.log' % (base), 'a')
	track = get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
	track.log(f)
	f.close()

	return 'An error has occured', 500
Example #9
0
def kerofis_search_query(sql):

    # perform the query
    try:
      pgDB = psycopg2.connect(sConnPostgre)
      pgCursor = pgDB.cursor()

      pgCursor.execute(sql)
      records = pgCursor.fetchall()

      # declare array + counter
      json_array = []
      loop_counter = 0

      # loop
      for record in records:

        # store attributes from order of the database attributes
        niv = record[0]
        deiziad_degemer = record[1]
        insee = record[2]
        kumun = record[3]
        rummad = record[4]
        stumm_orin = record[5]
        stumm_dibab = record[6]

        # building the json
        json_str = "{'insee':'" + insee + "',"
        json_str += "'municipality':'" + kumun + "',"
        json_str += "'validation_date':'" + str(deiziad_degemer) + "',"
        json_str += "'id':'" + str(niv) + "',"
        json_str += "'type':'" + rummad + "',"
        json_str += "'name:br':'" + stumm_orin + "',"
        json_str += "'name:fr':'" + stumm_dibab + "}"
        json_array.append(json_str)
        loop_counter += 1

      # then return a beautiful json
      return jsonify(
        licence = licence,
        attribution_en = attribution_en,
        attribution_fr = attribution_fr,
        attribution_br = attribution_br,
        count = loop_counter,
        places = json_array
      )

      # closing cursor and connection to the database
      pgCursor.close()
      pgDB.close()
      pass

    except Exception, e:
      # out the error to the log
      track= get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
      track.log()
      return jsonify(error = str(e)), 500
Example #10
0
def internal_server_error(e):
    base = os.path.dirname(os.path.abspath(__file__))
    f = open('%s/logs/error.log' % (base), 'a')
    track = get_current_traceback(skip=1,
                                  show_hidden_frames=True,
                                  ignore_system_exceptions=False)
    track.log(f)
    f.close()

    return 'An error has occured', 500
def index():
	msg = Message('Hello', recipients = ['*****@*****.**'])
	msg.body = 'this is the message body'
	try:
		mail.send(msg)
		return "Email sent"
	except:
		track = get_current_traceback()
		track.log()
		return 'Failed'
Example #12
0
def server_error_page(error):
    track = get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
    html = render_template("errors/error_mail.html", stacktrace=str(track.plaintext))
    try:
        send_log_email(current_user.name + ' ' + current_user.last_name + ' ' + current_user.municipal_id + ' ' + str(datetime.datetime.now()), html)
        auth = True
    except:
        send_log_email('server_error', html)
        auth = False
    return render_template("errors/500.html", auth=auth), 500
Example #13
0
def error_500(e):
    traceback = get_current_traceback()
    mail.send_message(subject='Wystąpił błąd przy przetwarzaniu żądania',
                      body='Path: {url}\nMethod: {method}\n--------------------\n{trace}'.format(
                          url=request.url,
                          method=request.method,
                          trace=traceback.plaintext),
                      sender=('Panel statystyk', config.SENDER_EMAIL),
                      recipients=[config.ADMIN_EMAIL])
    return 'Error 500', 500
Example #14
0
 def handler(error):
     traceback = get_current_traceback(skip=1,
                                       show_hidden_frames=True,
                                       ignore_system_exceptions=True)
     return json_response(
         status_=StatusCodeEnum.HTTP_500_INTERNAL_SERVER_ERROR,
         exception={
             "message": "{} {}".format(traceback.exception, error.message),
             "type": traceback.exception_type,
             "description": traceback.plaintext,
         },
     )
def internal_error(error):
    track = get_current_traceback(skip=1,
                                  show_hidden_frames=True,
                                  ignore_system_exceptions=False)

    track.log()

    return jsonify({
        "Success": False,
        "Message": str(error),
        "traceback": str(track.plaintext),
    }), 500
Example #16
0
def municipalities_search_query(sSQL):

    # perform the query
    try:
      pgDB = psycopg2.connect(sConnPostgre)
      pgCursor = pgDB.cursor()

      pgCursor.execute(sSQL)
      records = pgCursor.fetchall()

      # declare array + counter
      json_array = []
      loop_counter = 0

      # loop
      for record in records:
        json_str = "{'insee':'" + record[0] + "',"
        json_str += "'name:br':'" + record[1] + "',"
        json_str += "'name:fr':'" + record[2] + "',"
        json_str += "'nb': " + str(record[3]) + "}"
        json_array.append(json_str)
        loop_counter += 1

      # then return a beautiful json
      return jsonify(
        licence = licence,
        attribution_en = attribution_en,
        attribution_fr = attribution_fr,
        attribution_br = attribution_br,
        count = loop_counter,
        municipalities = json_array
      )

      # closing cursor and connection to the database
      pgCursor.close()
      pgDB.close()
      pass

    except Exception, e:
      # out the error to the log
      track= get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
      track.log()
      # error
      return jsonify(error = str(e)), 500
def send_data(req):
    if req == 'learn' and request.method == 'POST':
        try:
            # получение данных
            inp_data = request.stream.read().decode("utf-8")
            csv_r = csv.reader([inp_data], delimiter="\t")
            malt_data = []
            # на всякий случай цикл, вдруг во входном файле >одной строки.
            for row in csv_r:
                malt_data.append([float(x)+1 for x in row])

            # обрабатываем входные значения моделями sklearn
            val = parse_input(malt_data, ka, encoder, model_ka_RF)
            return '%s' % val

        except (Exception) as error:
            track = get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
            track.log()
            abort(500)
    else:
        return ""
Example #18
0
def go_procedure_list():
    try:
        response = procedure.list_procedure(session, request)
        items = response['Items']
        # 마지막 값을 가지고 있으면 다음 조회 가능 하도록 하고 없으면 없는 값 셋
        if 'LastEvaluatedKey' in response:
            esk_worship_date = response['LastEvaluatedKey']['worship_date']
            esk_church_id = response['LastEvaluatedKey']['church_id']
        else:
            esk_worship_date = None
            esk_church_id = None

    except Exception as e:
        #app.logger.error(e)
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        app.logger.error(track.log())
    return render_template('procedure/procedure_list.html',
                           items=items,
                           esk_worship_date=esk_worship_date,
                           esk_church_id=esk_church_id).encode('utf-8')
Example #19
0
File: app.py Project: poortij/Test
def userSession():
    try:
        if 'userName' not in session:
            session.permanent = False
            userName = config.TEST_USER_NAME
            bemsId = config.TEST_BEMSID
            emailId = "*****@*****.**"
            if config.WITH_WSSO:
                # get user info from WSSO
                userName = request.headers.get("boeingdisplayname")
                bemsId = request.headers.get("boeingbemsid")
                emailId = request.headers.get("mail")
            session['userName'] = str(userName)
            session['bemsId'] = int(bemsId)
            session['emailId'] = emailId

    except:
        track = get_current_traceback(skip=1,
                                      show_hidden_frames=True,
                                      ignore_system_exceptions=False)
        track.log()
        abort(500)
Example #20
0
def infos():
    #return "API kerofis : infos"

    try:
      # get a connection, if a connect cannot be made an exception will be raised here
      pgDB = psycopg2.connect(sConnPostgre)

      # pgDB.cursor will return a cursor object, you can use this cursor to perform queries
      pgCursor = pgDB.cursor()

      # the query
      pgCursor.execute("""SELECT * FROM v_infos_deiziad_restr LIMIT 1""")
      # get only first record
      record = pgCursor.fetchone()
      date_last_import = str(record[0])

      # pass the data to the JSON template
      return jsonify(
        name = "kerOfis database",
        licence = licence,
        attribution_en = attribution_en,
        attribution_fr = attribution_fr,
        attribution_br = attribution_br,
        last_file_import = date_last_import,
        file_imports = {}
      )

      # closing cursor and connection to the database
      pgCursor.close()
      pgDB.close()

    except Exception,e:
      # out the error to the log
      track= get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
      track.log()
      # return customized error message in JSON
      return jsonify(error = str(e)), 500
Example #21
0
def print_err(ex):
    print(ex)
    track = get_current_traceback(skip=1,
                                  show_hidden_frames=True,
                                  ignore_system_exceptions=False)
    track.log()
Example #22
0
    def debug(self, ctx: HTTPRequestContext,
              exc: Exception) -> typing.Tuple[bool, Response]:
        """
        Produces debug output for the application in a new template.
        """
        if not self.app.debug:
            return

        # Check the request's params.
        params = ctx.request.args

        debugger = params.get("__debugger__")
        if debugger == "yes":
            command = params.get("cmd")
            # Switch based on the command.
            if command is None:
                return Response(code=404, body="404")
            elif command == "resource":
                # Send a resource down the line.
                filename = params.get("f")
                # Get the __file__ of the werkzeug debugger.
                wz_f = os.path.dirname(debug.__file__)
                filename = os.path.join(wz_f, 'shared',
                                        os.path.basename(filename))
                # Guess the content type from the filename.
                mimetype = mimetypes.guess_type(
                    filename)[0] or 'application/octet-stream'
                if os.path.exists(filename):
                    with open(filename, 'rb') as f:
                        return False, Response(
                            body=f.read(),
                            code=200,
                            headers={"Content-Type": mimetype})
                else:
                    return False, Response(body="404", code=404)
            else:
                # It's a console command.
                frame = self.frames.get(int(ctx.request.args.get('frm')))
                if frame is None:
                    return False, Response(body="404", code=404)
                # Run the console command inside the frame.
                result = frame.console.eval(command)
                return False, Response(body=result,
                                       code=200,
                                       headers={"Content-Type": "text/html"})
        else:
            # Get the traceback, now.
            traceback = get_current_traceback(skip=0,
                                              show_hidden_frames=True,
                                              ignore_system_exceptions=False)
            for frame in traceback.frames:
                self.frames[frame.id] = frame
            self.tracebacks[traceback.id] = traceback
            # Render the base page.
            body = traceback.render_full(
                evalex=True,
                evalex_trusted=True,
            )
            r = Response(code=500,
                         body=body.encode(),
                         headers={"X-XSS-Protection": "0"})
            return True, r
Example #23
0
def teardown_request(exception):
    if exception:
        _traceback = get_current_traceback()
        logger.error(_traceback.plaintext)
Example #24
0
def exception_handler(error):
    return get_current_traceback(skip=1, show_hidden_frames=True,
                                 ignore_system_exceptions=False).render_full(evalex=True)
Example #25
0
def municipalities_index():
    # return a json response with the list of all the municipalities concerned in the database
    # datas provided by the v_stats_kumun table
    # insee | kumun | nb

    # return "API kerofis : stats : par commune : toutes les communes"

    try:
      # get a connection, if a connect cannot be made an exception will be raised here
      pgDB = psycopg2.connect(sConnPostgre)

      # pgDB.cursor will return a cursor object, you can use this cursor to perform queries
      pgCursor = pgDB.cursor()

      #-------------------------------------------------------------------------------
      # first : get count of municipality in the database

      pgCursor.execute("""SELECT COUNT(*) AS count FROM v_stats_kumun""")
      oneRecord = pgCursor.fetchone()
      NbOfMunicipalities = str(oneRecord[0])


      #-------------------------------------------------------------------------------
      # second : loop on all the municipalities

      # the query
      pgCursor.execute("""SELECT * FROM v_stats_kumun""")
      # get all the records
      records = pgCursor.fetchall()

      # return raw json records in  text/html + no attributes name
      #return str(json.dumps(records))

      # return correct application/json answer BUT no attributes name
      #return jsonify({'municipalities':records})

      # declare array
      json_array = []

      # loop on each record to built handmade json
      for record in records:
        json_str = "{'insee':'" + record[0] + "',"
        json_str += "'name:br':'" + record[1] + "',"
        json_str += "'name:fr':'" + record[2] + "',"
        json_str += "'nb': " + str(record[3]) + "}"
        json_array.append(json_str)

      # then return a beautiful json
      #return jsonify({'municipalities':json_array})
      return jsonify(
        licence = licence,
        attribution_en = attribution_en,
        attribution_fr = attribution_fr,
        attribution_br = attribution_br,
        count = NbOfMunicipalities,
        municipalities = json_array
      )

      #return "json_response"

      # closing cursor and connection to the database
      pgCursor.close()
      pgDB.close()

    except Exception,e:
      # out the error to the log
      track= get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
      track.log()
      # error
      return jsonify(error = str(e)), 500