SQLAlchemy Part 2
IDE git weirdness, this goes with the previous commit for setting up SQLAlchemy.
This commit is contained in:
33
database.py
Normal file
33
database.py
Normal file
@@ -0,0 +1,33 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Barbican Models
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The models for the Barbican application.
|
||||
|
||||
DO NOT USE THIS IN PRODUCTION. IT IS NOT SECURE IN ANY WAY.
|
||||
YOU HAVE BEEN WARNED.
|
||||
|
||||
:copyright: (c) 2013 by Jarret Raim
|
||||
:license: Apache 2.0, see LICENSE for details
|
||||
"""
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
engine = create_engine('sqlite:////tmp/barbican.db', convert_unicode=True)
|
||||
db_session = scoped_session(sessionmaker(autocommit=False,
|
||||
autoflush=False,
|
||||
bind=engine))
|
||||
Base = declarative_base()
|
||||
Base.query = db_session.query_property()
|
||||
|
||||
|
||||
def init_db():
|
||||
# import all modules here that might define models so that
|
||||
# they will be registered properly on the metadata. Otherwise
|
||||
# you will have to import them first before calling init_db()
|
||||
import models
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db_session.add(models.User('admin', 'admin@localhost'))
|
||||
db_session.commit()
|
26
models.py
Normal file
26
models.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Barbican Models
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The models for Barbican.
|
||||
|
||||
:copyright: (c) 2013 by Jarret Raim
|
||||
:license: Apache 2.0, see LICENSE for details
|
||||
"""
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = 'users'
|
||||
id = Column(Integer, primary_key=True)
|
||||
name = Column(String(50), unique=True)
|
||||
email = Column(String(120), unique=True)
|
||||
|
||||
def __init__(self, name=None, email=None):
|
||||
self.name = name
|
||||
self.email = email
|
||||
|
||||
def __repr__(self):
|
||||
return '<User %r>' % self.name
|
12
templates/users.html
Normal file
12
templates/users.html
Normal file
@@ -0,0 +1,12 @@
|
||||
{% extends "layout.html" %}
|
||||
|
||||
{% block body %}
|
||||
<h1>Users</h1>
|
||||
<ul>
|
||||
{% for user in users %}
|
||||
<li>{{ user.name }}</li>
|
||||
{% else %}
|
||||
<li><em>No users yet.</em></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endblock %}
|
Reference in New Issue
Block a user