довольно новый для python. Мне подарили код, чтобы попытаться привести его в порядок и приступить к работе. всякий раз, когда я пытаюсь запустить код, заполняющий базу данных (python log_parser.py -d plp_database.sqlite -l \ anonned_logs_DANW), я получаю сообщение об ошибке
Reading
C:\Users\name\Downloads\plp11\plp\anonned_logs_DANW/csquery.stats.20200101
-packages\flask_sqlalchemy\__init__.py", line 519, in __get__
return type.query_class(mapper, session=self.sa.session())
packages\flask_sqlalchemy\__init__.py", line 981, in get_app
raise RuntimeError(
RuntimeError: No application found. Either work inside a view function or
push an application context. See http://flask-
sqlalchemy.pocoo.org/contexts/.
(venv)
create_app / init .py файл находится ниже
from flask_bootstrap import Bootstrap
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
__version__ = (1,0,0, "dev")
db = SQLAlchemy()
def create_app(testing=None):
app = Flask(__name__, instance_relative_config=False)
if testing is None:
app.config.from_object('config.Config')
else:
app.config.from_object('config.TestConfig')
db.init_app(app)
with app.app_context():
from . import routes, models
db.create_all()
migrate = Migrate(app, db)
bootstrap = Bootstrap(app)
return app ```
Я попытался просмотреть файл init .py, где находится приведенный выше код но не вижу ничего явно неправильного.
Я сравнил это с Flask документацией, и это кажется правильным, хотя могла быть явная ошибка.
Я понятия не имею, как это исправить, так что любой помощь будет оценена. если требуется дополнительная информация, дайте мне знать, и я добавлю ее.
редактировать
plp
..application
....static
....templates
....__init__.py
....models.py
....routes.py
..config.py
..ingestor.py
..log_parser.py
..parser_config
..wsgi.py
from datetime import datetime
import os
import re
from application import db
from hashlib import sha256
from distutils import util
from application.models import LogData, CanonicalQuery, CronLog
class Ingestor:
def __init__(self, logs_path):
self.logs_path = os.path.abspath(logs_path)
print(logs_path)
print("ive just printed the logs path")
def list_logs(self):
for file in self.get_logs():
print (file)
def get_logs(self):
files = os.listdir(self.logs_path)
return files
def _get_start_line(self,file_path):**this is where it appears to fall over**
print("Reading %s" % file_path)
cronlog = CronLog.query.filter_by(file_path=file_path).first()
if cronlog:
return cronlog.last_entry
return 0
# return
def canonicalise(self, sql_query):
tmp = re.sub(r"\s+", " ", sql_query)
tmp = re.sub(r"'.*?'", "@QSTR", tmp)
tmp = re.sub(r"\b\d+\b", "@NUM", tmp)
tmp = re.sub(r"@QSTR(\s*,\s*@QSTR)+", "@QSTR_LIST", tmp)
tmp = re.sub(r"@NUM(\s*,\s*@NUM)+", "@NUM_LIST", tmp)
tmp = re.sub(r"[Ii][Nn] \(\s*@QSTR\)", "IN (@QSTR_LIST)", tmp)
tmp = re.sub(r"[Ii][Nn] \(\s*@NUM\)", "IN (@NUM_LIST)", tmp)
# Query db for instance of object
query = CanonicalQuery.query.filter_by(con_sql=tmp).first()
if query:
return query.id
else:
sql = CanonicalQuery(con_sql=tmp)
db.session.add(sql)
db.session.commit()
return sql.id
def add_data(self):
# get a list of all of the files
files = self.get_logs()
# parse all files to csv objects
for file in files:
# we can check if the file has changed before we try and parse it by checking the file checksum(sha256).
file_path="%s/%s" % (self.logs_path,file)
with open(file_path, "r") as csvfile:
line_total = self._get_start_line(file_path)
line_count = 0
try:
reader = csv.DictReader(csvfile, skipinitialspace=True, delimiter=',') # ignore the inital space if found
for num, row in enumerate(reader):
if num > line_total:
db.session.add(
LogData(
time=datetime.strptime(row['Time'],'%Y-%m-%d %H:%M:%S'),
user=row['User'],
host=row['Host'],
duration=row['Duration'],
recs_selected=row['Recs selected'],
recs_returned=row['Recs returned'],
recs_examined=row['Recs examined'],
bytes_read=row['Bytes read'],
index_seeks=row['Index seeks'],
batch_seeks=row['Batch seeks'],
lookup_duration=row['Lookup duration'],
base_raw_duration=row['Base/raw duration'],
sort_duration=row['Sort duration'],
error=util.strtobool(row['Error']),
server_used=row['Server used'],
action=row['Action'],
_case=row['Case'],
sql_query_id=self.canonicalise(row['SQL'])
)
)
line_count = num
db.session.commit()
except KeyError:
print ("%s - is not a vaild log file skipping...." % file_path)
print("Entries iterated %s entries total %s " % (line_count, line_total))
self.update_log(file_path, line_count)
def update_log(self, file_path, last_entry):
with open(file_path,"rb") as file_data:
data = file_data.read()
data_checksum = sha256(data).hexdigest()
# Check if entry exsists
cronlog = CronLog.query.filter_by(file_path=file_path).first()
if cronlog:
cronlog.date_parsed = datetime.now()
cronlog.last_entry = last_entry
cronlog.checksum = data_checksum
else:
# if no log exsits
db.session.add(
CronLog(
date_parsed=datetime.now(),
last_entry=last_entry,
file_path=file_path,
checksum=data_checksum
)
)
db.session.commit()
выделено жирным шрифтом, это то место, где я думаю . файлы log_parser и ingestor - это два основных файла серверного приложения.