2020-10-17DJango_day1

一、创建一个django项目

  • 使用cmd,选择一个目录下输入如下代码,创建一个test_2项目
django-admin startproject test_2
  • 启动django项目mysite,进入mysite目录下
python manage.py runserver
  • 使用ctrl+z,结束项目

二、配置django文件

  • 进入test_2目录可发现有如下文件
    test_2下面的文件
__init__.py 	//表明test_2是一个python包

settings.py 	//test_2的项目配置文件,比如添加应用,连接数据库等

urls.py			//映射路径,若想访问http://127.0.0.1:8000/hello,则需要去urls.py中配置路由,在urlpatterns中添加path('/hello',views.index_views),

views.py		//图视文件,test_2中没有自己建立的。一般在views.py中定义方法,urls.py用指定的路由配对相应的方法

wsgi.py			//网络接口,一般不进行设置

当我们想显示一个页面时(不建议这样使用,等下会讲更好的,了解即可)

  1. 创建一个test_2/views.py,用来存一个函数,函数指定返回一个http文件,或其他类型的文件
  2. 然后,我们在urls.py中配置路由,在urlpatterns中添加一行
# views是test_2/views.py
path('/hello',views.index_views), 	//当访问http://127.0.0.1:8000/hello 时返回http文件,views.index_views的意思是 views下的index_views()函数
  1. views.py中定义一个index_views()函数
from django.http import HttpResponse #django.http中HttpResponse类返回一个html文件或其他类型的文件在网页上

def index_views(request): 	# reuqest参数必须要,用于接收响应

    return HttpResponse("hello world!") # HttpResponse中也可以是.html文件

三、在项目下创建应用

  • 项目就好比一个学校,而应用就好比一个学院,一个学校中有很多学院,且有不同的功能。
  • 为了我们的项目更好的运行,我们会把在项目里创建多个应用。
    进入test_2目录下输入:
python manage.py startapp helloworld
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用`django_celery_beat`可以很方便地实现在前端添加定时任务。 首先需要在`settings.py`中配置`django_celery_beat`的数据库信息: ```python INSTALLED_APPS = [ # ... 'django_celery_beat', # ... ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers.DatabaseScheduler' ``` 在`urls.py`中配置任务添加和删除的路由: ```python from django.urls import path from . import views urlpatterns = [ path('add_task/', views.add_task, name='add_task'), path('delete_task/<int:task_id>/', views.delete_task, name='delete_task'), ] ``` 然后在`views.py`中实现添加和删除任务的方法: ```python from django.shortcuts import render, redirect from django.urls import reverse from django.utils.timezone import localtime from django_celery_beat.models import PeriodicTask, CrontabSchedule from datetime import datetime, timedelta def add_task(request): if request.method == 'POST': task_name = request.POST.get('task_name') task_url = request.POST.get('task_url') task_time = request.POST.get('task_time') task_args = request.POST.get('task_args') task_kwargs = request.POST.get('task_kwargs') task_enabled = True if request.POST.get('task_enabled') == 'on' else False crontab, created = CrontabSchedule.objects.get_or_create( minute=task_time.split(':')[1], hour=task_time.split(':')[0], day_of_week='*', day_of_month='*', month_of_year='*' ) periodic_task = PeriodicTask.objects.create( name=task_name, task='tasks.run_task', args=task_args, kwargs=task_kwargs, crontab=crontab, enabled=task_enabled ) return redirect(reverse('task_list')) return render(request, 'add_task.html') def delete_task(request, task_id): task = PeriodicTask.objects.get(id=task_id) task.delete() return redirect(reverse('task_list')) ``` 在`add_task.html`模板中添加表单用于添加任务: ```html <form method="post" action="{% url 'add_task' %}"> {% csrf_token %} <div class="form-group"> <label for="task_name">Task Name:</label> <input type="text" class="form-control" id="task_name" name="task_name" required> </div> <div class="form-group"> <label for="task_url">Task URL:</label> <input type="text" class="form-control" id="task_url" name="task_url" required> </div> <div class="form-group"> <label for="task_time">Task Time:</label> <input type="time" class="form-control" id="task_time" name="task_time" required> </div> <div class="form-group"> <label for="task_args">Task Args:</label> <input type="text" class="form-control" id="task_args" name="task_args"> </div> <div class="form-group"> <label for="task_kwargs">Task Kwargs:</label> <input type="text" class="form-control" id="task_kwargs" name="task_kwargs"> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" id="task_enabled" name="task_enabled" checked> <label class="form-check-label" for="task_enabled">Enabled</label> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> ``` 最后在`templates`目录下创建`task_list.html`模板用于展示所有定时任务: ```html {% extends 'base.html' %} {% block content %} <h1>Task List</h1> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Name</th> <th scope="col">Task</th> <th scope="col">Args</th> <th scope="col">KWArgs</th> <th scope="col">Time</th> <th scope="col">Enabled</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for task in tasks %} <tr> <th scope="row">{{ task.id }}</th> <td>{{ task.name }}</td> <td>{{ task.task }}</td> <td>{{ task.args }}</td> <td>{{ task.kwargs }}</td> <td>{{ task.crontab.minute }}:{{ task.crontab.hour }}</td> <td>{% if task.enabled %}Yes{% else %}No{% endif %}</td> <td> <a href="{% url 'delete_task' task.id %}" class="btn btn-danger">Delete</a> </td> </tr> {% endfor %} </tbody> </table> {% endblock %} ``` 在`tasks.py`中实现定时任务的具体操作: ```python from celery import shared_task @shared_task def run_task(url, args=None, kwargs=None): # do something pass ``` 最后在`views.py`中实现展示所有定时任务的方法: ```python from django.shortcuts import render from django_celery_beat.models import PeriodicTask def task_list(request): tasks = PeriodicTask.objects.all() context = { 'tasks': tasks } return render(request, 'task_list.html', context) ``` 这样就可以在前端添加定时任务了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值