GVKun编程网logo

python测试开发django-83.Dockerfile部署django项目(python docker部署)

14

在本文中,我们将详细介绍python测试开发django-83.Dockerfile部署django项目的各个方面,并为您提供关于pythondocker部署的相关解答,同时,我们也将为您带来关于dj

在本文中,我们将详细介绍python测试开发django-83.Dockerfile部署django项目的各个方面,并为您提供关于python docker部署的相关解答,同时,我们也将为您带来关于django开发-在Docker中部署django项目、python3.8+django2+celery5.2.7环境准备(python测试开发django)、python测试开发django-1.开始hello world!、python测试开发django-10.django连接mysql的有用知识。

本文目录一览:

python测试开发django-83.Dockerfile部署django项目(python docker部署)

python测试开发django-83.Dockerfile部署django项目(python docker部署)

前言

现在流行用 docker 部署环境,python 开发的 django 项目也可以写个 Dockefile 文件,方便docker部署。
django 是依赖于python环境的,所有镜像制作是用一个python的镜像基础上把我们需要的环境添加过去就可以了。

Dockefile 文件

Dockefile的编写参考前面这篇https://www.cnblogs.com/yoyoketang/p/11397597.html

FROM python:3.6.8

MAINTAINER yoyo  <283340479@qq.com>

# 更新下apt列表
RUN apt-get update

# 更新pip
RUN pip install --upgrade pip --index-url https://pypi.douban.com/simple

# 工作目录
workdir /code
ADD . /code

# pip安装依赖包
RUN pip install -r requirements.txt --index-url https://pypi.douban.com/simple

# 打开容器的8000端口
EXPOSE 8000

# 执行命令行,启动django服务
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

requirements.txt 是django项目需要的依赖包,是开发完 django 项目之后,通过 pip 生成的

pip freeze >requirements.txt

Dockefile 和requirements.txt都是放到 django 项目的根目录下

build镜像

Dockefile 文件完成后,其它小伙伴拿到项目源码包,就可以在任意地方部署了。
把整个代码包放到 linux 服务器上,使用 docker 来 build 一个镜像

docker build -t django_yoyo .

这时候会看到build的步骤,等依赖包安装完成

[root@VM_0_2_centos yoyo]# docker build -t django_yoyo .
Sending build context to Docker daemon  7.729MB
Step 1/9 : FROM python:3.6.8
 ---> 48c06762acf0
Step 2/9 : MAINTAINER yoyo  <283340479@qq.com>
 ---> Using cache
 ---> 791e4b982a47
Step 3/9 : RUN apt-get update
 ---> Using cache
 ---> 4d9a2088753e
Step 4/9 : RUN pip install --upgrade pip --index-url https://pypi.douban.com/simple
 ---> Using cache
 ---> d896cb71a359
Step 5/9 : workdir /code
 ---> Using cache
 ---> c4d15025b172
Step 6/9 : ADD . /code
 ---> 8dcd424c81cd
Step 7/9 : RUN pip install -r requirements.txt --index-url https://pypi.douban.com/simple
 ---> Running in 8b84c81bfe5e
Step 8/9 : EXPOSE 8000
 ---> Running in d02c088d286d
Removing intermediate container d02c088d286d
 ---> 87bda6266abe
Step 9/9 : CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
 ---> Running in 1e616dd15c29
Removing intermediate container 1e616dd15c29
 ---> 984e5b0a9896
Successfully built 984e5b0a9896
Successfully tagged django_yoyo:latest

当看到 Successfully built 镜像就制作完成了,可以使用docker images查看镜像

[root@VM_0_2_centos yoyo]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
django_yoyo         latest              984e5b0a9896        58 seconds ago      1.2GB

这是本地镜像的制作过程,有镜像仓库的小伙伴,上传到镜像仓库,其它小伙伴部署起来更方便,直接通过docker pull就可以拉到镜像了。
镜像仓库上传参考这篇https://www.cnblogs.com/yoyoketang/p/11923263.html

启动容器

docker run 运行容器,将容器8000端口映射到宿主机8000端口

docker run -d -p 8000:8000 --name web_yoyo1 django_yoyo

查看容器状态'docker ps -a'查看容器是否是Up状态

[root@VM_0_2_centos yoyo]# docker ps -a
CONTAINER ID        IMAGE                       COMMAND                  CREATED              STATUS                  PORTS                   NAMES
ffd12bbbc16a        django_yoyo                 "python manage.py ru…"   About a minute ago   Up About a minute       0.0.0.0:8000->8000/tcp  

