目录


一、环境安装

1、安装python

python >= 3.6

2、安装Django3

pip install django=3

3、安装mysqlclient

pip install mysqlclient

如果安装失败可能是没有mysqlclient环境根据官方提示安装

macOS (Homebrew)

国内源安装homebrew

/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"

Install MySQL and mysqlclient:

# Assume you are activating Python 3 venv
$ brew install mysql
$ pip install mysqlclient

If you don't want to install MySQL server, you can use mysql-client instead:

# Assume you are activating Python 3 venv
$ brew install mysql-client
$ echo 'export PATH="/usr/local/opt/mysql-client/bin:$PATH"' >> ~/.bash_profile
$ export PATH="/usr/local/opt/mysql-client/bin:$PATH"
$ pip install mysqlclient

LINUX

Note that this is a basic step. I can not support complete step for build for all environment. If you can see some error, you should fix it by yourself, or ask for support in some user forum. Don't file a issue on the issue tracker.

You may need to install the Python 3 and MySQL development headers and libraries like so:

$ sudo apt-get install python3-dev default-libmysqlclient-dev build-essential% sudo yum install python3-devel mysql-devel

Then you can install mysqlclient via pip now:

$ pip install mysqlclient
二、项目管理

1、新建项目

任意目录执行

django-admin startproject fastDjango

2、新建app

cd fastDjango #进入项目跟目录

python manage.py startapp fastApp

a、修改项目目录下的 fastDjango/setting.py

# todo 第一个修改的地方,允许任何IP访问
ALLOWED_HOSTS = ['*']

# todo 第二个修改的地方,增加app
INSTALLED_APPS = [
    'fastApp.apps.FastappConfig', #新增加的内容
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

# todo 第三个修改的地方,把sqlite换成mysql
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'root',
        'PASSWORD': '12345678',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

b、编辑 fastDjango/urls.py 把fastApp/urls.py配置的导入,稍后会对 fastApp/urls.py进行配置(默认无此文件需要新建)

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('fastApp/', include('fastApp.urls')),
    path('admin/', admin.site.urls),
]
三、添加接口

获取 url中的参数, GET请求,POST请求,上传文件

1、编辑 fastApp/views.py 定义请求接口时调用的方法

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt


# @require_http_methods(["GET", "POST"])
@require_http_methods(["GET"])
def get_test(request):
    res = {
        'code': 0,
        'method': "GET",
        'msg': "Hello! This is /fastApp/index"
    }
    return JsonResponse(res)

@require_http_methods(["GET"])
def api_path_params(request, id):
    res = {
        'code': 0,
        'method': "GET",
        'msg': "api_path_params is %s." % id
    }
    return JsonResponse(res)

@require_http_methods(["POST"])
@csrf_exempt
def post_test(request):
    res = {
        'code': 0,
        'method': "POST",
        'msg': "csrf_exempt 是为了解决post请求安全校验报错"
    }
    return JsonResponse(res)

2、新建 fastApp/urls.py 定义请求的接口地址及调用的方法

from django.urls import path
#将fastApp/views.py 中的方法导入到fastApp/urls.py
#以便将方法与URL绑定,访问URL自动执行绑定的方法
from . import views

urlpatterns = [
    # ex: /fastApp/
    path('', views.get_test, name='get_test'),
    # ex: /fastApp/5/
    path('<int:id>/', views.api_path_params, name='api_path_params'),
    # ex: /fastApp/post_test
    path('post_test/', views.post_test, name='post_test'),
]

接口请求的时候先找fastDjango/urls.py的路径,当遇到fastApp/ 时自动寻找fastApp/urls.py配置

3、获取GET请求参数, fastApp/views.py 增加方法,同时在fastApp/urls.py中增加路由

@require_http_methods(["GET"])
def get_method_params(request):
    if request.method == 'GET':
        params = request.GET.lists()
        res = {
            'code': 0,
            'msg': "获取请求的参数",
            'data': dict(params)
        }
        return JsonResponse(res)

返回结果

{ "code": 0, "msg": "获取请求的参数", "data": {"a": ["1"],"b": ["2"]} }

4、获取POST请求参数, fastApp/views.py 增加方法,同时在fastApp/urls.py中增加路由

@require_http_methods(["POST"])
@csrf_exempt
def post_method_data(request):
    if request.method == 'POST':
        data = request.POST.lists()
        res = {
            'code': 0,
            'msg': "获取请求的参数",
            'data': dict(data)
            }
        return JsonResponse(res)

5、POST 上传文件, fastApp/views.py 增加方法,同时在fastApp/urls.py中增加路由

@require_http_methods(["POST"])
@csrf_exempt
def upload_file(request):
    if request.method == 'POST':
        with open('./fastApp/upload/upload_test.zip', 'wb+') as fp:
            for chunk in request.FILES['file'].chunks():
                fp.write(chunk)
        res = {
            'code': 0,
            'msg': "上传文件"
            }
        return JsonResponse(res)
四、数据库操作

如果没有配置过数据库修改 fastDjango/setting.py, 连接mysql数据库

1、更新数据库,fastApp/model.py 增加方法

from django.db import models


class Table1(models.Model):
    age = models.IntegerField(default=0)
    name = models.CharField(max_length=200)

2、把mode的数据库修改提交到 migrate

python manage.py makemigrations fastApp

3、查看0001 的数据库更新语句

python manage.py sqlmigrate fastApp 0001

4、数据库修改更新到数据库

python manage.py migrate

五、启动服务

修改项目目录下的 fastDjango/setting.py,允许所有host访问

ALLOWED_HOSTS = ['*']

启动服务器 0 代表 0.0.0.0

python manage.py runserver 0:8000