熬死你的 发表于 2015-4-21 11:05:05

在MAC下 Python+Django+mysql配置

  今天在搭建Django+mysql环境的时候遇到了一点问题,记录下来。
  
  安装环境:OS X 10.10操作系统,Python 2.7。
MySQLdb其实包含在MySQL-python包中,因此无论下载还是在pip中search,都应该是搜寻MySQL-python。


以下将说明MySQLdb两种常见的安装方式:

下载安装或者pip安装MySQL-python。 

源码安装

下载MySQLdb源码
下面是1.2.5的版本
https://pypi.python.org/packages/source/M/MySQL-python/MySQL-python-1.2.5.zip#md5=654f75b302db6ed8dc5a898c625e030c
下载后解压,然后在终端Terminal中执行以下命令:
$ cd MySQL-python-1.2.5
然后修改 site.cfg, 修改下面内容:
  由#mysql_config = /usr/local/bin/mysql_config
  改成mysql_config = /usr/local/mysql/bin/mysql_config
  否则会出现找不到 MySQL config 的问题:



File "/tmp/easy_install-nHSsgl/MySQL-python-1.2.2/setup_posix.py", line 24, in mysql_config
EnvironmentError: mysql_config not found

  然后修改 _mysql.c, 把第 37 到 39 行注释掉, 如下:

//#ifndef uint
//#define uint unsigned int
//#endif

  
否则会出现:



In file included from /usr/local/mysql/include/mysql.h:47,
from _mysql.c:40:
/usr/include/sys/types.h:92: error: duplicate 'unsigned'
/usr/include/sys/types.h:92: error: two or more data types in declaration specifiers
error: command 'gcc' failed with exit status 1
  然后再用 python ./setup.py build 编译



$ python ./setup.py build

  然后再用 python ./setup.py install 安装



$ sudo python ./setup.py install
Password:

使用pip安装MySQLdb

在终端中执行:$ pip install MySQL-python
使用pip安装时没有办法修改site.cfg文件,因此可以通过修改OS X的系统环境变量来解决找不到mysql_config的错误。
修改OS X环境变量:打开终端,在终端中使用vim打开“~/.bash_profile”,如果没有安装vim,那就显示隐藏文件用文本编辑器打开,具体操作这里就不复述了。在.bash_profile中添加以下内容:
PATH="/usr/local/mysql/bin:${PATH}"
export PATH
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
export VERSIONER_PYTHON_PREFER_64_BIT=no
export VERSIONER_PYTHON_PREFER_32_BIT=yes
其中 VERSIONER_PYTHON_PREFER_64_BIT和VERSIONER_PYTHON_PREFER_64_BIT根据自己安装的MySQL进行选择。
另外再提供一个pip安装时找不到mysql_config的解决方法,在终端中输入以下命令:
$ sudo ln -s /usr/local/mysql/bin/* /usr/bin
到这里,MySQL-python包应该基本顺利安装。

解决 Reason: image not found 错误
  安装完MySQL-python包后,让我们import MySQLdb,此时出现一个错误,错误最后一行写着 Reason: image not found。
  解决方法是在终端执行:
  $ sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
  $ sudo ln -s /usr/local/mysql/lib /usr/local/mysql/lib/mysql

测试
  用下面的命令进行测试:



$ cd ~
$ python
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
>>> MySQLdb.apilevel
'2.0'
>>> import django
>>> print django.VERSION
(1, 0, 'final')
常见错误

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
经网上查证:http://www.tuicool.com/articles/zI7Vzu,貌似是mac os的Xcode从5.1起给编译器规定对于未知参数传入视为error,我们需要使用ARCHFLAGS将该error降级为warning,因此最后的安装命令应该如下:

sudo ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future python setup.py build
页: [1]
查看完整版本: 在MAC下 Python+Django+mysql配置