容器启动成功就可以访问django项目的页面了

django开发-在Docker中部署django项目

django开发-在Docker中部署django项目

今天整理了一下如何在docker中部署django项目。

1.环境如下:

python3.6  django2.0.5  nginx  mysql5.7  gunicorn

2.项目结构如下:
图片描述

由于仅仅是测试,项目比较简单,复杂的项目也是这个流程。

通过上面的结构,我们需要编写的文件包括

blog/Dockerfile, blog/gunicorn.conf, blog/start.sh, nginx/Doickerfile, nginx/nginx.conf, docker-conpose.yml

3.blog/Dockerfile(基础镜像使用的是python:3.6,而不是ubuntu、centos。如果是ubuntu、cenos,Dockerfile文件中需要配置python环境):

FROM python:3.6    # 选择基础镜像,这里的基础镜像也可以选择ubuntu,centos等,但是下面的配置就会发生变化

# 创建工作目录
RUN mkdir /blog  

#设置工作目录
WORKDIR /blog

#将当前目录加入到工作目录中
ADD . /blog
RUN pip3 install -r requirements.txt
#对外暴露端口
EXPOSE 80 8080 8000 5000
#设置环境变量
ENV SPIDER=/blog

4.blog/gunicorn.conf:

workers=2
bind=''0.0.0.0:8000''
proc_name=''blog''

5.blog/start.sh:

#!/bin/bash
python manage.py collectstatic --noinput&&
python manage.py makemigrations&&
python manage.py migrate &&
gunicornblog.wsgi:application -c gunicorn.conf

6.nginx/Dockerfile:

FROM nginx    # nginx镜像,最好是先拉取到本地


# 对外暴露端口
EXPOSE 80 8000

RUN rm /etc/nginx/conf.d/default.conf  # 删除原有配置文件
ADD nginx.conf  /etc/nginx/conf.d/   # 添加配置文件
RUN mkdir -p /usr/share/nginx/html/static  # 创建静态资源文件夹

7.nginx/nginx.conf:

