欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手把手教你在win10系统下搭建python3_django_mysql的环境配置

程序员文章站 2022-07-04 16:03:32
...

要想搭建上述环境,大方向来说分为四步:

  1. 安装python3
  2. 安装django
  3. 安装mysql
  4. 配置mysql与django连接

一、安装python3

1.去python的官网下载最新版本的python
https://www.python.org/downloads 
2.一路默认配置安装就好
3.在dos窗口输入python,如果返回如下,则证明已经安装成功。

手把手教你在win10系统下搭建python3_django_mysql的环境配置

返回版本信息等内容

二、安装django

方法一:在dos下输入pip install django ,一段时间后即可安装成功(推荐)

方法二:
1、https://www.djangoproject.com/download/  下载 Django-2.0.3.tar.gz/ 
2、解压并和Python安装目录放在同一个根目录,cmd下进入 Django 目录,执行python setup.py install,然后开始安装,Django将会被安装到Python的Lib下site-packages。
3、将django安装后的目录添加环境变量,比如C:\Python36\Lib\site-packages\Django-2.0.2-py3.6.egg\django

测试:

1.输入python
2.输入import django
3.输入django.get_version(),如下图就说明成功了

手把手教你在win10系统下搭建python3_django_mysql的环境配置

三、安装mysql

因为之前在搭建网站的时候已将安装过了mysql,重复安装的话会出现很多问题,甚至导致mysql数据库的错误,我物理机上用的是phpstudy。但是我这phpstudy自带的mysql版本是5.5.53,版本较低,与django2.2在连接的时候会存在很多的问题,在这里,重新在虚拟机里安装一个版本较高的mysql数据库。

手把手教你在win10系统下搭建python3_django_mysql的环境配置

phpstudy环境中的mysql

安装mysql数据库:
环境:
python3
win10

首先,需要下载一个mysql数据库。网址:https://www.mysql.com/downloads/
选择一个版本的mysql下载,建议选择mysql5.5以上的,之前自己装的时候发现django与5.5版本mysql存在很多不兼容的错误,需要自己修改源码,现在最新的mysql是8.0版本的,下载后一路next,中间需要设置一些端口以及数据库的密码。

四、配置mysql与django进行连接

django 连接mysql默认驱动是MySQLdb,MySQLdb没有支持python3的版本,如果使用python3.x版本时,用pymysql替换MySQLdb,或者用mysqlclient替换MySQLdb。

1.首先安装pymysql: pip install pymysql

手把手教你在win10系统下搭建python3_django_mysql的环境配置

2.然后新建文件夹(用于将来放项目文件),cd进去,创建django项目:django-admin startproject helloword

手把手教你在win10系统下搭建python3_django_mysql的环境配置

进入新建的文件夹

手把手教你在win10系统下搭建python3_django_mysql的环境配置

创建了一个项目

手把手教你在win10系统下搭建python3_django_mysql的环境配置

查看确认一下,的确已经建好了

坑:
这一步在虚拟机中演示一个坑点,因为咱们是用pip安装的django,网上很多的教程说是使用命令django-admin.py startproject HelloWorld

Type 'django-admin.py 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.).
这就报错了,如果出现这种错误的话,修改命令,也就是去掉后面的.py

3.进入helloworld文件夹下,找到__init__.py,加入下面指令即可:

import pymysql
pymysql.install_as_MySQLdb()
#打开数据库连接
db = pymysql.connect("127.0.0.1","root","yourpassword","csvt")

#使用cursor()方法获取操作游标
cursor = db.cursor()

#使用方法执行sql语句
cursor.execute("SELECT VERSION()")

#使用fetchone()方法获取一条数据库
data = cursor.fetchone()

print("Database version : %s" % data)

#关闭数据连接
db.close

手把手教你在win10系统下搭建python3_django_mysql的环境配置

4.同目录下编辑setting.py,将其中的databases改为如下:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'csvt',
        'USER':'root',
        'PASSWORD':'******',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    }
}

手把手教你在win10系统下搭建python3_django_mysql的环境配置

NAME: 指定的数据库名,如果是sqlite的话,就需要填数据库文件的绝对置  
USER: 数据库登录的用户名,mysql一般都是root  
PASSWORD:登录数据库的密码,必须是USER用户所对应的密码  
HOST: 由于一般的数据库都是C/S结构的,所以得指定数据库服务器的位置,我们一般数据库服务器和客户端都是在一台主机上面,所以一般默认都填127.0.0.1  PORT:数据库服务器端口,mysql默认为3306  
HOST和PORT都可以不填,使用默认的配置,但是如果你有更改默认配置的话,就需要填入更改后的。

