1

I'm trying to run a Flask - SQLAlchemy application. What I want to do is add the creation datetime by default at each insert in my table usuario. So far, I have 2 files:

Here, I create Usuario class to create users with some information and add the datetime as a default value.

database_setup.py

import datetime
import os
import sys
# in the next line, i get the error: ImportError: cannot import name 'Datetime'
from sqlalchemy import Column, ForeignKey, Integer, String, Datetime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base=declarative_base()


class Usuario(Base):
    __tablename__='usuario'

    id=Column(Integer, primary_key=True)
    usuario_id=Column(String(255), nullable=False)
    password=Column(String(200), nullable=False)
    email=Column(String(255), nullable=False)
    nombres=Column(String(300), nullable=False)
    apellidos=Column(String(300), nullable=False)
    # Here, I want to set a default value for each user
    fecha_creacion=Column(Datetime, nullable=False, default=datetime.utcnow)

# String connection to mysql database
engine=create_engine('mysql://user:password@localhost/bdname')


Base.metadata.create_all(engine)

The problem comes here, when I try to run this file from the console:

python3 project.py

I got the next lines:

File "project.py", line 4, in from database_setup import Base, Usuario
File "/home/facturacion/compartido/Cambio/database_setup.py", line 4, in
from sqlalchemy import Column, ForeignKey, Integer, String, Datetime
importError: cannot import name 'Datetime'

project.py

from flask import Flask, flash, render_template, request, redirect, jsonify, url_for, session
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Usuario
import os

app = Flask(__name__)

engine = create_engine('mysql://root:facturacion@localhost/cambio')
Base.metadata.bind = engine

DBSession = sessionmaker(bind = engine)
dbsession = DBSession()

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % session['username']
    return 'Aun no se encuentra logueado'

@app.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'POST':
        usuario_frompost = request.form['username']
        pass_frompost = request.form['password']
        user = None
        if '@' in usuario_frompost:
            user = dbsession.query(Usuario).filter_by(email = usuario_frompost, password = pass_frompost)
        else:
            user = dbsession.query(Usuario).filter_by(usuario_id = usuario_frompost, password = pass_frompost)

        if user:
            flash('Login exitoso')
            session['username'] = request.form['username']
            return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=password name=password>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.debug = True
    app.secret_key = os.urandom(24)
    app.run(host = '0.0.0.0', port = 5000)

1 Answer 1

6

Very simple, just a typo:

from sqlalchemy import DateTime

DateTime not Datetime

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. You were right. But after I made the correction, it throw the error No module named 'MySQLdb'. I installed pip3 install mysqlclient and works like a charm!
To avoid these very easy to make typos, i'll often just import sqlalchemy and reference everything through sqlalchemy.Column(sqlalchemy.Datetime) etc. To save typing you can do import sqlalchemy as sqla. Not sure if there is a community standard for abbreviation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.