我正在ubuntu中使用python学习Rest-API。我想使用SQLAlchemy将数据存储到SQLite数据库中。 这是我的密码
BookModel.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import json
from settings import app
db=SQLAlchemy(app)
class Book(db.Model):
__tablename__='books'
我该怎么办?
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(80),nullable=False)
price = db.Column(db.Float,nullable=False)
isbn =db.Column(db.Integer)
def add_book(_name,_price,_isbn):
new_book=Book(name=_name,price=_price,isbn=_isbn)
db.Session.add(new_book)
db.Session.commit()
def get_all_books(self):
return Book.query.all()
def __repr__(self):
book_object = {'name':self.name,
'price':self.price,
'isbn':self.isbn}
return json.dump(book_object)
settings.py
import os
from flask import Flask
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///' + os.path.join(basedir, 'app.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
我使用python中的波纹管命令创建数据库,并且可以正常工作。
>>> from BookModel import db
>>> db.create_all()
接下来,我使用以下命令测试add_book()方法。
>>> from BookModel import *
>>> Book.add_book("ss",55.6,556)
但是PyCharm向我显示以下错误。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/momo/Projects/flask_rest_aPI /BookModel.py", line 18, in add_book
db.Session.add(new_book)
TypeError: add() missing 1 required positional argument: 'instance'
答案 0 :(得分:0)
Route::redirect('/', '/en');
Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
Route::get('email/verify/{id}/{hash}', 'Auth\VerificationController@verify')->name('verification.verify');
Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
Route::group([
"prefix" => '{language}',
'where' => ['language' => '(en||bg)'],
], function () {
//Auth routes
Auth::routes();
//Returns to home
Route::get('/', 'HomeController@index')->name('home');
//Handles the faq routes
Route::resource('faq', 'FaqController');
});
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset')->name('password.update');
});
必须小写。
尝试
db.session
答案 1 :(得分:0)
在您的BookModel
中:
您拥有的功能add_book
:
db.Session.add(new_book)
db.Session.commit()
应为:
db.session.add(new_book)
db.session.commit()
并且add_book
和get_all_books
函数应该是classmethod
:
@classmethod
def add_book(cls, _name, _price, _isbn):
new_book=cls(name=_name,price=_price,isbn=_isbn)
db.session.add(new_book)
db.session.commit()
@classmethod
def get_all_books(cls):
return cls.query.all()