Flask报错笔记:ImportError: No module named ‘MySQLdb‘

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask报错笔记:ImportError: No module named ‘MySQLdb‘相关的知识,希望对你有一定的参考价值。

环境描述:Windows10
自己部署一个flask项目

#/usr/bin/python env
#coding:utf8
from flask_script import Manager
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask import Flask, render_template, session, redirect, url_for,flash
import os,pymysql
from flask_sqlalchemy import SQLAlchemy
pymysql.install_as_MySQLdb()
app = Flask(__name__)
app.config[‘SECRET_KEY‘] = ‘hard to guess string‘

basedir = os.path.abspath(os.path.dirname(__file__))
app.config[‘SQLALCHEMY_DATABASE_URI‘] =‘mysql://root:密码@IP:3306/school‘
app.config[‘SQLALCHEMY_COMMIT_ON_TEARDOWN‘] = True
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = False

manager = Manager(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)

class Role(db.Model):
    __tablename__ = ‘roles‘ 
    id = db.Column(db.Integer,primary_key=True)  
    name = db.Column(db.String(64),unique=True)
    user = db.relationship(‘User‘,backref=‘role‘,lazy=‘dynamic‘) 

    def __repr__(self):
        return ‘<Role {}> ‘.format(self.name)

class User(db.Model):
    __tablename__ = ‘users‘
    id = db.Column(db.Integer,primary_key=True)
    username = db.Column(db.String(64),unique=True,index=True)
    role_id = db.Column(db.Integer,db.ForeignKey(‘roles.id‘))

    def __repr__(self):
        return ‘<User {}>‘.format(self.username)

class NameForm(FlaskForm):
    name = StringField(‘What is your name?‘, validators=[Required()])
    submit = SubmitField(‘Submit‘)

@app.errorhandler(404)
def page_not_found(e):
    return render_template(‘404.html‘),404

@app.errorhandler(500)
def internal_server_error(e):
    return render_template(‘500.html‘),500

@app.route(‘/‘, methods=[‘GET‘, ‘POST‘])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get(‘name‘)
        if old_name is not None and old_name != form.name.data:
            flash(‘Looks like you have changed your name!‘)
        session[‘name‘] = form.name.data
        return redirect(url_for(‘index‘))
    return render_template(‘index.html‘,form=form,name=session.get(‘name‘),current_time=datetime.utcnow())

if __name__ == ‘__main__‘:
    app.run(debug = True,host=‘0.0.0.0‘,port=9000)
访问:

技术分享图片
执行报错:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    manager.run()
  File "C:\Python27\lib\site-packages\flask_script\__init__.py", line 412, in run
    result = self.handle(sys.argv[0], sys.argv[1:])
  File "C:\Python27\lib\site-packages\flask_script\__init__.py", line 383, in handle
    res = handle(*args, **config)
  File "C:\Python27\lib\site-packages\flask_script\commands.py", line 216, in __call__
    return self.run(*args, **kwargs)
  File "C:\Python27\lib\site-packages\flask_migrate\__init__.py", line 235, in upgrade
    command.upgrade(config, revision, sql=sql, tag=tag)
  File "C:\Python27\lib\site-packages\alembic\command.py", line 174, in upgrade
    script.run_env()
  File "C:\Python27\lib\site-packages\alembic\script\base.py", line 397, in run_env
    util.load_python_file(self.dir, ‘env.py‘)
  File "C:\Python27\lib\site-packages\alembic\util\pyfiles.py", line 93, in load_python_file
    module = load_module_py(module_id, path)
  File "C:\Python27\lib\site-packages\alembic\util\compat.py", line 79, in load_module_py
    mod = imp.load_source(module_id, path, fp)
  File "migrations\env.py", line 87, in <module>
    run_migrations_online()
  File "migrations\env.py", line 70, in run_migrations_online
    poolclass=pool.NullPool)
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\__init__.py", line 427, in engine_from_config
    return create_engine(url, **options)
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\__init__.py", line 386, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Python27\lib\site-packages\sqlalchemy\engine\strategies.py", line 75, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Python27\lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 92, in dbapi
    return __import__(‘MySQLdb‘)
ImportError: No module named MySQLdb

在网上搜索了解决方案如下:

1、安装PyMySQL
$ pip install PyMySQL
Collecting PyMySQL
Downloading PyMySQL-0.7.11-py2.py3-none-any.whl (78kB)
Installing collected packages: PyMySQL
Successfully installed PyMySQL-0.7.11

2、导入模块pymysql

import pymysql
pymysql.install_as_MySQLdb()

成功访问:http://127.0.0.1:9000
技术分享图片

以上是关于Flask报错笔记:ImportError: No module named ‘MySQLdb‘的主要内容,如果未能解决你的问题,请参考以下文章

使用烧瓶执行 hello world “ImportError: No module named flask”

Python flask-cors ImportError: No module named 'flask-cors' Raspberry pi

用pycharm+flask 建立项目以后运行出现ImportError: No module named flask-login问题

ubuntu上跑python连接pg,报错 ImportError: No module named psycopg2

解决pycharm终端/cmd运行python脚本报错“ImportError/ModuleNotFoundError:No Module named ...”

python 安装 reportlab 报错 “ImportError: No module named reportlab.lib”