__init __()接受1个位置参数,但给出了3个

时间:2019-07-06 19:13:03

标签: python python-2.7 flask-sqlalchemy

我正在尝试向创建的表发送发布请求,但一直收到错误 init ()接受1个位置参数,但给出了3个位置。

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)
file_path = os.path.abspath(os.getcwd())+"\database.db"

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'+file_path
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column(db.Boolean(50))
    title = db.Column(db.String(200))
    body = db.Column(db.String(max))
    createdtime = db.Column(db.DateTime())

def __init__(self, status, title, body, createdtime):
    self.status = status
    self.title= title
    self.body = body
    self.createdtime = createdtime


@app.route('/api/posts', methods=['GET'])
def get_all_posts():
    return ''

@app.route('/api/posts/<id>', methods=['GET'])
def get_one_post():
    return ''

@app.route('/api/new-post', methods=['POST'])
def put_post():
    title= request.get_json('title')
    body= request.get_json('body')

    new_post= post(title, body)
    db.session.add(new_post)
    db.session.commit()
    return jsonify({'message': 'Post created Successfully'})


@app.route('/api/delete-post', methods=['DELETE'])
def delete_post():
    return ''

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

我在做什么错了?

加上我的请求看起来像这样

{
 "title" : "Start before you are ready",
 "body": "This post will be a little different from what I'm used to 
 write. I tend to keep my articles in the technical realm of programming. 
 This time, I'll have to talk about a subject that transformed my mindset 
 lately. It will appear a little like a rant, and it very well may be :D"
}

1 个答案:

答案 0 :(得分:1)

首先,__init__方法与post类的缩进级别不同。 其次,您无需覆盖db.Model的默认构造函数,就可以使用Post模型。

例如: 像这样的post = Post(title='xx'),只要实例中使用的属性在类中,就可以在实例化Post类时向其传递尽可能多的参数。