Files
double-entry-accounting/server.py
2025-05-08 16:12:33 +12:00

85 lines
2.3 KiB
Python

import cherrypy
from sqlalchemy import create_engine
from accounting.models import Base
from accounting.api import AccountingAPI
import os
from config import DATABASE_URI
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
cherrypy.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
cherrypy.response.headers["Access-Control-Allow-Headers"] = "Content-Type"
class Root:
@cherrypy.expose
def index(self):
return open(os.path.join(os.path.dirname(__file__), 'accounting/templates/index.html')).read()
@cherrypy.expose
def favicon_ico(self):
return cherrypy.lib.static.serve_file(
os.path.join(os.path.dirname(__file__), 'static/favicon.ico'),
content_type='image/x-icon'
)
def setup_database():
engine = create_engine(DATABASE_URI)
Base.metadata.create_all(engine)
return engine
def main():
# Database setup
db_engine = setup_database()
# Create static directory if it doesn't exist
static_path = os.path.join(os.path.dirname(__file__), 'static')
if not os.path.exists(static_path):
os.makedirs(static_path)
# CherryPy configuration
conf = {
'/': {
'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),
'tools.CORS.on': True
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static',
},
'/api': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'application/json')],
}
}
# Register CORS tool
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
# Create application
root = Root()
root.api = AccountingAPI(db_engine)
cherrypy.tree.mount(root, '/', conf)
# Start server
cherrypy.config.update({
'server.socket_host': '0.0.0.0',
'server.socket_port': 8080,
'log.screen': True,
'engine.autoreload.on': True
})
print("Starting accounting system...")
cherrypy.engine.start()
cherrypy.engine.block()
if __name__ == '__main__':
main()