python:Django Rest Framework

一、创建项目

1、在pycharm中创建项目
在这里插入图片描述
2、修改配置

"""
# 额外安装的模块
pip install django-cors-headers -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
pip install djangorestframework -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
pip install coreapi -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
"""

# 接收的host
ALLOWED_HOSTS = ['*']

# DRF相关应用
INSTALLED_APPS = [
	'simpleui', # 美化admin页面
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',  ##################
    'rest_framework.authtoken',  # DRF自带的Token认证
    'corsheaders',  # 处理跨域
]

# 增加跨域忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# 允许所有方法
CORS_ALLOW_METHODS = ('*')
# 允许所有请求头
CORS_ALLOW_HEADERS = ('*')


# CORS_ORIGIN_WHITELIST = (
#     'http://127.0.0.1:5004',
#     'http://localhost:5004',
#     'http://127.0.0.1:2332',
#     'http://localhost:2332',
# )

MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 解决跨域问题,注意与common.CommonMiddleware的顺序
    'django.middleware.common.CommonMiddleware',
	...
]

# DRF的全局配置
REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 50,
    'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
    'DEFAULT_RENDER_CLASSES': [
        'rest_framework.renders.JSONRender',
        'rest_framework.renders.BrowsableAPIRenderer',
    ],
    'DEFAULT_PARSER_CLASSES': [  # 解析request.data
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        # from rest_framework.permissions import IsAuthenticatedOrReadOnly,IsAuthenticated,IsAdminUser,AllowAny // 未登录可读,必须登录,必须是管理员,所有人可操作
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
}

"""
1.使用Django manage.py生成Token // python manage.py drf_create_token admin
2.通过Django的信号机制生成Token
"""


# 数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'dealdb',
        'USER': 'root',
        'PASSWORD': '123',  # 密码
        'HOST': 'localhost',
        'PORT': '3306'
    },
}

# 时间设置
LANGUAGE_CODE = 'zh-hans' # 语言设置为中文

TIME_ZONE = 'Asia/Shanghai' # 时间地区设为上海

USE_I18N = True

USE_L10N = True

USE_TZ = False # 不使用时区

# 静态资源设置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")  ##################
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "staticfiles")  ##################
]

AUTH_USER_MODEL = 'accounts.MyUser' # 设置用户模型

#配置静态资源
STATIC_URL = ‘/static/’ # 静态资源的起始url
STATIC_ROOT = ‘all_static’ # 收集整个项目的静态资源,并存放在一个新的文件夹(自建)
STATICFILES_DIRS = [os.path.join(BASE_DIR, ‘static’)] # 项目的根目录下存放静态资源

3、配置mysql数据库连接

# Deal-->__init__.py
import pymysql

pymysql.install_as_MySQLdb()

4、创建新的应用程序(Terminal)

# 在Terminal中创建新应用
python manage.py startapp index

# 在setting中添加新应用
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'index',
]

# 设置路由
from django.contrib import admin
from django.urls import path
from index import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
]

# 设置视图函数
from django.shortcuts import render

def index(request):
    return render(request, "index/index.html", locals())

# 设置静态资源
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<div>
    <p>Welcome django.</p>
</div>
</body>

</html>

5、数据迁移

# 在Terminal中操作
python manage.py makemigrations
python manage.py migrate

二、常用命令

# 数据库迁移
python manage.py makemigrations
python manage.py migrate

# 创建管理员
python manage.py createsuperuser

# 创建新的应用程序(Terminal)
python manage.py startapp app     # django-admin startapp accounts

# 开启服务
python manage.py runserver
python manage.py runserver 0.0.0.0:8000

# 访问网站
http://127.0.0.1:8000/

# 复制静态资源(Terminal)
python manage.py collectstatic

# 创建缓存数据表
python manage.py createcachetable

快速启动命令.bat

@echo off
cd D:\Demo\
python manage.py runserver 0.0.0.0:5000
cmd /k

三、常见问题

1、DEBUG = False时,admin静态资源丢失问题

在setting.py中:

DEBUG = False	# 生产模式

ALLOWED_HOSTS = ['10.28.1.231','182.150.115.101','172.31.2.174','127.0.0.1']	# django程序本地IP

# 静态资源设置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")

url.py中新增:

# todo:Admin静态资源新增
from django.conf import settings
from django.conf.urls import url
from django.views import static

urlpatterns = [
    ...

    # todo:Admin静态资源新增
    url(r'^static/(?P<path>.*)$', static.serve,
        {'document_root': settings.STATIC_ROOT}, name='static'),
]

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值