pip install requests
全部代码:
import subprocess
import os
import requests
import zipfile
def replace_content_in_file(file_path, keyword, new_content):
try:
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
with open(file_path, 'w', encoding='utf-8') as file:
for line in lines:
if keyword in line:
line = line.replace(keyword, new_content)
file.write(line)
print(f"成功在文件中找到'{keyword}'并进行了替换。")
except FileNotFoundError:
print(f"文件 {file_path} 不存在。")
# 使用示例
# file_path = 'myapp/settings.py'
# keyword = 'ALLOWED_HOSTS = []'
# new_content = "ALLOWED_HOSTS = ['*']"
# replace_content_in_file(file_path, keyword, new_content)
def add_content_after_keyword(file_path, keyword, new_content):
try:
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
with open(file_path, 'w', encoding='utf-8') as file:
for line in lines:
if keyword in line:
line = line.rstrip() + new_content + '\n'
file.write(line)
print(f"成功在文件中找到'{keyword}'并添加了内容。")
except FileNotFoundError:
print(f"文件 {file_path} 不存在。")
# 使用示例
# file_path = 'myapp/settings.py'
# keyword = "'django.contrib.staticfiles',"
# new_content = "\n\t'app',"
def download_and_extract_zip(url, destination_directory):
# 下载 zip 文件
response = requests.get(url)
zip_filename = os.path.join(destination_directory, 'downloaded.zip')
with open(zip_filename, 'wb') as f:
f.write(response.content)
# 解压 zip 文件
with zipfile.ZipFile(zip_filename, 'r') as zip_ref:
zip_ref.extractall(destination_directory)
# 删除下载的 zip 文件
os.remove(zip_filename)
# 使用示例
url = 'https://gitee.com/layui/layui/attach_files/1930232/download'
destination_directory = 'static'
def create_django_project_and_app(project_name, app_name):
try:
# 创建 Django 项目
subprocess.run(["django-admin", "startproject", project_name], check=True)
# 切换到项目目录
os.chdir(project_name)
# 创建应用
subprocess.run(["python", "manage.py", "startapp", app_name], check=True)
# 创建templates目录
os.makedirs('templates', exist_ok=True)
# 创建 static 目录
os.makedirs('static', exist_ok=True)
# 创建media目录
os.makedirs('media', exist_ok=True)
file_path = project_name +'/settings.py'
keyword = "'django.contrib.staticfiles',"
new_content = "\n\t"+"'"+app_name+"'"+","
add_content_after_keyword(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = 'ALLOWED_HOSTS = []'
new_content = "ALLOWED_HOSTS = ['*']"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = "'DIRS': [],"
new_content = "'DIRS': [ BASE_DIR / 'templates'],"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = "LANGUAGE_CODE = 'en-us'"
new_content = "LANGUAGE_CODE = 'zh-hans'"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = "TIME_ZONE = 'UTC'"
new_content = "TIME_ZONE = 'Asia/Shanghai'"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = "from pathlib import Path"
new_content = "from pathlib import Path\nimport os"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/settings.py'
keyword = "STATIC_URL = 'static/'"
new_content = "STATIC_URL = 'static/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')"
replace_content_in_file(file_path, keyword, new_content)
answer = input("请输入 Y 或 N:")
if answer.upper() == 'Y':
print("你选择了 yes。")
file_path = app_name +'/models.py'
keyword = "from django.db import models"
new_content = ProductX
replace_content_in_file(file_path, keyword, new_content)
# 执行 makemigrations 命令 执行 migrate 命令
subprocess.run(["python", "manage.py", "makemigrations"], check=True)
subprocess.run(["python", "manage.py", "migrate"], check=True)
file_path = app_name +'/admin.py'
keyword = "from django.contrib import admin"
new_content = adminX
replace_content_in_file(file_path, keyword, new_content)
with open(f'{app_name}/urls.py', 'w') as urls_file:
urls_file.write(urls_content)
file_path = app_name +'/views.py'
keyword = "from django.shortcuts import render"
new_content = viewsX
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/urls.py'
keyword = "from django.urls import path"
new_content = "from django.urls import include, path\nfrom app.views import product_list # 导入的视图函数"
replace_content_in_file(file_path, keyword, new_content)
file_path = project_name +'/urls.py'
keyword = "path('admin/', admin.site.urls),"
new_content = "path('admin/', admin.site.urls),\npath('', product_list, name='home'),\npath('"+app_name+"/', include('"+app_name+".urls')),"
replace_content_in_file(file_path, keyword, new_content)
with open(f'templates/product_list.html', 'w',encoding="utf-8") as urls_file:
urls_file.write(product_list)
with open(f'templates/add_product.html', 'w',encoding="utf-8") as urls_file:
urls_file.write(add_product)
with open(f'templates/delete_product.html', 'w',encoding="utf-8") as urls_file:
urls_file.write(delete_product)
with open(f'templates/update_product.html', 'w',encoding="utf-8") as urls_file:
urls_file.write(update_product)
download_and_extract_zip(url, destination_directory) # 下载并解压文件
elif answer.upper() == 'N':
print("你选择了 no。")
# 执行 makemigrations 命令 执行 migrate 命令
subprocess.run(["python", "manage.py", "makemigrations"], check=True)
subprocess.run(["python", "manage.py", "migrate"], check=True)
else:
print("输入错误,请重新输入 Y 或 N。")
with open(f'viewSQL.py', 'w',encoding="utf-8") as urls_file:
urls_file.write(viewSQL)
# 创建超级用户
os.system("python manage.py createsuperuser")
# 运行开发服务器
subprocess.run(["python", "manage.py", "runserver"], check=True)
print(f"成功创建 Django 项目:{project_name},并创建应用:{app_name}")
except subprocess.CalledProcessError as e:
print(f"创建过程中出现错误:{e}")
ProductX = """
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255, verbose_name="商品名称")
description = models.TextField( verbose_name="商品描述")
quantity = models.PositiveIntegerField( verbose_name="商品数量")
price = models.DecimalField(max_digits=10, decimal_places=2 , verbose_name="商品价格")
class Meta:
verbose_name = "商品"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Sale(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE , verbose_name="商品")
quantity_sold = models.PositiveIntegerField( verbose_name="销售数量")
sale_date = models.DateTimeField(auto_now_add=True , verbose_name="销售日期")
class Meta:
verbose_name = "销售"
verbose_name_plural = verbose_name
class Purchase(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE , verbose_name="商品")
quantity_purchased = models.PositiveIntegerField( verbose_name="购买数量")
purchase_date = models.DateTimeField(auto_now_add=True , verbose_name="购买日期")
class Meta:
verbose_name = "购买"
verbose_name_plural = verbose_name"""
adminX = """
from django.contrib import admin
from.models import Product, Sale, Purchase
admin.site.register(Product)
admin.site.register(Sale)
admin.site.register(Purchase)"""
# 在应用中创建 urls.py 文件并写入内容
urls_content = """from django.urls import path
from.views import product_list, add_product, update_product, delete_product
urlpatterns = [
path('products/', product_list, name='product_list'),
path('products/add/', add_product, name='add_product'),
path('products/update/<int:product_id>/', update_product, name='update_product'),
path('products/delete/<int:product_id>/', delete_product, name='delete_product'),
]
"""
viewsX = """
from django.shortcuts import render, redirect
from.models import Product
def product_list(request):
products = Product.objects.all()
total_quantity = sum(product.quantity for product in products)
total_price = sum(product.price * product.quantity for product in products)
return render(request, 'product_list.html', {'products': products, 'total_quantity': total_quantity, 'total_price': total_price})
def add_product(request):
if request.method == 'POST':
name = request.POST['name']
description = request.POST['description']
quantity = int(request.POST['quantity'])
price = float(request.POST['price'])
product = Product(name=name, description=description, quantity=quantity, price=price)
product.save()
return redirect('product_list')
return render(request, 'add_product.html')
def update_product(request, product_id):
product = Product.objects.get(pk=product_id)
if request.method == 'POST':
product.name = request.POST['name']
product.description = request.POST['description']
product.quantity = int(request.POST['quantity'])
product.price = float(request.POST['price'])
product.save()
return redirect('product_list')
return render(request, 'update_product.html', {'product': product})
def delete_product(request, product_id):
product = Product.objects.get(pk=product_id)
if request.method == 'POST':
product.delete()
return redirect('product_list')
return render(request, 'delete_product.html', {'product': product})"""
dir_urls = """from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]"""
root_urls = """
from django.contrib import admin
from django.urls import include, path
from app.views import product_list # 导入的视图函数
urlpatterns = [
path('admin/', admin.site.urls),
path('', product_list, name='home'), # 将根路径映射到 product_list 视图函数
path('app/', include('app.urls')), # 将 app 应用中的 URL 映射到 app.urls 模块
]"""
product_list = """
<!DOCTYPE html>
<html>
{% load static %}
<head>
<title>Product List</title>
<link rel="stylesheet" type="text/css" href="{% static 'layui-v2.9.18/layui/css/layui.css' %}">
</head>
<body>
<div class="layui-container">
<h1>Product List 商品列表</h1>
<table class="layui-table" lay-skin="line" lay-even>
<thead>
<tr>
<th>Name商品名称</th>
<th>Description 商品描述</th>
<th>Quantity 数量</th>
<th>Price 单价</th>
<th>Actions </th>
</tr>
</thead>
<tbody>
{% for product in products %}
<tr>
<td>{
{ product.name }}</td>
<td>{
{ product.description }}</td>
<td>{
{ product.quantity }}</td>
<td>{
{ product.price }}</td>
<td>
<a href="{% url 'update_product' product.id %}" class="layui-btn layui-btn-sm layui-btn-normal">Update 修改</a>
<a href="{% url 'delete_product' product.id %}" class="layui-btn layui-btn-sm layui-btn-danger">Delete 删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<h2>Tota