Skip to content

Commit

Permalink
Merge pull request #20 from zorroforever/flask
Browse files Browse the repository at this point in the history
add:flask html edit config.json
  • Loading branch information
zorroforever authored Jun 14, 2024
2 parents e8070d3 + aad2ad7 commit 5670c18
Show file tree
Hide file tree
Showing 23 changed files with 377 additions and 131 deletions.
2 changes: 2 additions & 0 deletions babel.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[python: src/**.py]
[jinja2: templates/**.html]
36 changes: 0 additions & 36 deletions config.json

This file was deleted.

71 changes: 0 additions & 71 deletions cost/fixed_consume.py

This file was deleted.

115 changes: 115 additions & 0 deletions flask_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
from flask import Flask, render_template, request, redirect, url_for, send_from_directory
from flask_babel import Babel, _
import json
import os

from src.life import main
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations'
# babel = Babel(app)

# setup language support
LANGUAGES = {
'en': 'English',
'zh': 'Chinese',
'ja': 'Japanese'
}


def get_locale():
# try to guess the language from the user accept header the browser transmits.
return request.accept_languages.best_match(LANGUAGES.keys())


babel = Babel(app, locale_selector=get_locale)


@app.context_processor
def inject_locale():
return dict(get_locale=get_locale)


# load config.json
def load_config():
with open('src/config/config.json', 'r', encoding='utf-8') as file:
config_data = json.load(file)
return config_data


# save config.json
def save_config(config_data):
with open('src/config/config.json', 'w', encoding='utf-8') as file:
json.dump(config_data, file, indent=4, ensure_ascii=False)


# index
@app.route('/')
def index():
config_data = load_config()
return render_template('index.html', config=config_data)


# config edit
@app.route('/edit', methods=['GET', 'POST'])
def edit():
if request.method == 'POST':
# get form data and save it to config.json
config_data = request.form.to_dict(flat=False)
print(config_data)
nested_data = parse_nested_form(config_data)
save_config(nested_data)
return redirect(url_for('index'))
else:
config_data = load_config()
return render_template('edit.html', config=config_data)


def unflatten_dict(d):
result_dict = {}
for k, v in d.items():
keys = k.split('.')
d = result_dict
for key in keys[:-1]:
d = d.setdefault(key, {})
d[keys[-1]] = v[0] # assume only one value per key
return result_dict

def parse_nested_form(form):
config = {}
for key, value in form.items():
parts = key.split('.')
current = config
for part in parts[:-1]:
if part not in current:
current[part] = {}
current = current[part]
current[parts[-1]] = value[0]
return config

# run life
@app.route('/run', methods=['GET','POST'])
def run_life():
config_path = 'src/config/config.json'
# script_dir = os.path.dirname(os.path.abspath(__file__))
main(config_path)
# output_path = os.path.join(script_dir ,load_config()['output_file_path'])

# output_path = 'results/output.txt'
# result = subprocess.run(['python', 'life.py', config_path], capture_output=True, text=True)
# print(result)
# with open(output_path, 'w', encoding='utf-8') as file:
# file.write(result.stdout)
return redirect(url_for('download_file'))

# download output file
@app.route('/download')
def download_file():
# directory = 'results'
filename = load_config()['output_file_path']
directory = os.path.dirname(os.path.abspath(__file__))
return send_from_directory(directory, filename)


if __name__ == '__main__':
app.run(debug=True)
File renamed without changes.
File renamed without changes.
8 changes: 4 additions & 4 deletions bank/bank.py → src/bank/bank.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from bank.money import Money
from util.translations import get_translation
from src.bank.money import Money
from src.util.translations import get_translation


class Bank:
Expand All @@ -10,8 +10,8 @@ class Bank:
currency = 'CNY'

def __init__(self, config):
self.bank_rate = config['bank_rate']
self.balance = Money(config['initial_balance'], config['currency'], config["mark"])
self.bank_rate = float(config['bank_rate'])
self.balance = Money(float(config['initial_balance']), config['currency'], config["mark"])
self.language = config['language']
self.currency = config['currency']

Expand Down
2 changes: 1 addition & 1 deletion bank/money.py → src/bank/money.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from util.translations import get_translation
from src.util.translations import get_translation


class Money:
Expand Down
35 changes: 35 additions & 0 deletions src/config/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"language": "zh",
"currency": "CNY",
"mark": "¥",
"bank_rate": "1.2",
"initial_balance": "50000000",
"base_year": "2024",
"years": "30",
"target_year": "2084",
"inflate_rate": "4.48",
"birth_year": "1983",
"retirement_age": "65",
"output_file_path": "out.txt",
"cost": {
"monthly": {
"fixed": {
"house_fee": "1000",
"eng_water_fee": "50",
"eng_electricity_fee": "200",
"eng_gas_fee": "50",
"eng_network_fee": "200",
"phone_fee": "200",
"insurance_fee": "4000",
"aaa": "222"
},
"variable": {
"traffic_fee": "800",
"food_fee": "3000",
"shopping_fee": "3000",
"travelling_fee": "5000",
"vip_fee": "400"
}
}
}
}
File renamed without changes.
83 changes: 83 additions & 0 deletions src/cost/fixed_consume.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from ..bank.money import Money
from src.util.translations import get_translation


class FixedConsume:
c_age = 0
c_rate = 0
c_insurance_fee_monthly = 0
c_insurance_fee_yearly = 0
c_total_consume_monthly = 0
c_total_consume_yearly = 0

inflation_rate = 0
birth_year = 0
retirement_age = 0
base_year = 0
target_year = 0
config = {}
currency = ""

def __init__(self, config, base_year, target_year):
self.config = config
self.language = config['language']
self.base_year = int(base_year)
self.inflation_rate = float(config['inflate_rate'])
self.birth_year = int(config['birth_year'])
self.retirement_age = int(config['retirement_age'])
self.target_year = int(target_year)
self.c_age = self.target_year - self.birth_year
self.currency = config['currency']
self.mark = config['mark']

def inflation_adjustment_factor(self):
years = self.target_year - self.base_year
inflation_rate_decimal = self.inflation_rate / 100
adjustment_factor = (1 + inflation_rate_decimal) ** years
return adjustment_factor


def calculate_fixed_consume_yearly(self):
self.c_rate = self.inflation_adjustment_factor()
fixed_cost = 0
variable_costs = 0
annual_costs = 0
try:
fixed_costs_config = self.config["cost"]["monthly"]["fixed"]
if fixed_costs_config is not None:
for key, value in fixed_costs_config.items():
if key == "insurance_fee" and self.c_age > self.retirement_age:
continue
else:
fixed_cost += float(value)
if key == "insurance_fee":
self.c_insurance_fee_monthly = float(value)
except KeyError:
fixed_cost = 0
try:
variable_costs_config = self.config["cost"]["monthly"]["variable"]
if variable_costs is not None:
for key, value in variable_costs_config.items():
variable_costs += float(value)
except KeyError:
variable_costs = 0
try:
annual_costs_config = self.config["cost"]["monthly"]["annual"]
if annual_costs is not None:
for key, value in annual_costs_config.items():
annual_costs += float(value)
except KeyError:
annual_costs = 0
self.c_insurance_fee_yearly = Money(self.c_insurance_fee_monthly * 12 * self.c_rate, self.currency, self.mark)
self.c_total_consume_yearly = Money((fixed_cost + variable_costs + annual_costs) * 12 * self.c_rate, self.currency, self.mark)
self.c_total_consume_monthly = Money((fixed_cost + variable_costs + annual_costs) * self.c_rate, self.currency, self.mark)
return self.c_total_consume_yearly

def get_no_str(self):
message_template = get_translation('yearly_consumption', self.language)
return message_template.format(
age=self.c_age,
monthly_cost=self.c_total_consume_monthly,
total_cost=self.c_total_consume_yearly,
insurance_cost=self.c_insurance_fee_yearly
)
Loading

0 comments on commit 5670c18

Please sign in to comment.