ogn-python/app/gateway/process_tools.py

48 wiersze
1.2 KiB
Python
Czysty Zwykły widok Historia

2019-09-25 21:17:30 +00:00
import os
import gzip
import time
from contextlib import contextmanager
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
from flask import current_app
from app import db
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
@contextmanager
def open_file(filename):
"""Opens a regular OR gzipped textfile for reading."""
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
file = open(filename, "rb")
a = file.read(2)
file.close()
if a == b"\x1f\x8b":
file = gzip.open(filename, "rt", encoding="latin-1")
else:
file = open(filename, "rt", encoding="latin-1")
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
try:
yield file
finally:
file.close()
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
class Timer(object):
def __init__(self, name=None):
self.name = name
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
def __enter__(self):
self.tstart = time.time()
2019-03-04 21:14:13 +00:00
2019-09-25 21:17:30 +00:00
def __exit__(self, type, value, traceback):
if self.name:
print("[{}]".format(self.name))
print("Elapsed: {}".format(time.time() - self.tstart))
2019-03-04 21:14:13 +00:00
2020-11-22 07:55:19 +00:00
2020-10-27 19:46:14 +00:00
def export_to_path(path):
2019-09-25 21:17:30 +00:00
connection = db.engine.raw_connection()
cursor = connection.cursor()
2020-10-27 19:46:14 +00:00
aircraft_beacons_file = os.path.join(path, "sender_positions.csv.gz")
2019-09-25 21:17:30 +00:00
with gzip.open(aircraft_beacons_file, "wt", encoding="utf-8") as gzip_file:
2020-10-27 19:46:14 +00:00
cursor.copy_expert("COPY ({}) TO STDOUT WITH (DELIMITER ',', FORMAT CSV, HEADER, ENCODING 'UTF-8');".format("SELECT * FROM sender_positions"), gzip_file)