初始化SQLite数据库时找不到__main__

时间:2020-04-08 17:27:48

标签: python flask

我是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)

1 个答案:

答案 0 :(得分:2)

您如何调用代码?如果您是直接拨打电话,例如使用

$ python app.py

然后,您需要将app.run()命令包装在app.py末尾的 main 块中

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

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

$ python -m friend_code

然后,您需要在文件夹内包括一个__main__.py文件,该文件包含带有 main 块的代码块(以及app的import语句)

问题在于,每次您尝试从该文件导入数据库时​​,都会执行您的运行服务器函数调用,因为它没有被其中的包裹>块。

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

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

create_db.py

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