-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_setup.py
More file actions
382 lines (311 loc) · 11.1 KB
/
flask_setup.py
File metadata and controls
382 lines (311 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import subprocess
import os
import sys
import json
import tkinter as tk
from tkinter import filedialog
def run_command(command, cwd=None):
try:
process = subprocess.Popen(
command,
cwd=cwd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True # This makes output strings instead of bytes
)
stdout, stderr = process.communicate()
if process.returncode != 0:
print(f"Command failed: {stderr}") # Keep this critical error logging
return False
return True
except Exception as e:
print(f"Error executing command: {str(e)}") # Keep this critical error logging
return False
def create_tailwind_config(path):
config_content = """/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
animation: {
'spin-slow': 'spin 20s linear infinite',
},
},
},
plugins: [],
}"""
with open(os.path.join(path, 'tailwind.config.js'), 'w') as f:
f.write(config_content)
def create_postcss_config(path):
config_content = """export default {
plugins: {
'tailwindcss/nesting': {},
tailwindcss: {},
autoprefixer: {},
},
}"""
with open(os.path.join(path, 'postcss.config.js'), 'w') as f:
f.write(config_content)
def modify_css(path):
css_content = """@tailwind base;
@tailwind components;
@tailwind utilities;"""
with open(os.path.join(path, 'src', 'index.css'), 'w') as f:
f.write(css_content)
def setup_flask_ts(folder_name="flask-ts-app"):
try:
# Create and configure root window with HiDPI support
try:
from ctypes import windll
windll.shcore.SetProcessDpiAwareness(2)
except:
pass
root = tk.Tk()
try:
root.tk.call('tk', 'scaling', root.winfo_fpixels('1i')/72.0)
except:
pass
root.withdraw()
path = filedialog.askdirectory(
title="Select Directory for Flask Project"
)
if not path:
return False
full_path = os.path.join(path, folder_name)
if os.path.exists(full_path):
raise Exception(f"Directory {full_path} already exists")
try:
os.makedirs(full_path)
except PermissionError:
raise Exception(f"Permission denied: Cannot create directory at {full_path}")
except Exception as e:
raise Exception(f"Failed to create directory at {full_path}: {str(e)}")
# Create main project directories
backend_path = os.path.join(full_path, 'backend')
frontend_path = os.path.join(full_path, 'frontend')
os.makedirs(backend_path)
os.makedirs(frontend_path)
# Setup Backend
print("\nSetting up Flask Backend...")
# Create backend structure
backend_app = os.path.join(backend_path, 'app')
os.makedirs(os.path.join(backend_app, 'routes'), exist_ok=True)
os.makedirs(os.path.join(backend_app, 'models'), exist_ok=True)
os.makedirs(os.path.join(backend_app, 'schemas'), exist_ok=True)
# Create pyproject.toml for Poetry
pyproject_content = """[tool.poetry]
name = "flask-ts-backend"
version = "0.1.0"
description = "Flask backend initialized by Scripty"
authors = ["Your Name <your.email@example.com>"]
[tool.poetry.dependencies]
python = "^3.9"
flask = "^3.0.0"
flask-cors = "^4.0.0"
python-dotenv = "^1.0.0"
flask-sqlalchemy = "^3.1.0"
marshmallow = "^3.20.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.4.0"
black = "^23.7.0"
mypy = "^1.5.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"""
with open(os.path.join(backend_path, 'pyproject.toml'), 'w') as f:
f.write(pyproject_content)
# Create main app file
app_content = """from flask import Flask
from flask_cors import CORS
from dotenv import load_dotenv
import os
load_dotenv()
def create_app():
app = Flask(__name__)
CORS(app)
# Configure SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///app.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Register routes
from app.routes import main
app.register_blueprint(main.bp)
return app
app = create_app()
if __name__ == '__main__':
app.run(port=5000)"""
with open(os.path.join(backend_app, '__init__.py'), 'w') as f:
f.write(app_content)
# Create routes
routes_content = """from flask import Blueprint, jsonify
bp = Blueprint('main', __name__, url_prefix='/api')
@bp.route('/test')
def test():
return jsonify({'message': 'Flask backend is working! Initialized by Scripty'})"""
with open(os.path.join(backend_app, 'routes', 'main.py'), 'w') as f:
f.write(routes_content)
# Create models
models_content = """from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Example model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.username}>'"""
with open(os.path.join(backend_app, 'models', '__init__.py'), 'w') as f:
f.write(models_content)
# Create .env
env_content = """FLASK_APP=app
FLASK_ENV=development
FLASK_DEBUG=1
DATABASE_URL=sqlite:///app.db
SECRET_KEY=your-secret-key-here"""
with open(os.path.join(backend_path, '.env'), 'w') as f:
f.write(env_content)
# Create requirements.txt as backup
requirements_content = """flask>=3.0.0
flask-cors>=4.0.0
python-dotenv>=1.0.0
flask-sqlalchemy>=3.1.0
marshmallow>=3.20.0"""
with open(os.path.join(backend_path, 'requirements.txt'), 'w') as f:
f.write(requirements_content)
# Setup Frontend (reuse Vite setup)
print("\nSetting up TypeScript Frontend...")
# Add minimal logging for critical steps
print("Setting up project structure...") # Keep this to track progress
frontend_commands = [
f"npm create vite@latest . -- --template react-ts --force",
"npm install",
"npm install -D tailwindcss@3.3.0 postcss@8.4.31 autoprefixer@10.4.14",
"npm install axios @tanstack/react-query react-router-dom"
]
for cmd in frontend_commands:
if not run_command(cmd, cwd=frontend_path):
print(f"Failed to execute: {cmd}") # Keep this critical error logging
return False
# Use the same helper functions as setup_vite
create_tailwind_config(frontend_path)
create_postcss_config(frontend_path)
modify_css(frontend_path)
# Create frontend .env
frontend_env = """VITE_API_URL=http://localhost:5000/api"""
with open(os.path.join(frontend_path, '.env'), 'w') as f:
f.write(frontend_env)
# Create App.tsx with Flask backend test
app_content = """import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { useEffect, useState } from 'react'
import axios from 'axios'
const queryClient = new QueryClient()
function App() {
const [backendMessage, setBackendMessage] = useState('')
useEffect(() => {
axios.get('http://localhost:5000/api/test')
.then(response => setBackendMessage(response.data.message))
.catch(error => console.error('Error:', error))
}, [])
return (
<QueryClientProvider client={queryClient}>
<Router>
<div className="min-h-screen bg-gray-50">
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto py-6 px-4">
<h1 className="text-3xl font-bold text-gray-900">
Flask + TypeScript App <span className="text-purple-600">by Scripty</span>
</h1>
</div>
</header>
<main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
<div className="px-4 py-6 sm:px-0">
<div className="bg-white rounded-xl shadow-lg p-6">
<p className="text-gray-600">Backend Message:</p>
<p className="text-lg font-semibold mt-2">{backendMessage}</p>
</div>
<Routes>
<Route path="/" element={<div>Welcome to your Flask + TypeScript app!</div>} />
</Routes>
</div>
</main>
</div>
</Router>
</QueryClientProvider>
)
}
export default App"""
with open(os.path.join(frontend_path, 'src', 'App.tsx'), 'w') as f:
f.write(app_content)
# Create README
readme_content = f"""# {folder_name}
Flask + TypeScript Stack project initialized by Scripty
## Project Structure
{folder_name}/
- backend/ # Flask Python backend
- frontend/ # React TypeScript frontend
## Getting Started
1. Start the backend:
cd backend
# If using Poetry:
poetry install
poetry run flask run
# If using pip:
pip install -r requirements.txt
flask run
2. Start the frontend:
cd frontend
npm install
npm run dev"""
with open(os.path.join(full_path, 'README.md'), 'w') as f:
f.write(readme_content)
return True
except Exception as e:
if os.path.exists(full_path):
try:
import shutil
shutil.rmtree(full_path)
except:
pass
return False
async def func(args):
"""Handler function for Flask + React project setup"""
try:
folder_name = args.get("folder_name")
if not folder_name:
return json.dumps({
"success": False,
"error": "Folder name is required"
})
if setup_flask_ts(folder_name):
return json.dumps({
"success": True,
"message": f"Flask + React project created successfully in {folder_name}"
})
else:
return json.dumps({
"success": False,
"error": "Project setup failed. Check console for details."
})
except Exception as e:
return json.dumps({
"success": False,
"error": str(e)
})
object = {
"name": "flask_setup",
"description": "Create a new Flask + React project with TypeScript and TailwindCSS",
"parameters": {
"type": "object",
"properties": {
"folder_name": {
"type": "string",
"description": "Name of the project folder",
"default": "flask_project"
}
}
}
}