无法从Flask连接到sqlite数据库

时间:2020-02-07 07:10:58

标签: python sqlite flask sqlalchemy flask-sqlalchemy

我正在尝试将用户名作为表单的输入,并将其添加到sqlite数据库。但是我无法连接到sqlite。我正在使用FLASK。 我的代码如下:

config.py

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    # ...
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')
                                # os.environ.get('DATABASE_URL') or \
    SQLALCHEMY_TRACK_MODIFICATIONS = False

初始化 .py

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import  models

models.py

from app import db
from sqlalchemy.orm import column_property
import datetime

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    Username = db.Column(db.String(128), nullable=True)

    def __repr__(self):
        return '<User {}>'.format(self.username)

login.html

{% extends 'layouts.html' %}
{% block title %}Loimg{% endblock %}

{% block content %}
<p>Welcome back, {{ username }}!</p>
        <h1>Tell us your name!!!</h1>
        <div class="login">
            <form action="{{url_for('login')}}" method="post">
                <span class = "text">Your Name </span> <input class="uname" id = "username" type="text" name="username">  <br/><br><br>        
                <div class="msg">{{msg}}</div>
                <input class = "button"  type="submit"  value="Submit" />
            </form>
        </div>       
{% endblock %}

main.py

from flask import *
from flask_sqlalchemy import SQLAlchemy  
from config import Config
from app import db
from app.models import User, FileDetails, UserFileMapping

app = Flask(__name__) 
app.config['SECRET_KEY'] = "random string"

@app.route('/')
def hello():
    return "Hello world"

@app.route('/login',methods = ['GET','POST'])
def login():

    if request.method =='POST' and 'username' in request.form:
        username = request.form['username']
        try:
            newUser = User(Username=username) 
            db.session.add(newUser)
            # return "session started"
            if db.session.commit():
                return ("added user")

        except:
            return "cant add"
        # return redirect(url_for('upload')
    return render_template ("login.html")
if __name__ == '__main__':  
    app.run(debug = True)  

最初我跑了

flask db init
flask db migrate
flask db upgrade

它正在捕获异常并打印“无法添加”。我不知道为什么db.session.add(Username = username)无法正常工作。

错误: enter image description here 任何帮助都会很棒。谢谢

0 个答案:

没有答案