Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def filepath_in_document_folder(documents_folder, account, filename):
"""File path for a document in the folder for an account.
Args:
documents_folder: The documents folder.
account: The account to choose the subfolder for.
filename: The filename of the document.
Returns:
The path that the document should be saved at.
"""
if documents_folder not in g.ledger.options["documents"]:
raise FavaAPIException(
"Not a documents folder: {}.".format(documents_folder)
)
if account not in g.ledger.attributes.accounts:
raise FavaAPIException("Not a valid account: '{}'".format(account))
for sep in os.sep, os.altsep:
if sep:
filename = filename.replace(sep, " ")
return path.normpath(
path.join(
path.dirname(g.ledger.beancount_file_path),
documents_folder,
*account.split(":"),
filename
def add_document():
"""Upload a document."""
if not g.ledger.options["documents"]:
raise FavaAPIException("You need to set a documents folder.")
upload = request.files["file"]
if not upload:
raise FavaAPIException("No file uploaded.")
filepath = filepath_in_document_folder(
request.form["folder"], request.form["account"], upload.filename
)
directory, filename = path.split(filepath)
if path.exists(filepath):
raise FavaAPIException("{} already exists.".format(filepath))
if not path.exists(directory):
os.makedirs(directory, exist_ok=True)
def query(self, types, rows):
"""Chart for a query.
Args:
types: The list of result row types.
rows: The result rows.
"""
if not self.can_plot_query(types):
raise FavaAPIException("Can not plot the given chart.")
if types[0][1] is datetime.date:
return [
{"date": date, "balance": inv_to_dict(units(inv))}
for date, inv in rows
]
return [
{"group": group, "balance": inv_to_dict(units(inv))}
for group, inv in rows
]
def get_source(self, path):
"""Get source files.
Args:
path: The path of the file.
Returns:
A string with the file contents and the `sha256sum` of the file.
Raises:
FavaAPIException: If the file at `path` is not one of the
source files.
"""
if path not in self.list_sources():
raise FavaAPIException("Trying to read a non-source file")
with open(path, mode="rb") as file:
contents = file.read()
sha256sum = sha256(contents).hexdigest()
source = codecs.decode(contents)
return source, sha256sum
)
if json_entry["type"] == "Balance":
date = util.date.parse_date(json_entry["date"])[0]
raw_amount = json_entry["amount"]
amount = Amount(D(str(raw_amount["number"])), raw_amount["currency"])
return data.Balance(
json_entry["meta"], date, json_entry["account"], amount, None, None
)
if json_entry["type"] == "Note":
date = util.date.parse_date(json_entry["date"])[0]
comment = json_entry["comment"].replace('"', "")
return data.Note(
json_entry["meta"], date, json_entry["account"], comment
)
raise FavaAPIException("Unsupported entry type.")
def move():
"""Move a file."""
if not g.ledger.options["documents"]:
raise FavaAPIException("You need to set a documents folder.")
account = request.args.get("account")
new_name = request.args.get("newName")
filename = request.args.get("filename")
new_path = filepath_in_document_folder(
g.ledger.options["documents"][0], account, new_name
)
if not path.isfile(filename):
raise FavaAPIException("Not a file: '{}'".format(filename))
if path.exists(new_path):
raise FavaAPIException("Target file exists: '{}'".format(new_path))
if not path.exists(path.dirname(new_path)):
self.ledger.all_entries,
self.ledger.options,
query_string,
numberify=True,
)
except (
query_compile.CompilationError,
query_parser.ParseError,
) as exception:
raise FavaAPIException(str(exception))
if result_format == "csv":
data = to_csv(types, rows)
else:
if not HAVE_EXCEL:
raise FavaAPIException("Result format not supported.")
data = to_excel(types, rows, result_format, query_string)
return name, data
def query_result():
"""Render a query result to HTML."""
query = request.args.get("query_string", "")
table = get_template_attribute("_query_table.html", "querytable")
contents, types, rows = g.ledger.query_shell.execute_query(query)
if contents:
if "ERROR" in contents:
raise FavaAPIException(contents)
table = table(contents, types, rows)
if types and g.ledger.charts.can_plot_query(types):
return {
"table": table,
"chart": g.ledger.charts.query(types, rows),
}
return {"table": table}
@app.errorhandler(FavaAPIException)
def fava_api_exception(error):
"""Handle API errors."""
if g.partial:
return error.message, 400
return render_template("_error.html", error=error), 400