ubuntu16.04下virtualenv环境中, django与mysql安装

来源:互联网 发布:java分布式集群框架 编辑:程序博客网 时间:2024/05/22 04:35

1 安装virtualenv

zhai@zhai:~$ pip listThe program 'pip' is currently not installed. You can install it by typing:sudo apt install python-pipzhai@zhai:~$ sudo apt install python-pip...

You are using pip version 8.1.1, however version 8.1.2 is available.You should consider upgrading via the 'pip install --upgrade pip' command.zhai@zhai:~$ pip install --upgrade pipCollecting pip  Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB)    100% |████████████████████████████████| 1.2MB 18kB/s Installing collected packages: pipSuccessfully installed pip-8.1.2

zhai@zhai:~$ sudo apt install virtualenvsudo: unable to resolve host zhaiReading package lists... DoneBuilding dependency tree       Reading state information... Done

zhai@zhai:~$ which virtualenv/usr/bin/virtualenvzhai@zhai:~$ mkdir venvszhai@zhai:~$ virtualenv venvsRunning virtualenv with interpreter /usr/bin/python2New python executable in /home/zhai/venvs/bin/python2Also creating executable in /home/zhai/venvs/bin/pythonInstalling setuptools, pkg_resources, pip, wheel...done.zhai@zhai:~$ ls venvs/bin  include  lib  local  pip-selfcheck.json  sharezhai@zhai:~$ pip listadium-theme-ubuntu (0.3.4)pip (8.1.2)setuptools (20.7.0)unity-lens-photos (1.0)virtualenv (15.0.2)wheel (0.29.0)zhai@zhai:~$ cd venvs/zhai@zhai:~/venvs$ lsbin  include  lib  local  pip-selfcheck.json  sharezhai@zhai:~/venvs$ . bin/activate(venvs) zhai@zhai:~/venvs$ pythonPython 2.7.11+ (default, Apr 17 2016, 14:00:29) [GCC 5.3.1 20160413] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import djangoTraceback (most recent call last):  File "<stdin>", line 1, in <module>ImportError: No module named django>>> (venvs) zhai@zhai:~/venvs$ pip install djangoCollecting django  Downloading Django-1.9.7-py2.py3-none-any.whl (6.6MB)    100% |████████████████████████████████| 6.6MB 20kB/s Installing collected packages: djangoSuccessfully installed django-1.9.7

检查python版本及django版本

(venvs) zhai@zhai:~/venvs$ which python/home/zhai/venvs/bin/python(venvs) zhai@zhai:~/venvs$ pythonPython 2.7.11+ (default, Apr 17 2016, 14:00:29) [GCC 5.3.1 20160413] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import django>>> django.VERSION(1, 9, 7, 'final', 0)>>> django.get_version()'1.9.7'>>> 


2 创建django工程项目

要创建一个Django项目非常简单,使用startproject命令,输入项目名称:

django-admin.py startproject mysite

Django会在当前目录下自动生成一个名为mysite的文件夹,里面有以下文件:

├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

创建项目后,进入项目文件夹,启动Django自带的web服务器:

python manage.py runserver
(django1.9) zhai@zhai:~/django1.9/mysite$ python manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.June 15, 2016 - 06:51:33Django version 1.9.7, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

访问http://127.0.0.1:8000,如果顺利显示,说明Django已经可以正常使用了。但现在只有本机可以访问,要让外网能够访问,或是要更换默认的8000端口,可以执行命令:

python manage.py runserver 0.0.0.0:8080

这样就将端口修改为8080,且外网也可以通过IP访问本机上的Django。



3 安装mysql-server

3.1 安装mysql-server与mysql-client

zhai@zhai:~$ sudo apt-get install mysql-server

zhai@zhai:~$ mysql -u root -pEnter password: Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 9Server version: 5.7.12-0ubuntu1 (Ubuntu)Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> ^C^Cmysql> ^DBye

3.2 安装libmysqld-dev包

在虚拟运行环境下直接安装

sudo apt-get install libmysqld-dev

