Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views2 pages

Server

Uploaded by

bien24052008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Server

Uploaded by

bien24052008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

from flask import Flask, request

import json
import os
from flask_cors import CORS
app = Flask(__name__)
from flask_cors import cross_origin
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

@app.after_request
def add_cors_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type,
Authorization'
response.headers['Access-Control-Allow-Credentials'] = 'true'
return response

DATA_FILE = 'data/data.json'
SETTINGS_FILE = 'data/setting.json'

def read_data():
if not os.path.exists(DATA_FILE):
# Nếu file chưa có, tạo cấu trúc mặc định
return {"tasks": []}
with open(DATA_FILE, 'r', encoding='utf-8') as f:
try:
return json.load(f)
except Exception:
return {"tasks": []}

def write_data(data):
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)

@app.route('/save', methods=['POST'])
def save():
task = request.json
data = read_data()
if "tasks" not in data or not isinstance(data["tasks"], list):
data["tasks"] = []
data["tasks"].append(task)
write_data(data)
return 'Đã lưu thành công!'

@app.route('/edit', methods=['PUT', 'OPTIONS'])


def edit():
if request.method == 'OPTIONS':
# CORS preflight
resp = app.make_response('')
resp.status_code = 200
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
resp.headers['Access-Control-Allow-Headers'] = 'Content-Type,
Authorization'
resp.headers['Access-Control-Allow-Credentials'] = 'true'
return resp
updated_task = request.json
data = read_data()
if "tasks" not in data or not isinstance(data["tasks"], list):
resp = app.make_response({'error': 'No tasks found'})
resp.status_code = 404
return resp
for idx, task in enumerate(data["tasks"]):
if str(task.get("id")) == str(updated_task.get("id")):
data["tasks"][idx] = updated_task
write_data(data)
resp = app.make_response({'message': 'Đã cập nhật thành công!'})
resp.status_code = 200
return resp
resp = app.make_response({'error': 'Task not found'})
resp.status_code = 404
return resp

@app.route('/settings', methods=['GET'])
def get_settings():
if not os.path.exists(SETTINGS_FILE):
# Return default settings if file doesn't exist
return {
"dark_mode": False,
"api_key": "",
"ai_model": "gpt-3.5-turbo"
}
with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
try:
return json.load(f)
except Exception:
return {
"dark_mode": False,
"api_key": "",
"ai_model": "gpt-3.5-turbo"
}

@app.route('/settings', methods=['POST'])
def update_settings():
settings = request.json
with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
json.dump(settings, f, ensure_ascii=False, indent=2)
return {'message': 'Settings updated successfully!'}

if __name__ == '__main__':
app.run(port=4567)

You might also like