5.切换到上级目录并输入命令:
创建app:manage startapp testapp 有的命令是python manage.py startapp testapp 具体原因和上边一样。

报错了:大体意思就是版本问题balabala~~

Database version : 8.0.15
Traceback (most recent call last):
  File "D:\test\HelloWorld\manage.py", line 21, in <module>
    main()
  File "D:\test\HelloWorld\manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    django.setup()
  File "C:\Python37\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Python37\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "C:\Python37\lib\site-packages\django\apps\config.py", line 211, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Python37\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Python37\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Python37\lib\site-packages\django\db\models\base.py", line 117, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "C:\Python37\lib\site-packages\django\db\models\base.py", line 321, in add_to_class
    value.contribute_to_class(cls, name)
  File "C:\Python37\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "C:\Python37\lib\site-packages\django\db\__init__.py", line 28, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "C:\Python37\lib\site-packages\django\db\utils.py", line 201, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "C:\Python37\lib\site-packages\django\db\utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "C:\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 36, in <module>
    raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决方案:
找到Python安装路径下的C:\Python37\Lib\site-packages\django\db\backends\mysql\base.py文件将文件中的如下代码注释
if version < (1, 3, 3): raise ImproperlyConfigured("mysqlclient 1.3.3 or newer is required; you have %s" % Database.version)
路径根据自己的实际情况来改

手把手教你在win10系统下搭建python3_django_mysql的环境配置

注释

我们可以看到已经成功创建好了

手把手教你在win10系统下搭建python3_django_mysql的环境配置

成功创建

6. 编辑setting.py,在INSTALLED_APPS里添加刚创建的app名字,eg:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HelloWorld'

手把手教你在win10系统下搭建python3_django_mysql的环境配置

添加自己创建的APP

7.cmd 里manage.py同级目录下输入 :
python manage.py makemigrations

报错:

D:\test\HelloWorld+>python manage.py makemigrations
Database version : 8.0.15
Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Python37\lib\site-packages\django\core\management\commands\makemigrations.py", line 101, in handle
    loader.check_consistent_history(connection)
  File "C:\Python37\lib\site-packages\django\db\migrations\loader.py", line 283, in check_consistent_history
    applied = recorder.applied_migrations()
  File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations
    if self.has_table():
  File "C:\Python37\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor
    return self._cursor()
  File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor
    self.ensure_connection()
  File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection
    self.connect()
  File "C:\Python37\lib\site-packages\django\db\backends\base\base.py", line 197, in connect
    self.init_connection_state()
  File "C:\Python37\lib\site-packages\django\db\backends\mysql\base.py", line 231, in init_connection_state
    if self.features.is_sql_auto_is_null_enabled:
  File "C:\Python37\lib\site-packages\django\utils\functional.py", line 80, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python37\lib\site-packages\django\db\backends\mysql\features.py", line 82, in is_sql_auto_is_null_enabled
    cursor.execute('SELECT @@SQL_AUTO_IS_NULL')
  File "C:\Python37\lib\site-packages\django\db\backends\utils.py", line 103, in execute
    sql = self.db.ops.last_executed_query(self.cursor, sql, params)
  File "C:\Python37\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
    query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

解决方法:

File "C:\Python37\lib\site-packages\django\db\backends\mysql\operations.py", line 146, in last_executed_query
query = query.decode(errors='replace')
AttributeError: 'str' object has no attribute 'decode'

打开此文件把146行的decode修改为encode

7. cmd里manage.py同级目录下输入 
python manage.py makemigrations

报错:

No changes detected

解决方法:
 

1.在settings.py 下的 INSTALLED_APPS 插入blog 
2.在testapp下的models.py 添加模型 
例如:
class HelloWord_Model(models.Model):
name = models.CharField(db_column='name', max_length=200, blank=True, verbose_name='name')
class Meta:
db_table = 'HelloWord' # 定义了table的名字
再执行 python manage.py makemigrtions HelloWord

如果还不行的话试一试这个方法:
直接使用python manage.py migrate.

手把手教你在win10系统下搭建python3_django_mysql的环境配置

如上图所示,我们已经成功的把django与mysql数据库连接起来了,在数据库中看一下,表是不是已经成功创建了

手把手教你在win10系统下搭建python3_django_mysql的环境配置

成功!

到现在为止,已经成功的搭建好环境并且连接上了mysql的数据库。