【问题标题】:Error: __init__() takes 1 positional argument but 7 were given错误:__init__() 采用 1 个位置参数,但给出了 7 个
【发布时间】:2020-10-10 10:58:11
【问题描述】:

您好,我是一名新程序员,最近开始使用烧瓶制作网站。我最近开始用烧瓶制作一个迷你 YouTube,但我的数据库有这个问题。当我在数据库中创建一个新条目时,它给了我这个错误:“错误:init() 采用 1 个位置参数,但给出了 7 个”

from flask import Flask, redirect, url_for, render_template, session, request
from flask_restful import Api, Resource, reqparse, abort, fields, marshal_with
from flask_sqlalchemy import SQLAlchemy
from app import *

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class ChannelDB(db.Model):
    id = db.Column(db.Integer, nullable=True)
    name = db.Column(db.String(100), primary_key=True)
    email = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(100), nullable=False)
    subs = db.Column(db.Integer, nullable=False)
    num_of_videos = db.Column(db.Integer, nullable=False)

channel_fields = {
    "id": fields.Integer,
    "name": fields.String,
    "email": fields.String,
    "password": fields.String,
    "subs": fields.Integer,
    "num_of_videos": fields.Integer
}

@app.route("/")
@app.route("/home")
def home():
    return render_template("home.html")

@app.route("/login")
def login():
    return render_template("login.html")

@app.route("/create_acc", methods=["POST", "GET"])
def create_acc():
    if request.method == "POST":
        name = request.form["nm"]

        check = ChannelDB.query.filter_by(name=name).first()

        if not check:
            email = request.form["em"]
            psw = request.form["ps"]

            channel = ChannelDB(0, name, email, psw, 0, 0)
            db.session.add(channel)
            db.session.commit()

            return redirect(url_for("user"))
        else:
            abort(409, message="Video alredy exists")

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

这是我的 .py 文件中的代码

{% extends "base.html" %}

{% block title %}Login Page{% endblock %}

{% block content %}
    <form action="/create_acc", method="post">
        <p>Name: </p>
        <p><input type="text" name="nm"></p>
        <p>Email: </p>
        <p><input type="text" name="em"></p>
        <p>Password: </p>
        <p><input type="text" name="ps"></p>
        <p>Press this button when you fill the spots above</p>
        <p><input type="submit" value="submit"></p>
    </form>
{% endblock %}

这是我的 login.html 文件,以防万一。

谁能帮帮我?

【问题讨论】:

  • 我看不出您是否在代码中的任何位置定义了 def init。所以也许这就是为什么它为 __init__(constructor) 采用默认的 1 位置参数

标签: python flask flask-sqlalchemy


【解决方案1】:

__init__ 需要 关键字参数 而不是 位置参数。不同之处在于在值前面加上字段名称:

channel = ChannelDB(id=0, name=name, email=email, password=psw, subs=0, num_of_videos=0)

还有一些提示:

  • 不要使用first() 来检查记录是否存在,而是使用.exists()。它会导致更快的查询,Python 不必将响应解析为 Channel 对象,并且您将使用更少的带宽,因为数据库不发送记录,它只发送 True 或 False;
  • 查看column defaults。当然,一个新频道总是有 0 个订阅者,如果您添加默认值,则不必指定。视频数量相同;
  • 通常不需要指定主键,因为数据库只是为您从 1 开始计数。显式指定它实际上会导致问题,因为大多数数据库都保留一个单独的运行计数器,然后该计数器就会不同步。

【讨论】:

    【解决方案2】:

    您的 channelDB 类缺少 init() 方法。 我在下面修改了它

    class ChannelDB(db.Model):
        def __init__(self, id, name, email, password, subs, num_of_videos): #newly added line
            id = db.Column(db.Integer, nullable=True)
            name = db.Column(db.String(100), primary_key=True)
            email = db.Column(db.String(100), nullable=False)
            password = db.Column(db.String(100), nullable=False)
            subs = db.Column(db.Integer, nullable=False)
            num_of_videos = db.Column(db.Integer, nullable=False)
    

    【讨论】:

      【解决方案3】:

      您的 ChannelDB 没有 init 方法来获取您传入的所有参数。

      要么创建一个 init 方法,要么直接将值设置为实例的属性。比如channel.name = "some name"等等。

      【讨论】:

      • Flask-SQLAlchemy 提供了一个默认的__init__ 方法
      • 感谢您的反馈。虽然您的解决方案更可取,但我的方案也适用。
      • 实际上,对于我的上一个项目,我创建了一个自定义 init 以处理默认值。
      • 是的,它绝对有用。当我想预先进行一些数据转换时,我也会使用它们
      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 2022-10-06
      • 2023-03-15
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多