duqing2026's picture
Fix: PermissionError on HF Spaces by creating user/dirs in Dockerfile
df118ab
from flask import Flask, render_template, send_from_directory, jsonify
import os
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Ensure directories exist
try:
os.makedirs('static', exist_ok=True)
os.makedirs('templates', exist_ok=True)
except OSError as e:
logger.warning(f"Could not create directories: {e}. Assuming they exist or are not needed for write access.")
class CustomFlask(Flask):
jinja_options = Flask.jinja_options.copy()
jinja_options.update(dict(
block_start_string='<%',
block_end_string='%>',
variable_start_string='[[',
variable_end_string=']]',
comment_start_string='<#',
comment_end_string='#>',
))
app = CustomFlask(__name__, static_folder='static', template_folder='templates')
@app.route('/')
def index():
try:
# Since we changed delimiters, Flask won't try to parse {{ }} as variables
# This fixes the conflict with Vue.js
return render_template('index.html')
except Exception as e:
logger.error(f"Error rendering index: {e}")
# Fallback to verify if it's a template error
return f"<h1>Internal Server Error</h1><p>{str(e)}</p>", 500
@app.route('/static/<path:path>')
def serve_static(path):
return send_from_directory('static', path)
@app.errorhandler(404)
def page_not_found(e):
return render_template('index.html'), 200
@app.errorhandler(500)
def internal_server_error(e):
return jsonify(error=str(e)), 500
@app.route('/health')
def health_check():
return jsonify(status='ok'), 200
if __name__ == '__main__':
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)