server {
    listen      80;
    server_name localhost;

    location /static {
        alias /usr/share/nginx/html/static;
    }

    location / {
        proxy_pass http://web:8000;
        proxy_set_header Host $host;
        proxy_redirect off;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

}

8.docker-compose.yml:

version: "3"

services:


db:
    image: mysql:5.7  # mysql镜像,最好先拉取到本地
    environment:
      - MYSQL_HOST=localhost
      - MYSQL_DATABASE=docker
      - MYSQL_USER=root
      - MYSQL_PASSWORD=wyzane
      - MYSQL_ROOT_PASSWORD=wyzane
    volumes:
      - /home/wyzane/pyprojects/db:/var/lib/mysql  # 将宿主机与容器中的文件映射
    restart: always  # 若容器运行出现问题,会自动重启容器

  web:
    build: ./blog
    ports:
    - "8000:8000"
    volumes:
    - ./blog:/blog
    - /tmp/logs:/tmp
    command: bash start.sh  # 执行命令,有多种格式
    links:
    - db
    depends_on:
    - db
    restart: always

nginx:
    build: ./nginx
    ports:
    - "80:80"
    volumes:
    - ./blog/static:/usr/share/nginx/html/static:ro
    links:
    - web
    depends_on:
    - web
    restart: always

9.依次执行以下命令:
docker-compose build
docker-compose up -d

10.执行完成后,通过
docker images 命令可以查看新增了2个镜像
docker ps 命令可以查看启动了3个容器

多执行几次docker ps,当容器的STATUS是以Restarting开头时,表示这个容器运行时发生了错误。执行docker logs CONTAINERID可以查看容器出错的具体原因。

若上述容器都成功运行,则在浏览器中输入http://127.0.0.1:80/api/v1/articles/info/时,视图会返回相应的结果。
以交互方式进入容器:

docker exec -it CONTAINERID /bin/bash

后,进入mysql数据库,会看到在数据库中生成了相应的表。

11.运行中遇到的问题,在运行3个容器后,web容器一直报错,通过
docker logs CONTAINERID查看主要错误信息如下:

django.db.utils.OperationalError: (2003, ''Can\''t connect to MySQL server on \''mariadb55\'' (111 "Connection refused")'')

解决方案在这里 https://stackoverflow.com/que...
主要是在settings.py中,将database配置中的HOST值改成db,而不是127.0.0.1,指向docker-compose.yml中的db服务

参考自 https://blog.csdn.net/hbnn111...

今天就聊到这里,如有疑问,欢迎交流!

python3.8+django2+celery5.2.7环境准备(python测试开发django)

python3.8+django2+celery5.2.7环境准备(python测试开发django)

前言

以前版本的 Celery 需要一个单独的库(django-celery)来与 Django 一起工作,但从 3.1 开始不再是这种情况。
现在支持开箱即用的 Django,因此本文档仅包含集成 Celery 和 Django 的基本方法.
celery5.x 不支持windows平台了。Celery 5.0.x 支持 Django 1.11 LTS 或更新版本。

版本要求

Celery 5.2 版运行于

  • Python❨3.7、3.8、3.9、3.10❩
  • PyPy3.7、3.8 ❨7.3.7❩

Celery 4.x 是支持 Python 2.7 的最后一个版本,
Celery 5.x 需要 Python 3.6 或更高版本。
Celery 5.1.x 还需要 Python 3.6 或更高版本。
Celery 5.2.x 需要 Python 3.7 或更新版本。

如果您运行的是旧版本的 Python,则需要运行旧版本的 Celery:

Python 2.7 或 Python 3.5:Celery 系列 4.4 或更早版本。
Python 2.6:Celery 系列 3.1 或更早版本。
Python 2.5:Celery 系列 3.0 或更早版本。
Python 2.4 是 Celery 系列 2.2 或更早版本。

Celery 是一个资金很少的项目,所以不支持 Microsoft Windows。请不要打开与该平台相关的任何问题。

环境准备

运行系统:linux(centos/debian/ubuntu),不支持windows
Python版本:3.8.5
Django : 2.2.2
celery: 5.2.7

使用pip安装celery5.2.7版本

pip install celery==5.2.7

Django中使用Celery

要在 Django 项目中使用 Celery,您必须首先定义 Celery 库的实例(称为“应用程序”)
如果你有一个现代的 Django 项目布局,比如:

- proj/
  - manage.py
  - proj/
    - __init__.py
    - settings.py
    - urls.py

那么推荐的方法是创建一个新的proj/proj/celery.py模块来定义 Celery 实例:

proj/proj/celery.py 文件内容

import os
from celery import Celery
# Set the default Django settings module for the ''celery'' program.
os.environ.setdefault(''DJANGO_SETTINGS_MODULE'', ''proj.settings'')
app = Celery(''proj'')
# Using a string here means the worker doesn''t have to serialize
# the configuration object to child processes.
# - namespace=''CELERY'' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object(''django.conf:settings'', namespace=''CELERY'')
# Load task modules from all registered Django apps.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
    print(f''Request: {self.request!r}'')

然后你需要在你的proj/proj/init.py 模块中导入这个应用程序。这可以确保在 Django 启动时加载应用程序,以便@shared_task装饰器(稍后提到)将使用它:

proj/proj/__init__.py内容:

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = (''celery_app'',)

请注意,此示例项目布局适用于较大的项目,对于简单的项目,您可以使用单个包含的模块来定义应用程序和任务

让我们分解第一个模块中发生的事情,首先,我们设置默认值DJANGO_SETTINGS_MODULEcelery命令行程序的环境变量:

os.environ.setdefault(''DJANGO_SETTINGS_MODULE'', ''proj.settings'')

您不需要此行,但它使您不必总是将设置模块传递给celery程序。它必须始终在创建应用程序实例之前出现,就像我们接下来要做的那样:

app = Celery(''proj'')

这是我们的库实例,您可以有很多实例,但在使用 Django 时可能没有理由这样做。

我们还将 Django 设置模块添加为 Celery 的配置源。这意味着您不必使用多个配置文件,而是直接从 Django 设置中配置 Celery;但如果需要,您也可以将它们分开。

app.config_from_object(''django.conf:settings'', namespace=''CELERY'')

大写命名空间意味着所有 Celery 配置选项 必须以大写而不是小写指定,并且以 开头 CELERY_,例如task_always_eager设置变为CELERY_TASK_ALWAYS_EAGER,broker_url 设置变为CELERY_BROKER_URL。这也适用于工作人员设置,例如,worker_concurrency 设置变为CELERY_WORKER_CONCURRENCY.

例如,一个 Django 项目的配置文件可能包括:

...
# Celery Configuration Options
CELERY_TIMEZONE = "Australia/Tasmania"
CELERY_TASK_TRACK_STARTED = True
CELERY_TASK_TIME_LIMIT = 30 * 60

您可以直接传递设置对象,但使用字符串更好,因为这样工作人员不必序列化对象。CELERY_命名空间也是可选的,但建议使用(以防止与其他 Django 设置重叠)。

接下来,可重用应用程序的一个常见做法是在单独的tasks.py模块中定义所有任务,Celery 确实有一种方法可以自动发现这些模块:

app.autodiscover_tasks()

使用上面的代码,Celery 将自动从您安装的所有应用程序中发现任务,遵循tasks.py约定:

- app1/
    - tasks.py
    - models.py
- app2/
    - tasks.py
    - models.py

这样您就不必手动将各个模块添加到CELERY_IMPORTS设置中。

最后,该debug_task示例是一个转储自己的请求信息的任务。这是使用bind=True Celery 3.1 中引入的新任务选项来轻松引用当前任务实例。

使用 @shared_task 装饰器

您编写的任务可能会存在于可重用的应用程序中,而可重用的应用程序不能依赖于项目本身,因此您也不能直接导入您的应用程序实例。

装饰器允许您在@shared_task没有任何具体应用实例的情况下创建任务:

demoapp/tasks.py:

# Create your tasks here
from demoapp.models import Widget
from celery import shared_task
@shared_task
def add(x, y):
    return x + y
@shared_task
def mul(x, y):
    return x * y
@shared_task
def xsum(numbers):
    return sum(numbers)
@shared_task
def count_widgets():
    return Widget.objects.count()
@shared_task
def rename_widget(widget_id, name):
    w = Widget.objects.get(id=widget_id)
    w.name = name
    w.save()

您可以在以下位置找到 Django 示例项目的完整源代码: https ://github.com/celery/celery/tree/master/examples/django/

django-celery-results 保存结果

django-celery-results- 使用 Django ORM/Cache 作为结果后端
django-celery-results扩展使用Django ORM 或 Django Cache 框架提供结果后端。

要将其用于您的项目,您需要执行以下步骤:
1.安装django-celery-results库:

 pip install django-celery-results

2.添加django_celery_results到INSTALLED_APPS您的 Django 项目中settings.py:

INSTALLED_APPS = (
    ...,
    ''django_celery_results'',
)

请注意,模块名称中没有破折号,只有下划线。
3.通过执行数据库迁移来创建 Celery 数据库表:

 python manage.py migrate django_celery_results

4.配置 Celery 以使用django-celery-results后端。
假设您使用 Djangosettings.py来配置 Celery,添加以下设置

CELERY_RESULT_BACKEND = ''django-db''

对于缓存后端,您可以使用:

CELERY_CACHE_BACKEND = ''django-cache''

我们也可以使用 django 的 CACHES 设置中定义的缓存。

# celery setting.
CELERY_CACHE_BACKEND = ''default''

# django setting.
CACHES = {
    ''default'': {
        ''BACKEND'': ''django.core.cache.backends.db.DatabaseCache'',
        ''LOCATION'': ''my_cache_table'',
    }
}

有关其他配置选项,请查看 任务结果后端https://docs.celeryq.dev/en/stable/userguide/configuration.html#conf-result-backend设置参考。

django-celery-beat 定时任务

django-celery-beat- 具有管理界面的数据库支持的定期任务。 详细资料参考https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html#beat-custom-schedulers

启动工作进程

在生产环境中,您将希望在后台将工作程序作为守护程序运行 - 请参阅守护程序-但对于测试和开发,能够使用 celery worker manage 命令启动工作程序实例很有用,就像您一样d 使用 Django 的 manage.py runserver:

celery -A proj worker -l INFO

有关可用命令行选项的完整列表,请使用帮助命令:

 celery help

到此这篇关于python3.8+django2+celery5.2.7环境准备的文章就介绍到这了,更多相关python3.8+django2+celery5.2.7环境内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • Python Django2.0集成Celery4.1教程
  • 详尽讲述用Python的Django框架测试驱动开发的教程

python测试开发django-1.开始hello world!

python测试开发django-1.开始hello world!

前言

当你想走上测试开发之路,用python开发出一个web页面的时候,需要找一个支持python语言的web框架。django框架有丰富的文档和学习资料,也是非常成熟的web开发框架,想学python开发的小伙伴,从django入手是一个不错的选择。本篇写一个简单的“Hello World! ”页面,开始django之旅~
环境准备:
Python 3.6.0
django 2.1.2
pycharm

环境准备

django的环境安装非常简单,只需用pip安装一个django库就可以了,编辑器选择pycharm

pip install django==2.1.2

查看版本号:pip show django

C:\Users\dell>pip show django
Name: Django
Version: 2.1.2
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: e:\python36\lib\site-packages
Requires: pytz
required-by:

安装完之后在cmd检查下是否能用

C:\Users\dell>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
2.1.2
>>>
创建项目

先建一个工程,比如我的项目代码想放到E:\web_djo目录下,然后新建一个Django project( 即一个 Django 项目实例需要的设置项集合,包括数据库配置、Django 配置和应用程序配置。)
打开命令行,cd 到一个你想放置你代码的目录,然后运行以下命令:

django-admin startproject helloworld

执行完之后打开pycharm就可以看到web_djo工程目录下多了以下层级文件

─helloworld
    │  manage.py
    │  
    └─helloworld
            settings.py
            urls.py
            wsgi.py
            __init__.py

这些目录和文件的用处是:

  • 最外层的:helloworld: 项目的容器,可以随便命名。
  • manage.py: 一个让你用各种方式管理 Django 项目的命令行工具。
  • helloworld/__init__.py:一个空文件,告诉 Python 这个目录应该被认为是一个 Python 包。
  • helloworld/settings.py:Django 项目的配置文件。
  • helloworld/urls.py:Django 项目的 URL 声明,就像你网站的“目录”。
  • helloworld/wsgi.py:作为你的项目的运行在 Wsgi 兼容的Web服务器上的入口。
django-admin

django-admin.exe是一个可执行文件,安装django时候会默认安装到python3\Scripts目录下,相关指令用-h查看

E:\python36\Scripts>django-admin -h

Type 'django-admin help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
启动服务

接下来启动django服务,使用helloworld下的manage.py,先cd到web_djo/helloworld目录下,到在命令行输入以下指令:

python manage.py runserver

E:\web_djo\helloworld>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 23, 2018 - 21:09:39
Django version 2.1.2, using settings 'helloworld.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

启动完只看看到这句:Starting development server at http://127.0.0.1:8000/,复制地址在浏览器打开

django服务默认在8000端口启动,如果想换个端口,可以输入以下指令

python manage.py runserver 8080

如果一个局域网另外一台电脑也需要能访问,可以监听所有ip:python manage.py runserver 0.0.0.0:8000,访问的时候用电脑ip代替127.0.0.1

用于开发的服务器在需要的情况下会对每一次的访问请求重新载入一遍 Python 代码。所以你不需要为了让修改的代码生效而频繁的重新启动服务器。然而,一些动作,比如添加新文件,将不会触发自动重新加载,这时你得自己手动重启服务器。

视图和URL配置

在先前创建的helloworld/helloworld目录新建一个 view.py 文件,并输入代码

# helloworld/helloworld/view.py
from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello world !  django ~~")

绑定URL与视图函数。打开 urls.py 文件,删除原来代码,将以下代码复制粘贴到 urls.py 文件中

# helloworld/helloworld/urls.py
from django.conf.urls import url
from . import view

urlpatterns = [
    url(r'^$', view.index),
]

url函数

url() 可以接收四个参数,分别是两个必选参数:regex、view 和两个可选参数:kwargs、name.

def url(regex, view, kwargs=None, name=None):
    return re_path(regex, view, kwargs, name)
  • regex: 正则表达式,与之匹配的 URL 会执行对应的第二个参数 view。

  • view: 用于执行与正则表达式匹配的 URL 请求。

  • kwargs: 视图使用的字典类型的参数。

  • name: 用来反向获取 URL。

多个url设置

urlpatterns里面url(r'^$', view.index)这项是打开首页http://127.0.0.1:8000,平常网站会有多个页面,如果想加个页面地址如:http://127.0.0.1:8000/yoyo打开另外一个页面.

view.py加个函数

from django.http import HttpResponse
 
def index(request):
    return HttpResponse("Hello world ! django ~~ ")


def yoyo(request):
    return HttpResponse("yoyo!  django ~~ ")

urls.py加个配置

from django.conf.urls import url
from . import view

urlpatterns = [
    url('^$', view.index),
    url('^yoyo$', view.yoyo),
]

这样在浏览器上输入地址:http://127.0.0.1:8000/,打开页面出现:Hello world ! django ~~
在浏览器输入地址:http://127.0.0.1:8000/yoyo, 打开页面出现:yoyo! django ~~

关于regex正则表达式用法可以参考菜鸟教程http://www.runoob.com/regexp/regexp-tutorial.html

django交流QQ群:779429633

python测试开发django-10.django连接mysql

python测试开发django-10.django连接mysql

前言

Django 对各种数据库提供了很好的支持,包括:Postgresql、MysqL、sqlite、Oracle。本篇以MysqL为例简单介绍django连接MysqL进行数据操作
Django连MysqL需要安装驱动MysqLclient

MysqLclient安装

先要安装数据库驱动MysqLclient,使用pip安装就行

pip install MysqLclient

   copying MysqLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MysqLdb\constants
    copying MysqLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MysqLdb\constants
    running build_ext
    building '_MysqL' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    ----------------------------------------
Command "e:\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\dell\\AppData\\Local\\Temp\\pip-install-trc0p4gc\\MysqLclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\dell\AppData\Local\Temp\pip-record-ulwogpct\install-record.txt --single-version-externally-managed --compile" Failed with error code 1 in C:\Users\dell\AppData\Local\Temp\pip-install-trc0p4gc\MysqLclient\

这里我安装的时候出现了报错:“Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools” 打开报错给的地址404

解决办法,指定1.3.10版本安装

pip install MysqLclient==1.3.10

C:\Users\dell>pip install MysqLclient==1.3.10
Collecting MysqLclient==1.3.10
  Downloading https://files.pythonhosted.org/packages/c8/e0/e38c1fc71355bbc60e89401674bc0190f39a207f0235bb92b7e7b09948d0/MysqLclient-1.3.10-cp36-cp36m-win_amd64.whl (1.4MB)
    100% |████████████████████████████████| 1.4MB 466kB/s
Installing collected packages: MysqLclient
Successfully installed MysqLclient-1.3.10
django配置数据库

settings.py 文件中找到 DATABASES 配置项, django默认连接sqllite。ENGINE:是指连接数据库驱动的名称,有以下几种情况:

  • django.db.backends.postgresql 连接 Postgresql
  • django.db.backends.MysqL 连接 MysqL
  • django.db.backends.sqlite3 连接 sqlite
  • django.db.backends.oracle 连接 oracle

这里我们连接MysqL需要账户密码,也就是之前安装MysqL的root用户名,和自己设置的密码,NAME是数据库的名称,连接配置如下:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.MysqL',  # 或者使用 MysqL.connector.django
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD': 'yoyo',
        'HOST':'localhost',
        'PORT':'3306',
    }
}
创建表,同步到MysqL

