将项目文件夹名修改为config
接下来创建一个app目录,这里我创建user
目录,用于处理用户搜索、用户信息的接口。
python manage.py startapp user
在user/views.py
添加如下内容
from django.http import HttpResponse
def searchUser(request):
name = request.GET.get('name')
return HttpResponse("user" + name) # 字符串作为返回内容
具体请求和响应对象的用法,参考https://docs.djangoproject.com/zh-hans/3.1/ref/request-response/
配置路由
在config/urls.py
添加以下内容
from django.contrib import admin
from django.urls import path
# 导入searchUser函数
from user.views import searchUser
urlpatterns = [
path('admin/', admin.site.urls),
path('user/search/', searchUser), # 为searchUser函数配置user/search路由
]
在config/setting.py
的INSTALLED_APPS中添加user
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
]
配置跨域
首先安装django-cors-headers模块
pip install django-cors-headers
在config/setting.py
中修改
ALLOWED_HOSTS = ['skyemperor.top', 'localhost', '127.0.0.1']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'user',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ('http://*.*.*.*:*', 'http://skyemperor.top:*', 'http://localhost', 'http://127.0.0.1')
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = ('*',)
运行项目,访问
http://127.0.0.1:8000/user/search?name=ee
,会得到结果useree
在config/_init_.py
中添加
import pymysql
pymysql.install_as_MySQLdb()
在config/setting.py
中配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1', # 数据库主机
'PORT': 3306, # 数据库端口
'USER': 'user', # 数据库用户名
'PASSWORD': '123456', # 数据库用户密码
'NAME': 'library' # 数据库名字
}
}
在user/models.py
中创建数据库对象
from django.db import models
class Student(models.Model):
user_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
age = models.CharField(max_length=20)
# 指定表名
class Meta:
db_table = 'student'
def insert(request):
# 随机整数 作为学号
for i in range(0, 5):
student = Student() # 从models文件中获取student对象
# 给对象赋值
student.user_id = i
student.name = 'name' + str(i)
student.age = 15
student.save() # 插入数据
return HttpResponse('添加成功')
def delete(request):
user_id = request.GET.get('id')
student = Student.objects.get(user_id=user_id)
student.delete()
return HttpResponse('删除成功')
def modify(request):
# 通过学号获取student对象
student = Student.objects.get(user_id=3)
# 设置student的name为jack
student.name = 'jack'
student.save()
return HttpResponse('修改成功')
def find(request):
# django 也可以执行原生的sql语句
#sql = 'select * from student'
#result = Student.objects.raw(sql)
# 查询name = tom的数据
result = Student.objects.filter(name='tom')
# result为的对象,需要进行数据处理
arr = []
for i in result:
content = {
'user_id': i.user_id, 'name': i.name, 'age': i.age}
arr.append(content)
print(arr)
return HttpResponse(arr)
# 在本地生成依赖库版本文件
pip freeze > requirements.txt
# 安装模块
pip install -r requirements.txt
# 运行Django项目
nohup python manage.py runserver 0.0.0.0:6000 &