Я подумывал о добавлении метаданных в файлы, которые помогут мне создать свой блог. Когда я закончил урок по базе данных и устал запускать его для проверки вручную, он не сработал.
Код:
import os
import frontmatter
import time
import mistune
import json
import sqlite3
# ADS = Alternative Data Stream AKA Metadata for NTFS File System
class Metadata():
def __init__(self, filepath : str, ads_name : str) -> None:
self.filepath = filepath
self.ads_name = ads_name
def pull_metadata(self) -> bool | Exception:
"""
Pulls up the given metdata from the given filepath; returns error if unsucessful
"""
ads_path = os.path.join(self.filepath, f":{self.ads_name}")
try:
with open(ads_path, 'r') as ads_file:
metadata_str = ads_file.read()
metadata = json.loads(metadata_str)
return metadata['accessed']
except FileNotFoundError:
raise FileNotFoundError
def write_metadata(self, metadata: dict) -> bool | Exception:
"""
Writes the given metadata to a ads_path ---
a path that constitues of the filepath to the object,
and the name of the variable in which metadata is stored in a string format.
"metadata" is the dictionary "contaning" the key, value pairs of the metadata that has to be written
"""
metadata_string = json.dumps(metadata)
ads_path = os.path.join(self.filepath, f":{self.ads_name}")
try:
with open(ads_path, 'w') as ads_file:
ads_file.write(metadata_string)
return metadata["accessed"]
except:
raise
def convert_mdh(text):
""" Converts a markdown into HTML """
markdown = mistune.create_markdown()
html = markdown(text)
return html
class Database(Metadata):
def __init__(self, filepath = None, ads_name = None) -> None:
super().__init__(filepath, ads_name)
self.con = None
self.cur = None
self.filepath = "C:/Users/ghosa/Desktop/Master Folder/Programing/portfolio-web/blog/"
self.ads_name = "metadata"
def create_db(self):
# Create SQLite Database
self.con = sqlite3.connect("database.db")
self.cur = self.con.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS records (title TEXT NOT NULL, data TEXT NOT NULL, last_modified_date TEXT NOT NULL, accessed BOOLEAN NOT NULL);")
# Intiate Search for written blogs
absolute_blog_folder_path = self.filepath
os.chdir(absolute_blog_folder_path)
directories = os.listdir()
# Create database useing files, their contents, metadata
for filename in directories:
filepath = f"{self.filepath}/{filename}"
markdown_file_object = frontmatter.load(filepath)
text = markdown_file_object.content
timestamp = os.path.getmtime(filename)
data = convert_mdh(text)
title = filename
last_modified_date = time.strftime('%B %d %Y', time.localtime(timestamp))
try:
accessed = self.pull_metadata()
except FileNotFoundError:
metadata = {"accessed": False}
accessed = self.write_metadata(metadata)
# Fill Database
self.cur.execute("INSERT INTO records (title, data, last_modified_date, accessed) VALUES (?,?,?,?);", (data, title, last_modified_date, accessed))
self.con.commit()
database = Database()
database.create_db()
функция). Я предполагаю, что ошибка связана с :, но я не могу ее удалить, поскольку это способ доступа к данным ADS. Конечно, это действительно странная ситуация. Вроде бы должно было сработать, но не получилось. Некоторая помощь будет оценена
Я подумывал о добавлении метаданных в файлы, которые помогут мне создать свой блог. Когда я закончил урок по базе данных и устал запускать его для проверки вручную, он не сработал. Код: [code]import os import frontmatter import time import mistune import json import sqlite3
# ADS = Alternative Data Stream AKA Metadata for NTFS File System
def pull_metadata(self) -> bool | Exception: """ Pulls up the given metdata from the given filepath; returns error if unsucessful """ ads_path = os.path.join(self.filepath, f":{self.ads_name}") try: with open(ads_path, 'r') as ads_file: metadata_str = ads_file.read() metadata = json.loads(metadata_str) return metadata['accessed']
except FileNotFoundError: raise FileNotFoundError
def write_metadata(self, metadata: dict) -> bool | Exception: """ Writes the given metadata to a ads_path --- a path that constitues of the filepath to the object, and the name of the variable in which metadata is stored in a string format. "metadata" is the dictionary "contaning" the key, value pairs of the metadata that has to be written """ metadata_string = json.dumps(metadata) ads_path = os.path.join(self.filepath, f":{self.ads_name}")
try: with open(ads_path, 'w') as ads_file: ads_file.write(metadata_string)
return metadata["accessed"] except: raise
def convert_mdh(text): """ Converts a markdown into HTML """ markdown = mistune.create_markdown() html = markdown(text) return html
def create_db(self): # Create SQLite Database self.con = sqlite3.connect("database.db") self.cur = self.con.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS records (title TEXT NOT NULL, data TEXT NOT NULL, last_modified_date TEXT NOT NULL, accessed BOOLEAN NOT NULL);")
# Intiate Search for written blogs absolute_blog_folder_path = self.filepath os.chdir(absolute_blog_folder_path) directories = os.listdir()
# Create database useing files, their contents, metadata for filename in directories: filepath = f"{self.filepath}/{filename}" markdown_file_object = frontmatter.load(filepath) text = markdown_file_object.content timestamp = os.path.getmtime(filename)
data = convert_mdh(text) title = filename last_modified_date = time.strftime('%B %d %Y', time.localtime(timestamp))
# Fill Database self.cur.execute("INSERT INTO records (title, data, last_modified_date, accessed) VALUES (?,?,?,?);", (data, title, last_modified_date, accessed)) self.con.commit()
database = Database() database.create_db() [/code] Когда я запустил его, он выдал ошибку: [code]Exception has occurred: OSError [Errno 22] Invalid argument: 'C:/Users/ghosa/Desktop/Master Folder/Programing/portfolio-web/blog/:metadata' File "C:\Users\ghosa\Desktop\Master Folder\Programing\portfolio-web\blog_handeler.py", line 22, in pull_metadata with open(ads_path, 'r') as ads_file: ^^^^^^^^^^^^^^^^^^^ File "C:\Users\ghosa\Desktop\Master Folder\Programing\portfolio-web\blog_handeler.py", line 87, in create_db accessed = self.pull_metadata() ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ghosa\Desktop\Master Folder\Programing\portfolio-web\blog_handeler.py", line 97, in database.create_db() OSError: [Errno 22] Invalid argument: 'C:/Users/ghosa/Desktop/Master Folder/Programing/portfolio-web/blog/:metadata' [/code] Он должен был выполниться и проверить, прикреплены ли к материалу метаданные ([code]pull_metadata()[/code] функция). Я предполагаю, что ошибка связана с :, но я не могу ее удалить, поскольку это способ доступа к данным ADS. Конечно, это действительно странная ситуация. Вроде бы должно было сработать, но не получилось. Некоторая помощь будет оценена