| from flask import Flask, request, jsonify |
| import os |
| from datetime import datetime |
| import traceback |
|
|
| app = Flask(__name__) |
| BASE_DIR = "markdown_files" |
| os.makedirs(BASE_DIR, exist_ok=True) |
|
|
| def log_error_console(req, error_msg): |
| print("\n--- Failed Request ---") |
| print(f"Time: {datetime.utcnow().isoformat()} UTC") |
| print(f"Remote Addr: {req.remote_addr}") |
| print(f"Path: {req.path}") |
| print(f"Headers: {dict(req.headers)}") |
| print(f"Args: {dict(req.args)}") |
| print(f"Form: {dict(req.form)}") |
| try: |
| print(f"Raw Data: {req.data.decode('utf-8', errors='ignore')}") |
| except: |
| print("Raw Data: <unreadable>") |
| print(f"Error: {error_msg}") |
| print(f"Traceback:\n{traceback.format_exc()}") |
| print("----------------------\n") |
|
|
| def extract_data(req): |
| try: |
| return req.get_json(force=True) |
| except: |
| pass |
|
|
| if "title" in req.args and "content" in req.args: |
| return { |
| "title": req.args.get("title"), |
| "content": req.args.get("content"), |
| "tag": req.args.get("tag", "untagged") |
| } |
|
|
| if "X-Title" in req.headers and "X-Content" in req.headers: |
| return { |
| "title": req.headers.get("X-Title"), |
| "content": req.headers.get("X-Content"), |
| "tag": req.headers.get("X-Tag", "untagged") |
| } |
|
|
| return None |
|
|
| @app.route("/create-md", methods=["POST"]) |
| def create_markdown(): |
| try: |
| data = extract_data(request) |
| if not data or "title" not in data or "content" not in data: |
| raise ValueError("Missing 'title' or 'content' in body, query, or headers.") |
|
|
| title = data["title"].strip() |
| content = data["content"] |
| tag = data.get("tag", "untagged").strip().replace(" ", "_") |
|
|
| tag_dir = os.path.join(BASE_DIR, tag) |
| os.makedirs(tag_dir, exist_ok=True) |
|
|
| filename = f"{title.replace(' ', '_')}_{int(datetime.utcnow().timestamp())}.md" |
| filepath = os.path.join(tag_dir, filename) |
|
|
| with open(filepath, "w", encoding="utf-8") as f: |
| f.write(f"# {title}\n\n{content}") |
|
|
| return jsonify({ |
| "message": "Markdown file created", |
| "filename": filename, |
| "tag": tag, |
| "path": filepath |
| }), 201 |
|
|
| except Exception as e: |
| log_error_console(request, str(e)) |
| return jsonify({"error": str(e)}), 400 |
|
|
| if __name__ == "__main__": |
| app.run(host="0.0.0.0", port=7860) |
|
|