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

发布时间:2020-06-18 07:58:05 作者:今歌
来源:网络 阅读:6875

环境描述: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)
访问:

Flask报错笔记:ImportError: No module named 'MySQLdb'
执行报错:

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'

推荐阅读:
  1. 用Flask封装下Ansible提供后端API
  2. Flask如何实现异步非阻塞请求功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

flask web te

上一篇:宏和函数的区别

下一篇:所有_show parameters

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》