(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ apt-cache search mysql |grep devellibmysqlclient-dev - MySQL database development fileslibmysqld-dev - MySQL embedded database development filesgambas3 - Complete visual development environment for Gambaslibapophenia2-dev - Apophenia Statistical C Library -- development packagelibapq4-dev - Pluggable Ada 95 Binding to various database systems (development)libcppdb-dev - SQL Connectivity Library (development files)libmysql++-dev - MySQL C++ library bindings (development)libmysql-ocaml-dev - OCaml bindings for MySql (development package)libmysqlcppconn-dev - MySQL Connector for C++ (development files)libodb-mysql-dev - ODB Runtime Library for MySQL (development)libsqlclient-dev - SQL client library for GNUstep (development files)libtango8-dev - TANGO distributed control system - development librarylibterralib-dev - C++ library for Geographical Information Systems -- development packagelibwtdbomysql-dev - MySQL/MariaDB backend for Wt::Dbo [development]lua-dbi-mysql-dev - DBI library for the Lua language, MySQL development fileslua-sql-mysql-dev - luasql development files for the Lua languagemonodevelop-database - Database plugin for MonoDeveloptora - graphical toolkit for database developers and administratorstora-dbg - graphical toolkit for database developers and administrators - debugging symbols(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ sudo apt-get install libmysqlclient-dev[sudo] password for zhai: Reading package lists... DoneBuilding dependency tree       Reading state information... DoneThe following additional packages will be installed:  zlib1g-devThe following NEW packages will be installed:  libmysqlclient-dev zlib1g-dev0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.Need to get 1,325 kB of archives.After this operation, 7,470 kB of additional disk space will be used.Do you want to continue? [Y/n] yGet:1 http://cn.archive.ubuntu.com/ubuntu xenial/main amd64 zlib1g-dev amd64 1:1.2.8.dfsg-2ubuntu4 [168 kB]Get:2 http://security.ubuntu.com/ubuntu xenial-security/main amd64 libmysqlclient-dev amd64 5.7.12-0ubuntu1 [1,158 kB]Fetched 1,325 kB in 1s (666 kB/s)                      Selecting previously unselected package zlib1g-dev:amd64.(Reading database ... 241961 files and directories currently installed.)Preparing to unpack .../zlib1g-dev_1%3a1.2.8.dfsg-2ubuntu4_amd64.deb ...Unpacking zlib1g-dev:amd64 (1:1.2.8.dfsg-2ubuntu4) ...Selecting previously unselected package libmysqlclient-dev.Preparing to unpack .../libmysqlclient-dev_5.7.12-0ubuntu1_amd64.deb ...Unpacking libmysqlclient-dev (5.7.12-0ubuntu1) ...Processing triggers for man-db (2.7.5-1) ...Setting up zlib1g-dev:amd64 (1:1.2.8.dfsg-2ubuntu4) ...Setting up libmysqlclient-dev (5.7.12-0ubuntu1) ...

如果不安装这个包,在安装下面的mysql-python包的过程中会出现“mysql_config not found”错误。

3.3 安装mysql-python包

在虚拟运行环境下直接安装
Django(Python)操作MySQL依赖第三方包,所以要先安装mysql-python包。 pypi网址:https://pypi.python.org/pypi/MySQL-python

命令:

pip install mysql-python
过程:

(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ pip install mysql-pythonCollecting mysql-python  Using cached MySQL-python-1.2.5.zipBuilding wheels for collected packages: mysql-python  Running setup.py bdist_wheel for mysql-python ... done  Stored in directory: /home/zhai/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62Successfully built mysql-pythonInstalling collected packages: mysql-pythonSuccessfully installed mysql-python-1.2.5


3.4 新建数据库

库名要与下面配置Django中settings.py里面的DATABASES里面的数据库名一致

MariaDB [(none)]> create database mysite;Query OK, 1 row affected (0.00 sec)MariaDB [(none)]> show databases;+--------------------+| Database           |+--------------------+| information_schema || mysite             || mysql              || performance_schema |+--------------------+4 rows in set (0.00 sec)MariaDB [(none)]> use mysite;Database changedMariaDB [mysite]> show tables;Empty set (0.00 sec)

执行命令 GRANT ALL PRIVILEGES ON mysite.* TO zhai@localhost IDENTIFIED BY '*******' WITH GRANT OPTION;

MariaDB [(none)]> GRANT ALL PRIVILEGES ON mysite.* TO root@localhost IDENTIFIED BY '123456' WITH GRANT OPTION; Query OK, 0 rows affected (0.00 sec)MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO zhai@localhost IDENTIFIED BY '123456' WITH GRANT OPTION;Query OK, 0 rows affected (0.00 sec)MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY '123456' WITH GRANT OPTION;Query OK, 0 rows affected (0.00 sec)MariaDB [(none)]> exitBye

如果不执行上面的grant命令可能出现错误:

(django1.9) zhai@zhai:~/django1.9/mysite$ mysql -uroot -pEnter password: ERROR 1698 (28000): Access denied for user 'root'@'localhost'

3.5 数据库操作

创建数据库: CREATE DATABASE <dbname> CHARACTER SET utf8;
这可以确保所有表和列默认使用UTF-8。

查看mysql数据库的端口号

MariaDB [(none)]> show global variables like 'port';+---------------+-------+| Variable_name | Value |+---------------+-------+| port          | 3306  |+---------------+-------+1 row in set (0.00 sec)
查看有哪些数据库:show databases;

查看mysql数据库所有用户:select distinct concat('user:''',user,'''@''',host,''';') as query from mysql.user

MariaDB [(none)]> select distinct concat('user:''',user,'''@''',host,''';') as query from mysql.user    -> ;+--------------------------+| query                    |+--------------------------+| user:'root'@'localhost'; || user:'zhai'@'localhost'; |+--------------------------+2 rows in set (0.00 sec)
MariaDB [mysql]> select * from user;

查看某个数据库中所有的表: show tables;

mysql语法总结:http://www.cnblogs.com/hongten/archive/2013/05/23/hongten_mysql_5_5.html

3.6 mysql相关

文件结构

MySQL配置文件:/etc/mysql/my.cnf ,其中指定了数据文件存放路径

datadir         = /var/lib/mysql

如果你创建了一个名为 test 的数据库,那么这个数据库的数据会存放到 /var/lib/mysql/test 目录下。

进入MySQL

mysql -u root -p 

(输入mysql的root密码)

qii@ubuntu:~$ mysql -u root -p
Enter password: Welcome to the MySQL monitor.  Commands end with ; or \g.Your MySQL connection id is 37Server version: 5.1.41-3ubuntu12.3 (Ubuntu)Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> 

修改 MySQL 的管理员密码:

sudo mysqladmin -u root password newpassword;

简单的操作

显示数据库:

mysql> show databases;
+--------------------+| Database           |+--------------------+| information_schema || mysql              |+--------------------+2 rows in set (0.00 sec)

设置远程访问

1.取消本地监听
正常情况下,mysql占用的3306端口只是在IP 127.0.0.1上监听,拒绝了其他IP的访问(通过netstat可以查看到)。取消本地监听需要修改 my.cnf 文件:

sudo vim /etc/mysql/my.cnf//找到如下内容,并注释bind-address = 127.0.0.1

然后需要重启 mysql (可最后再重启)。

2.授权法

mysql>GRANT ALL PRIVILEGES ON *.* TO <user>@"%" IDENTIFIED BY '<password>' WITH GRANT OPTION;mysql>FLUSH PRIVILEGES

第二句表示从mysql数据库的grant表中重新加载权限数据。因为MySQL把权限都放在了cache中,所以在做完更改后需要重新加载。

参考:http://wiki.ubuntu.com.cn/MySQL

4 让Django支持Mysql数据库

4.1 要让Django支持Mysql数据库,我们需要改一下配置文件settings.py(mysite/mysite目录下面)。

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'mysite',        'USER': 'root',        'PASSWORD': '123456',        'HOST': '',        'PORT': '',    }}

此配置详细说明请参考:http://python.usyiyi.cn/django/ref/settings.html#messages


如果NAME指定的数据库没有创建,在启动python manage.py runserver命令后,会出现错误:

django.db.utils.OperationalError: (1049, "Unknown database 'mysite'")


4.2 测试一下mysql数据库配置是否成功

引入一下看看是否会出现错误,如果没有出现错误,说明配置成功。

(django1.9) zhai@zhai:~/django1.9/mysite$ python manage.py shellPython 2.7.11+ (default, Apr 17 2016, 14:00:29) [GCC 5.3.1 20160413] on linux2Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>> from django.db import connection>>> cursor=connection.cursor()>>> 

4.3 数据库迁移

运行python manage.py runserver后没有做迁移

(django1.9) zhai@zhai:~/django1.9/mysite$ python manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.June 15, 2016 - 06:51:33Django version 1.9.7, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

在浏览器上,输入:http://127.0.0.1:8000/admin/,出现错误:

ProgrammingError at /admin/(1146, "Table 'mysite.django_session' doesn't exist")

做迁移后访问url正常:

(django1.9) zhai@zhai:~/django1.9/mysite$ ./manage.py migrateOperations to perform:  Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations:  Rendering model states... DONE  Applying contenttypes.0001_initial... OK  Applying auth.0001_initial... OK  Applying admin.0001_initial... OK  Applying admin.0002_logentry_remove_auto_add... 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 polls.0001_initial... OK  Applying sessions.0001_initial... OK

迁移前后:

MariaDB [(none)]> use mysite;Reading table information for completion of table and column namesYou can turn off this feature to get a quicker startup with -ADatabase changedMariaDB [mysite]> show tables;+-------------------+| Tables_in_mysite  |+-------------------+| django_migrations |+-------------------+1 row in set (0.00 sec)MariaDB [mysite]> show tables;+----------------------------+| Tables_in_mysite           |+----------------------------+| auth_group                 || auth_group_permissions     || auth_permission            || auth_user                  || auth_user_groups           || auth_user_user_permissions || django_admin_log           || django_content_type        || django_migrations          || django_session             || polls_choice               || polls_question             |+----------------------------+12 rows in set (0.00 sec)



Mysql的安装与配置。

1、  Django默认的数据库是sqlite,我们可以看到项目文件夹下面有个自动生成的db.sqlite3文件。而我们是需要使用Mysql的。

2、  要让Django支持Mysql数据库,我们需要改一下配置文件settings.py(mysite/mysite目录下面)。知道DATABASES进行如下修改即可。

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 数据库名,         'USER': '用户名,        'PASSWORD': '密码',         'HOST': '127.0.0.1',        'PORT': '3306',    }}

3、  安装Mysql

1
sudo apt-get install mysql-server mysql-client
1
sudo apt-get install libmysqld-dev

在这个过程他会提示你输入root的密码并确认密码。

Django(Python)操作MySQL依赖第三方包,所以要先安装MySQL for Python

1
sudo apt-get install python-dev
1
wget https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip
1
解压MySQL-python-1.2.5.zip
1
cd MySQL-python-1.2.5/
1
sudo python setup.py install

4、  配置mysql远程访问权限(用户名密码自行修改)

?
1
2
3
GRANT ALL PRIVILEGES ON *.* TO '用户名'@'%' IDENTIFIED BY '密码' WITH GRANT OPTION;
 
FLUSH  PRIVILEGES;(配置立即生效)

 

这个时候我们还是无法远程连接Mysql,下面还得修改/etc/mysql/my.cnf文件;

将bind-address                  = 127.0.0.1中的IP地址修改为0.0.0.0

重启mysql

1
service mysql restart

OK,远程连接成功。

5、  新建数据库

新建一个数据库,名字需要续我们前面配置Django中settings.py里面的DATABASES里面的数据库名一致。

6、  再次执行python manage.py migrate

 

当我们看到新建的数据库中增加了如上所以的表,证明Mysql已经配置成功。





出现问题:

(django1.9) zhai@zhai:~/django1.9/mysite$ python manage.py runserverUnhandled exception in thread started by <function wrapper at 0x7fe6f9e98938>Traceback (most recent call last):  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper    fn(*args, **kwargs)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run    autoreload.raise_last_exception()  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception    six.reraise(*_exception)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper    fn(*args, **kwargs)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup    apps.populate(settings.INSTALLED_APPS)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate    app_config.import_models(all_models)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models    self.models_module = import_module(models_module_name)  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module    __import__(name)  File "/home/zhai/django1.9/mysite/polls/models.py", line 13, in <module>    class Question(models.Model):  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/models/base.py", line 108, in __new__    new_class.add_to_class('_meta', Options(meta, app_label))  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/models/base.py", line 307, in add_to_class    value.contribute_to_class(cls, name)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/models/options.py", line 263, in contribute_to_class    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__    return getattr(connections[DEFAULT_DB_ALIAS], item)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/utils.py", line 212, in __getitem__    backend = load_backend(db['ENGINE'])  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/utils.py", line 116, in load_backend    return import_module('%s.base' % backend_name)  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module    __import__(name)  File "/home/zhai/django1.9/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 28, in <module>    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

原因是没有安装mysql-python包

下载MySQL-python-1.2.4b4.tar.gz,安装失败

安装过程:

(django1.9) zhai@zhai:~/django1.9$ pip install mysql-python==1.2.4Collecting mysql-python==1.2.4  Downloading MySQL-python-1.2.4.zip (113kB)    100% |████████████████████████████████| 122kB 666kB/s     Complete output from command python setup.py egg_info:    Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz    Extracting in /tmp/tmpwIXYRY    Now working in /tmp/tmpwIXYRY/distribute-0.6.28    Building a Distribute egg in /tmp/pip-build-pw40wx/mysql-python    Traceback (most recent call last):      File "setup.py", line 220, in <module>        scripts = scripts,      File "/usr/lib/python2.7/distutils/core.py", line 111, in setup        _setup_distribution = dist = klass(attrs)      File "/tmp/tmpwIXYRY/distribute-0.6.28/setuptools/dist.py", line 225, in __init__        _Distribution.__init__(self,attrs)。。。     File "/home/zhai/django1.9/lib/python2.7/re.py", line 155, in sub        return _compile(pattern, flags).sub(repl, string, count)    RuntimeError: maximum recursion depth exceeded    /tmp/pip-build-pw40wx/mysql-python/distribute-0.6.28-py2.7.egg    Traceback (most recent call last):      File "<string>", line 1, in <module>      File "/tmp/pip-build-pw40wx/mysql-python/setup.py", line 7, in <module>        use_setuptools()      File "/tmp/pip-build-pw40wx/mysql-python/distribute_setup.py", line 145, in use_setuptools        return _do_download(version, download_base, to_dir, download_delay)      File "/tmp/pip-build-pw40wx/mysql-python/distribute_setup.py", line 125, in _do_download        _build_egg(egg, tarball, to_dir)      File "/tmp/pip-build-pw40wx/mysql-python/distribute_setup.py", line 116, in _build_egg        raise IOError('Could not build the egg.')    IOError: Could not build the egg.        ----------------------------------------Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-pw40wx/mysql-python/

安装:

(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ pip install mysql-pythonCollecting mysql-python  Using cached MySQL-python-1.2.5.zip    Complete output from command python setup.py egg_info:    sh: 1: mysql_config: not found    Traceback (most recent call last):      File "<string>", line 1, in <module>      File "/tmp/pip-build-SbKCKR/mysql-python/setup.py", line 17, in <module>        metadata, options = get_config()      File "/tmp/pip-build-SbKCKR/mysql-python/setup_posix.py", line 43, in get_config        libs = mysql_config("libs_r")      File "/tmp/pip-build-SbKCKR/mysql-python/setup_posix.py", line 25, in mysql_config        raise EnvironmentError("%s not found" % (mysql_config.path,))    EnvironmentError: mysql_config not found        ----------------------------------------Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-SbKCKR/mysql-python/

安装:

(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ apt-cache search mysql |grep devellibmysqlclient-dev - MySQL database development fileslibmysqld-dev - MySQL embedded database development filesgambas3 - Complete visual development environment for Gambaslibapophenia2-dev - Apophenia Statistical C Library -- development packagelibapq4-dev - Pluggable Ada 95 Binding to various database systems (development)libcppdb-dev - SQL Connectivity Library (development files)libmysql++-dev - MySQL C++ library bindings (development)libmysql-ocaml-dev - OCaml bindings for MySql (development package)libmysqlcppconn-dev - MySQL Connector for C++ (development files)libodb-mysql-dev - ODB Runtime Library for MySQL (development)libsqlclient-dev - SQL client library for GNUstep (development files)libtango8-dev - TANGO distributed control system - development librarylibterralib-dev - C++ library for Geographical Information Systems -- development packagelibwtdbomysql-dev - MySQL/MariaDB backend for Wt::Dbo [development]lua-dbi-mysql-dev - DBI library for the Lua language, MySQL development fileslua-sql-mysql-dev - luasql development files for the Lua languagemonodevelop-database - Database plugin for MonoDeveloptora - graphical toolkit for database developers and administratorstora-dbg - graphical toolkit for database developers and administrators - debugging symbols(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ sudo apt-get install libmysqlclient-dev[sudo] password for zhai: Reading package lists... DoneBuilding dependency tree       Reading state information... DoneThe following additional packages will be installed:  zlib1g-devThe following NEW packages will be installed:  libmysqlclient-dev zlib1g-dev0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.Need to get 1,325 kB of archives.After this operation, 7,470 kB of additional disk space will be used.Do you want to continue? [Y/n] yGet:1 http://cn.archive.ubuntu.com/ubuntu xenial/main amd64 zlib1g-dev amd64 1:1.2.8.dfsg-2ubuntu4 [168 kB]Get:2 http://security.ubuntu.com/ubuntu xenial-security/main amd64 libmysqlclient-dev amd64 5.7.12-0ubuntu1 [1,158 kB]Fetched 1,325 kB in 1s (666 kB/s)                      Selecting previously unselected package zlib1g-dev:amd64.(Reading database ... 241961 files and directories currently installed.)Preparing to unpack .../zlib1g-dev_1%3a1.2.8.dfsg-2ubuntu4_amd64.deb ...Unpacking zlib1g-dev:amd64 (1:1.2.8.dfsg-2ubuntu4) ...Selecting previously unselected package libmysqlclient-dev.Preparing to unpack .../libmysqlclient-dev_5.7.12-0ubuntu1_amd64.deb ...Unpacking libmysqlclient-dev (5.7.12-0ubuntu1) ...Processing triggers for man-db (2.7.5-1) ...Setting up zlib1g-dev:amd64 (1:1.2.8.dfsg-2ubuntu4) ...Setting up libmysqlclient-dev (5.7.12-0ubuntu1) ...(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ pip install mysql-pythonCollecting mysql-python  Using cached MySQL-python-1.2.5.zipBuilding wheels for collected packages: mysql-python  Running setup.py bdist_wheel for mysql-python ... done  Stored in directory: /home/zhai/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62Successfully built mysql-pythonInstalling collected packages: mysql-pythonSuccessfully installed mysql-python-1.2.5(django1.9) zhai@zhai:~/django1.9/MySQL-python-1.2.4b4$ 

安装成功后问题解决。

(django1.9) zhai@zhai:~/django1.9/mysite$ python manage.py runserverPerforming system checks...System check identified no issues (0 silenced).You have unapplied migrations; your app may not work properly until they are applied.Run 'python manage.py migrate' to apply them.June 14, 2016 - 10:18:07Django version 1.9.7, using settings 'mysite.settings'Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C.

参考:

1 mysql官方安装指导:http://dev.mysql.com/doc/mysql-apt-repo-quick-guide/en/


原文:http://dmyz.org/archives/110

Django+MySQL安装配置详解(Linux)[更新为1.8.2版]

Perface

Django是一个开源的Web应用框架,由Python写成,并于2005年7月在BSD许可证下发布。Django的主要目标是使得开发复杂的、数据库驱动的网站变得简单。Django采用MVC设计模式注重组件的重用性和“可插拔性”,敏捷开发和DRY法则(Don’t Repeat Yourself)。在Django中Python被普遍使用,甚至包括配置文件和数据模型。本文介绍Django在Linux(Ubuntu 14.04.2)+MySQL(5.5.43)环境下安装、配置的过程,包括安装、运行、添加应用的所有流程,最终建立一个可以从MySQL读取文章并显示的Django应用。文章面向刚接触Python/Django的初学者,所以安装过程都以默认环境为主,用pip可以简化安装过程。

Install

首先下载Django,得到Django-1.8.2.tar.gz,后解压并安装

$ wget https://www.djangoproject.com/m/releases/1.8/Django-1.8.2.tar.gz
$ tar xzvf Django-1.8.2.tar.gz
$ cd Django-1.8.2
$ sudo python setup.py install

如果提示缺少setuptools还要下载安装setuptools(建议提前安上,因为在安装MySQL for Python的时候也会用到)。

完成安装后,Django会拷贝django-admin.py到/usr/local/bin下,这个py文件引入了Django的管理模块。进阶安装方式可以参看virtualenv, pip

Setup

要创建一个Django项目非常简单,使用startproject命令,输入项目名称:

$ django-admin.py startproject mysite

Django会在当前目录下自动生成一个名为mysite的文件夹,里面有以下文件:

├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

以上是Django 1.4以后的目录结构(如果是1.4之前的版本,manage.py和settings.py等文件是在同一层)。站点的配置放在与项目同名的一个app里(本例中是mysite),所以下文的项目文件夹指的是mysite,注意不要和mysite/mysite文件夹混淆。

  • __init__.py:Python特性,可以是空文件,表明这个文件夹是一个可以导入的包。
  • settings.py:配置文件,本文主要修改数据库信息、模板目录、加载模块的信息。
  • url.py:URL配置文件,指定函数与URL的映射关系。
  • wsgi.py:本文中不会使用,nginx/apache+wsgi在生产环境中运行Django时使用。

创建完成后,在项目文件夹启动Django自带的web服务器。Django会自动检查配置文件中的错误,如果全部正常则顺利启动:

$ python manage.py runserver
Validating models…
Performing system checks…
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run ‘python manage.py migrate’ to apply them.

June 01, 2015 – 00:00:00
Django version 1.8.2, using settings ‘mysite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

访问http://127.0.0.1:8000,如果顺利显示,说明Django已经安装成功了。但现在只有本机可以访问,要让外网能够访问,或是要更换默认的8000端口,可以执行命令:

$ python manage.py runserver 0.0.0.0:8080

这样就将端口修改为8080,且外网也可以通过IP访问本机上的Django。

注意红字部分提示还没有执行migrate。这是1.7版本加入的数据库迁移工具,执行:

$ python manage.py migrate

可以看到Django创建了身份认证(auth)相关的表,默认是sqlite数据库,所以项目文件夹下会生成db.sqlite3这个文件。

现在要让Django支持MySQL数据库。编辑配置文件(mysite/mysite/settings.py)。找到DATABASES的配置,当前版本是在77行,默认是sqlite,把它改成MySQL:

代码的中文注释,在不指定Python文件编码的情况下会引起SyntaxError,所以不要复制这些中文注释。下文的中文注释同理。

Django(Python)操作MySQL依赖第三方包,所以要先安装MySQL for Python。

$ wget https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip
$ unzip MySQL-python-1.2.5.zip
$ sudo python setup.py install

可能会提示EnvironmentError: mysql_config not found。因为没有安装开发工具包,所以找不到mysql_config文件,执行:

$ sudo apt-get install libmysqld-dev

安装模块后再次执行migrate命令,如果相关的模块/库都正确安装,Django会创建下列表:

mysql> show tables;
+—————————-+
| Tables_in_dmyz |
+—————————-+
| auth_group
| auth_group_permissions
| auth_permission
| auth_user
| auth_user_groups
| auth_user_user_permissions
| django_admin_log
| django_content_type
| django_migrations
| django_session
+—————————-+
10 rows in set (0.00 sec)

URL

现在首页还是默认内容。Django会通过URL配置文件来查找相应的对象,URL地址使用正则表达式设置。在mysite/mysite目录下可以找到urls.py文件,它是URL配置的默认起点,修改这个文件增加首页的配置:

在mysite/mysite文件夹下新建views.py文件,内容如下:

刷新网站首页,看到已经输出了”hello, world”。

Application

上一节”hello world”的例子只是说明了URL的用法,这节才是本文重点:编写一个名为articles的应用,从MySQL数据库里读取出文章作者、标题、内容。

首先建立应用,在项目文件夹中执行:

$ python manage.py startapp articles

运行后在项目文件夹中会创建article文件夹,包含下列文件:

articles/
├── admin.py
├── __init__.py
├── migrations
  └── __init__.py
├── models.py
├── tests.py
└── views.py
  • admin.py:当前应用在Django管理界面的设置。
  • migrations:数据库迁移用文件夹,创建的migrate会存在这个文件夹里。
  • models.py:模型文件,用 Python 类来描述数据表。
  • views.py:视图文件,用来联系模型与模版,主要的业务逻辑一般都写在这里。
  • tests.py:单元测试文件。

生成应用之后,要修改配置文件,告诉Django这个应用是属于当前项目的。打开配置文件(mysite/mysite/settings.py),找到INSTALLED_APPS元组,增加articles:

然后编写模型文件(article/models.py):

Django会根据模型文件自动生成migrations来操作数据库。syncdb命令在1.9版本之前仍然可以使用,但还是建议使用migrate:

$ python manage.py makemigrations
Migrations for ‘articles’:
  0001_initial.py:
    – Create model Article
$ python manage.py migrate
Running migrations:
  Rendering model states… DONE
    Applying articles.0001_initial… OK

Django会创建名为articles_article的表,包含一个默认的主键和之前定义的字段:

mysql> show columns from articles_article;
+———+————-+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+———+————-+——+—–+———+—————-+
| id | int(11) | NO | PRI | NULL | auto_increment |
| title | varchar(64) | NO | | NULL | |
| author | varchar(32) | NO | | NULL | |
| content | longtext | NO | | NULL | |
+———+————-+——+—–+———+—————-+
4 rows in set (0.00 sec)

简单的模型就设置完成了,现在编辑应用的视图(articles/views.py)文件:

编辑之前的urls.py文件(mysite/mysite/urls.py):

现在访问http://127.0.0.1:8000/articles/,直接运行会报错TemplateDoesNotExist at 路径,因为还没有告诉Django,到哪里去找articles.html文件。

编辑配置文件(mysite/mysite/settings.py),在56行找到TEMPLATE设置,在DIRS中设置一个模版路径,这里将模版目录指定为项目文件夹下的templates:

创建templates(mysite/templates)文件夹和articles.html文件(mysite/templates/articles.html)。如果使用过其它框架或者模板引擎,下面articles.html的内容就很容易看懂了,Django在模版文件中利用相应的TAG控制传递过来的变量显示的位置:

这样所有的配置就完成了,访问 http://127.0.0.1:8000/articles,Django会自动读取数据库中的内容,并显示在网页上。可以直接在数据库中写入数据,或是在Django的shell中操作:

$ python manage.py shell
>>> from articles.models import Article
>>> Article.create(title=’Django’, author=’perchouli’, content=’Django+MySQL’)

0 0
原创粉丝点击