flask-sqlalchemy教程的开始都是创建数据库,数据表,那py文件每一次执行都会创建一次数据库数据表?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask-sqlalchemy教程的开始都是创建数据库,数据表,那py文件每一次执行都会创建一次数据库数据表?相关的知识,希望对你有一定的参考价值。

flask-sqlalchemy教程的开始都是创建数据库,数据表,那py文件每一次执行都会创建一次数据库数据表?

python3下用flask-sqlalchemy对mysql数据库操作案例:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config[\'SQLALCHEMY_DATABASE_URI\'] = \'mysql://username:password@localhost/db_name\'
db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)

def __init__(self, username, email):
self.username = username
self.email = email

def __repr__(self):
return \'<User %r>\' % self.username

admin = User(\'admin\', \'admin@example.com\')

db.create_all() # In case user table doesn\'t exists already. Else remove it.

db.session.add(admin)

db.session.commit() # This is needed to write the changes to database

User.query.all()

User.query.filter_by(username=\'admin\').first()
参考技术A 这个只是连接数据库,数据库还要自己创建才能连接上去

ModuleNotFoundError:Flask-sqlalchemy 中没有名为“MySQLdb”的模块

【中文标题】ModuleNotFoundError:Flask-sqlalchemy 中没有名为“MySQLdb”的模块【英文标题】:ModuleNotFoundError: No module named 'MySQLdb' in Flask-sqlalchemy 【发布时间】:2021-01-09 12:11:04 【问题描述】:

我是 Flask 的新手,所以我尝试使用不同的教程源将数据发送到数据库。我建立简单的博客类型网站,我的数据库服务器是http://localhost/phpmyadmin/。在我单击contact.html 上的提交按钮后。我得到了这个错误。那么我该如何解决这个错误呢。

Traceback (most recent call last):
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1020, in __call__
    return self.registry[key]
KeyError: 6528

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "F:\Flask\01\tut1.py", line 33, in contact
    db.session.add(entry)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\scoping.py", line 163, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\util\_collections.py", line 1022, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\orm\session.py", line 3286, in __call__
    return self.class_(**local_kw)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 138, in __init__
    bind = options.pop('bind', None) or db.engine
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 943, in engine
    return self.get_engine()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 962, in get_engine
    return connector.get_engine()
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 556, in get_engine
    self._engine = rv = self._sa.create_engine(sa_url, options)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_sqlalchemy\__init__.py", line 972, in create_engine
    return sqlalchemy.create_engine(sa_url, **engine_opts)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\__init__.py", line 500, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\engine\strategies.py", line 87, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Users\New Tech\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\sqlalchemy\dialects\mysql\mysqldb.py", line 118, in dbapi
    return __import__("MySQLdb")
ModuleNotFoundError: No module named 'MySQLdb'

我的代码在这里

from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from datetime  import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/blog'
db = SQLAlchemy(app)

class Contacts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(255), nullable=False)
    phone_number = db.Column(db.String(50), nullable=False)
    message = db.Column(db.String(120), nullable=False)
    date_created = db.Column(db.String(50), nullable=True )


@app.route('/contact/', methods=['GET','POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone_number = request.form.get('phone_number')
        message = request.form.get('message')
        entry = Contacts(name=name, email=email, phone_number=phone_number, message=message, date_created=datetime.now())
        db.session.add(entry)
        db.session.commit()
    return render_template('contact.html')

app.run(debug=True)

有谁知道,我是怎么得到这个错误的?

【问题讨论】:

【参考方案1】:

运行命令pip install pymysqlpip install mysqldbmodel 帮助我摆脱这个该死的(**) 错误。

编辑:

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:@localhost/blog'

我在ImportError: No module named MySQLdb找到这个解决方案

【讨论】:

【参考方案2】:

datetime.now:不返回字符串,您需要将其转换为字符串或将数据库中的类型更改为这样的日期

    date_created = db.Column(db.DateTime, nullable=True )

我用过这个,它对我很有用

from flask import Flask, render_template, request,redirect
from flask_sqlalchemy import SQLAlchemy
import sqlite3
from datetime import *

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database1.db'
db = SQLAlchemy(app)

class Contacts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(255), nullable=False)
    phone_number = db.Column(db.String(50), nullable=False)
    message = db.Column(db.String(120), nullable=False)
    date_created = db.Column(db.DateTime, nullable=True )

db.create_all()

@app.route('/contact', methods=['GET','POST'])
def contact():
    if request.method == 'POST':
        name = request.form.get('name')
        email = request.form.get('email')
        phone_number = request.form.get('phone_number')
        message = request.form.get('message')

        entry = Contacts(name="name", email="email", phone_number="phone_number", message="message", date_created=datetime.now())

    try:
        db.session.add(entry)
        db.session.commit()
        db.session.close()
        return render_template('h.html')


    except:
        return "Error"

app.run(debug=True)

你需要改变我已经改变的东西,比如 render_template

如果不行,请提供github

【讨论】:

是的,它奏效了。但是我怎样才能在数据库表上看到这些数据呢?有没有像 django has(admin/) 一样的管理 URL。如果可能的话,我想使用 MySQL 数据库。 问题解决了吗?对于我从未使用过的 mySQL,但我想您可以打开 mySQL 并查询表并检索您想要的内容 查看此链接dev.mysql.com/doc/mysql-getting-started/en 我发布了我的答案。谢谢你!!让我对 sqlite3 有所了解。我对此一无所知,因为我是 Flask 的新手。

以上是关于flask-sqlalchemy教程的开始都是创建数据库,数据表,那py文件每一次执行都会创建一次数据库数据表?的主要内容,如果未能解决你的问题,请参考以下文章

Flask-SqlAlchemy教程增删改查

在python3下怎样用flask-sqlalchemy对mysql数据库操作

在python3下怎样用flask-sqlalchemy对mysql数据库操作

Flask-Sqlalchemy 使用 postgres 创建视图

无法使用 flask-sqlalchemy 创建自动递增主键

flask-sqlalchemy