类名代表了数据库表名,且继承了models.Model,类里面的字段代表数据表中的字段(name),数据类型则由CharField(相当于varchar)、DateField(相当于datetime), max_length 参数限定长度。

# models.py

from django.db import models

# Create your models here.

class Test(models.Model):
    name = models.CharField(max_length=20)

先创建表结构,在数据库里面新增一些表

python manage.py migrate

D:\web_djo\helloworld>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, hello, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying hello.0001_initial... OK
  Applying hello.0002_auto_20181122_1025... OK
  Applying hello.0003_auto_20181122_1033... OK
  Applying sessions.0001_initial... OK

打开数据库,会发现多了一些表名称,hello_test就是上一步新建的表

接着让 Django 知道我们在我们的模型有一些变更

python manage.py makemigrations hello

D:\web_djo\helloworld>python manage.py makemigrations hello
No changes detected in app 'hello'

再创建hello这个app应用的表结构

python manage.py migrate hello

D:\web_djo\helloworld>python manage.py migrate hello
Operations to perform:
  Apply all migrations: hello
Running migrations:
  No migrations to apply.
操作数据库

在settings.py同一目录新建一个testdb.py文件

# -*- coding: utf-8 -*-

from django.http import HttpResponse

from hello.models import Test

# 数据库操作
def testdb(request):
    test1 = Test(name='yoyo1')
    test1.save()
    return HttpResponse("数据库hello_test添加name成功!看去看看吧")

urls.py配置访问地址

from django.conf.urls import url
from django.urls import re_path, path
from . import view, testdb

urlpatterns = [
    url(r'^testdb$', testdb.testdb),
]

浏览器打开:http://127.0.0.1:8000/testdb 访问一次,数据库里面就会新增一条数据

查看数据库hello_test会新增数据

django交流QQ群:779429633

关于python测试开发django-83.Dockerfile部署django项目python docker部署的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于django开发-在Docker中部署django项目、python3.8+django2+celery5.2.7环境准备(python测试开发django)、python测试开发django-1.开始hello world!、python测试开发django-10.django连接mysql等相关知识的信息别忘了在本站进行查找喔。

本文标签: