【问题标题】:Can't find __main__ when initializing my SQLite database初始化我的 SQLite 数据库时找不到 __main__
【发布时间】:2020-04-08 17:27:48
【问题描述】:

我是 Python 新手,甚至是 Flask 新手。当我尝试使用 SQLAlchemy 初始化我的数据库时,出现错误。有谁知道发生了什么以及如何解决这个问题,以便我可以运行 db.create_table() 来初始化我的数据库并测试我的 API 端点?

我输入:

python3
from app import db

错误:

* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
/Users/mark/Documents/Coding/friend_code/venv/bin/python3: can't find '__main__' module in '/Users/mark/Documents/Coding/friend_code'

这是我在 app.py 中的全部代码

import os
import secrets
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, request, jsonify
from flask_marshmallow import Marshmallow

users = []
theme = [
    {'neon red and neon blue': ('rgb(255, 60, 40)', 'rgb(10, 185, 230)')},
    {'gray': ('rgb(130, 130, 130)', 'rgb(130, 130, 130)')},
    {'blue and neon yellow': ('rgb(70, 85, 230)', 'rgb(230, 255, 0)')},
    {'neon pink and neon green': ('rgb(255, 50, 120)', 'rgb(30, 220, 0)')},
    {'neon purple and neon orange': ('rgb(180, 0, 245)', 'rgb(250, 160, 5)')},
    {'neon yellow': ('rgb(250, 160, 5)', 'rgb(250, 160, 5)')}
]

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))

# database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
    os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# initializion
db = SQLAlchemy(app)
ma = Marshmallow(app)


# user class/model
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    avatar = db.Column(db.String, default='default.jpg', nullable=False,)
    friend_code = db.Column(db.Integer, nullable=False)
    update_code = db.Column(db.String, nullable=False)
    theme = db.Column(db.String, default='neon red and neon blue')
    dark_mode = db.Column(db.Boolean, default=True, nullable=False)

    def __init__(self, username, avatar, friend_code, update_code, theme, dark_mode):
        self.username = username
        self.avatar = avatar
        self.friend_code = friend_code
        self.update_code = update_code
        self.theme = theme
        self.dark_mode = dark_mode


# user schema
class UserSchema(ma.Schema):
    # allowed visible fields
    class Meta:
        fields = ('username', 'avatar', 'friend_code',
                  'update_code', 'theme', 'dark_mode')


# initialization
user_schema = UserSchema()

# GET
@app.route('/<username>', methods=['GET'])
def get(username):
    user = User.query.get(username)
    return user_schema.jsonify(user)

# POST
@app.route('/', methods=['POST'])
def post():
    username = request.json['username']
    avatar = request.json['avatar']
    friend_code = request.json['friend_code']
    update_code = secrets.token_urlsafe(8)
    theme = request.json['theme']
    dark_mode = request.json['dark_mode']

    new_user = User(username, avatar, friend_code,
                    update_code, theme, dark_mode)

    # add to db
    db.session.add(new_user)
    db.session.commit()

    return user_schema.jsonify(new_user)


# run server
app.run(debug=True)

【问题讨论】:

标签: python flask


【解决方案1】:

你是如何调用你的代码的?如果您是直接调用,例如使用

$ python app.py

那么您需要将app.run() 命令包装在app.py 末尾的ma​​in 块内

if __name__ == "__main__":
    app.run(debug=True)

否则,如果您尝试直接调用 ,例如使用

$ python -m friend_code

那么您需要在文件夹中包含一个__main__.py 文件,该文件包含带有ma​​in 块(以及app 的导入语句)的代码块。

问题是每次您尝试从该文件导入数据库时​​都会执行您的 run server 函数调用,因为它没有使用这些 ma​​in之一进行包装> 块。

您可以从this in-depth answer 了解更多有关其工作原理的信息。

关于创建数据库表,最简单的方法是创建一个文件来为您处理,然后您可以直接运行该文件

create_db.py

if __name__ == "__main__":
    from app import db
    db.create_all()
    print("Database Created")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2012-12-15
    • 2019-11-29
    • 2017-05-11
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多