【发布时间】:2022-01-02 16:23:09
【问题描述】:
执行代码后,在工作目录或主目录中找不到数据库文件(此处为test.db)。 Python-flask 代码如下所示。我在 YouTube 视频中看到,连接成功后会自动创建 .db 文件。
import os
from flask import Flask, render_template, request, redirect
from flask_sqlalchemy import SQLAlchemy
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
app = Flask(__name__)
#db_path = os.path.join(os.path.dirname(__file__), 'test.db')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///test.db' #path of the database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
#initialising the database
db=SQLAlchemy(app)
db.init_app(app)
#create database model
#we will not have to give sql commands, just can be created using class
class exec_members(db.Model):
id=db.Column(db.Integer,primary_key=True) #person id
name=db.Column(db.String(50),nullable=False) #execom member name
postn=db.Column(db.String(100),nullable=False) #position represented by the execom member
twitter=db.Column(db.String(200),nullable=False) #twitter id of the execom member
facebook=db.Column(db.String(200),nullable=False) #facebook id of the execom member
instagram=db.Column(db.String(200),nullable=False) ##instagram id of the execom member
linkedin=db.Column(db.String(200),nullable=False) #linkedin id of the execom member
#img_name=db.Column(db.String(200),nullable=False) #image of the execom member
@app.route("/admin")
def hello_world():
return render_template('admin.html')
@app.route("/",methods=['GET'])
def home():
return render_template('home.html')
@app.route("/details",methods=['POST'])
def details():
pname=request.form['name']
post=request.form['post-name']
twitterid=request.form['twitter']
facebookid=request.form['facebook']
instagramid=request.form['instagram']
linkedinid=request.form['linkedin']
try:
db.session.add(exec_members(name=pname))
db.session.add(exec_members(postn=post))
db.session.add(exec_members(twitter=twitterid))
db.session.add(exec_members(facebook=facebookid))
db.session.add(exec_members(instagram=instagramid))
db.session.add(exec_members(linkedin=linkedinid))
except:
print("Error adding to database!")
return redirect('/admin')
#########################error uploading files to the database
#print(name, post, twitter, facebook, instagram, linkedin)
另外,执行代码后没有返回错误。
【问题讨论】:
标签: python sqlite flask flask-sqlalchemy