def create_app(config=None, debug=True): app = create_base_app(config, debug) app.config[ 'SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_social_test' db = SQLAlchemy(app) roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(120)) active = db.Column(db.Boolean()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) connections = db.relationship('Connection', backref=db.backref('user', lazy='joined')) class Connection(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) provider_id = db.Column(db.String(255)) provider_user_id = db.Column(db.String(255)) access_token = db.Column(db.String(255)) secret = db.Column(db.String(255)) display_name = db.Column(db.String(255)) profile_url = db.Column(db.String(512)) image_url = db.Column(db.String(512)) rank = db.Column(db.Integer) app.security = Security(app, SQLAlchemyUserDatastore(db, User, Role)) app.social = Social(app, SQLAlchemyConnectionDatastore(db, Connection)) @app.before_first_request def before_first_request(): db.drop_all() db.create_all() populate_data() pass return app
def create_app(config, **kwargs): app = create_base_app(config) #app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_security_test' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' db = SQLAlchemy(app) roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) @app.before_first_request def before_first_request(): db.drop_all() db.create_all() populate_data(app.config.get('USER_COUNT', None)) app.security = Security(app, datastore=SQLAlchemyUserDatastore(db, User, Role), **kwargs) add_context_processors(app.security) return app
''' 图片墙 ''' class ListImage(db.Model): id = db.Column(db.Integer, primary_key=True) src = db.Column(db.String(80)) href = db.Column(db.String(128)) content = db.Column(db.String(300)) people_id = db.Column(db.Integer, db.ForeignKey('people_show.id')) blogs = db.Table( 'blogs', db.Column('blog_category_id', db.Integer, db.ForeignKey('blog_category.id')), db.Column('blog_id', db.Integer, db.ForeignKey('blog.id'))) class BlogCategory(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32)) blog = db.relationship('Blog', secondary=blogs, backref='blog_category', lazy='dynamic') def __repr__(self): return self.name
t = PlaceType(name, short_name, level) db.sesson.add(t) def __lt__(self, other): if isinstance(other, PlaceType): # Smaller level indicated higher in the hierarchy return self.level > other.level else: return False # The place_parents table stores the parent-child relation # of places. For convenience, we also store a place as parent of it self. # That makes it easier to run queries over the subtree, including that place. place_parents = db.Table( 'place_parents', db.Column('parent_id', db.Integer, db.ForeignKey('place.id'), index=True), db.Column('child_id', db.Integer, db.ForeignKey('place.id'), index=True)) class Place(db.Model, Mixable): __tablename__ = "place" id = db.Column(db.Integer, primary_key=True) key = db.Column(db.Text, nullable=False) name = db.Column(db.Text, nullable=False) type_id = db.Column(db.Integer, db.ForeignKey('place_type.id'), nullable=False) type = db.relationship('PlaceType', foreign_keys=type_id, backref=db.backref('places', lazy='dynamic'))
from sqlalchemy.orm import sessionmaker, relationship, backref db_url = '{dialect}://{user}:{passwd}@{host}:{port}/{dbname}'.format( dialect=config.get('lawdb', 'dialect'), user=config.get('lawdb', 'username'), passwd=config.get('lawdb', 'password'), host=config.get('lawdb', 'host'), port=config.get('lawdb', 'port'), dbname=config.get('lawdb', 'dbname'), ) # We'll bind the app later db = SQLAlchemy() roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime())
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask_wtf import Form from wtforms import StringField, TextAreaField from wtforms.validators import DataRequired, Length from sqlalchemy import func from config import DevConfig app = Flask(__name__) app.config.from_object(DevConfig) db = SQLAlchemy(app) tags = db.Table('post_tags', db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))) class User(db.Model): id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(255)) password = db.Column(db.String(255)) posts = db.relationship('Post', backref='user', lazy='dynamic') def __init__(self, username): self.username = username def __repr__(self): return '<User {}>'.format(self.username)
DB_NAME = 'fantalega.db' app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///%s' % DB_NAME app.config['SQLALCHEMY_ECHO'] = False db = SQLAlchemy(app) MODULI = ('3-4-3', '3-5-2', '4-3-3', '4-4-2', '4-5-1', '5-3-2', '5-4-1') migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) # M2M secondary tables leghe_squadre = db.Table( 'leghe_squadre', db.Column('lega_id', db.Integer, db.ForeignKey('lega.id')), db.Column('squadra_id', db.Integer, db.ForeignKey('squadra.id'))) punteggi_squadre = db.Table( 'punteggi_squadre', db.Column('punteggio_id', db.Integer, db.ForeignKey('punteggio.id')), db.Column('squadra_id', db.Integer, db.ForeignKey('squadra.id'))) # M2M secondary Association object class FormazioniGiocatori(db.Model): __tablename__ = 'formazioni_giocatori' giocatore_id = db.Column(db.Integer, db.ForeignKey('giocatore.id'), primary_key=True) formazione_id = db.Column(db.Integer,
from flask.ext.sqlalchemy import SQLAlchemy #from flask.ext.mongoengine import MongoEngine from flask_login import AnonymousUserMixin from webapp.extensions import bcrypt db = SQLAlchemy() #mongodb = MongoEngine() tags = db.Table('post_tags', db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))) roles = db.Table('role_users', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('role_id', db.Integer, db.ForeignKey('role.id'))) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) posts = db.relationship('Post', backref='user', lazy='dynamic') roles = db.relationship('Role', secondary=roles, backref=db.backref('users', lazy='dynamic')) def __init__(self, username): self.username = username default = Role.query.filter_by(name="default").one()
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import SQLAlchemyUserDatastore, UserMixin, RoleMixin from sqlalchemy.orm import relationship import datetime from collections import namedtuple db = SQLAlchemy() #used by ext.security roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('myuser.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) go_server_admins = db.Table( 'go_server_admin', db.Column('user_id', db.Integer, db.ForeignKey('myuser.id')), db.Column('server_id', db.Integer, db.ForeignKey('go_server.id'))) _Role = namedtuple("_Role", "name description") RATINGS_ADMIN_ROLE = _Role("ratings_admin", "Admin of AGA-Online Ratings") SERVER_ADMIN_ROLE = _Role("server_admin", "Admin of a Go Server") USER_ROLE = _Role("user", "Default role") # Define models class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255))
""" from datetime import datetime from sqlalchemy.event import listens_for from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import UserMixin import bcrypt db = SQLAlchemy() resourcecategory = db.Table( 'resourcecategory', db.Column('resource_id', db.Integer, db.ForeignKey('resource.id'), primary_key=True), db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True)) resourcepopulation = db.Table( 'resourcepopulation', db.Column('resource_id', db.Integer, db.ForeignKey('resource.id'), primary_key=True), db.Column('population_id', db.Integer, db.ForeignKey('population.id'), primary_key=True))
"""Models for blog application.""" import datetime from flask import url_for, current_app from flask.ext.login import AnonymousUserMixin, UserMixin from flask.ext.sqlalchemy import SQLAlchemy from itsdangerous import SignatureExpired, BadSignature from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from .extensions import bcrypt, mongo db = SQLAlchemy() roles = db.Table( 'role_users', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('role_id', db.Integer, db.ForeignKey('role.id')) ) class User(db.Model, UserMixin): """User.""" id = db.Column(db.Integer(), primary_key=True, autoincrement=True) username = db.Column(db.String(255)) password = db.Column(db.String(255)) posts = db.relationship('Post', backref='user', lazy='dynamic') roles = db.relationship('Role', secondary=roles, backref=db.backref('users', lazy='dynamic')) def __repr__(self):
# -*- coding: utf8 -*- import json from sqlalchemy import MetaData, Table, Column, String, Integer from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import Security, SQLAlchemyUserDatastore, \ UserMixin, RoleMixin, login_required DB = SQLAlchemy() ## User and roles roles_users = DB.Table( 'roles_users', DB.Column('users_id', DB.Integer(), DB.ForeignKey('users.id')), DB.Column('roles_id', DB.Integer(), DB.ForeignKey('roles.id'))) class Roles(DB.Model, RoleMixin): id = DB.Column(DB.Integer(), primary_key=True) name = DB.Column(DB.String(80), unique=True) description = DB.Column(DB.String(255)) class Users(DB.Model, UserMixin): id = DB.Column(DB.Integer, primary_key=True) email = DB.Column(DB.String(255), unique=True) password = DB.Column(DB.String(255)) active = DB.Column(DB.Boolean()) confirmed_at = DB.Column(DB.DateTime())
from flask.ext.sqlalchemy import SQLAlchemy, models_committed app = Flask(__name__) app.secret_key = "asdfdf" # 配置数据库 app.config[ 'SQLALCHEMY_DATABASE_URI'] = "mysql://*****:*****@127.0.0.1:3306/manytomany" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) # 创建一个的表 tb_Student_Course = db.Table( "student_course", db.Column('student_id', db.Integer, db.ForeignKey("student.id")), db.Column('course_id', db.Integer, db.ForeignKey("course.id")), ) # 使用模型去表示一张表 class Student(db.Model): """学生表""" id = db.Column(db.Integer, primary_key=True) # 学生名 name = db.Column(db.String(64), unique=True) # 当前学生都选修了哪些课程 courses = db.relationship('Course', backref=db.backref('students', lazy="dynamic"), lazy="dynamic", secondary=tb_Student_Course)
app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL') app.config['DEBUG'] = os.environ.get('DEBUG') app.config['USERNAME'] = os.environ.get('USERNAME') app.config['PASSWORD'] = os.environ.get('PASSWORD') app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') app.config['POSTMARK_API_KEY'] = os.environ.get('POSTMARK_API_KEY') app.config['POSTMARK_SENDER'] = os.environ.get('POSTMARK_SENDER') markdown = Markdown(app,extensions=['tables']) db = SQLAlchemy(app) candidate_problems = db.Table('candidate_problems', db.Model.metadata, db.Column('candidate_id', db.Integer, db.ForeignKey('candidates.id')), db.Column('problem_id', db.Integer, db.ForeignKey('problems.id')), db.Column('position', db.Integer)) class Candidate(db.Model): __tablename__ = 'candidates' id = db.Column(db.Integer, db.Sequence('candidate_id_seq'), primary_key=True) name = db.Column(db.String) email = db.Column(db.String) notify_emails = db.Column(db.String) start_time = db.Column(db.DateTime) url_hash = db.Column(db.String) problems = db.relationship('Problem', secondary=candidate_problems, order_by=candidate_problems.columns.position, backref='candidates') def __repr__(self):
app = Flask(__name__) try: import clb_config app.config.from_object('clb_config.Config') except: app.config.from_object(os.environ['APP_SETTINGS']) app.permanent_session_lifetime = timedelta(minutes=15) db = SQLAlchemy(app) meta = db.MetaData() meta.bind = db.engine activated_table = db.Table('activated_addresses', meta, db.Column('address', db.String, primary_key=True)) csrf = SeaSurf(app) import models login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "login_page" assets = flask.ext.assets.Environment() assets.init_app(app) sslify = SSLify(app)
from logbook import Logger from collections import deque import click import requests import json import time db = SQLAlchemy() JsonType = db.String().with_variant(JSON(), 'postgresql') inf = float('inf') log = Logger(__name__) route_station_assoc = db.Table( 'route_station_assoc', db.Column('route_id', db.Integer, db.ForeignKey('route.id')), db.Column('station_id', db.Integer, db.ForeignKey('station.id')), db.Column('sequence', db.Integer), ) route_edge_assoc = db.Table( 'route_edge_assoc', db.Column('route_id', db.Integer, db.ForeignKey('route.id')), db.Column('edge_id', db.Integer, db.ForeignKey('edge.id')), ) # Many-to-many relationship between (transferable) routes # route_route_assoc = db.Table( # 'route_station_assoc', # db.Column('route_id1', db.Integer, db.ForeignKey('route.id')), # db.Column('route_id2', db.Integer, db.ForeignKey('route.id')), # db.Column('station_id', db.Integer, db.ForeignKey('station.id')),
from flask.ext.sqlalchemy import SQLAlchemy from flask import json from moviesneaker import app db = SQLAlchemy(app) zipcodes = db.Table( 'zipcodes', db.Column('zipcode_id', db.Integer, db.ForeignKey('zipcode.id')), db.Column('venue_id', db.Integer, db.ForeignKey('venue.id'))) class Zipcode(db.Model): id = db.Column(db.Integer, primary_key=True) zipcode = db.Column(db.String(60), unique=True) def __init__(self, zipcode): self.zipcode = zipcode def __json__(self): return self.zipcode class Movie(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(256)) runtime = db.Column(db.Integer) # in minutes description = db.Column(db.String(512)) notes = db.Column(db.String(1024)) showings = db.relationship('Showing')
from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base import random import hashlib db = SQLAlchemy() association_table = db.Table( 'association', db.Model.metadata, db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('course_id', db.Integer, db.ForeignKey('course.id'))) class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(128)) courses = db.relationship("Course", secondary=association_table, backref="users") coursesTeaching = db.relationship('Course', backref='author', lazy='dynamic') name = db.Column(db.String(255)) permissions = db.Column(db.Integer, default=10) task_responses = db.relationship('TaskResponse', backref='user', lazy='dynamic')
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username category_activitytype = db.Table( 'category_activitytype', db.Column('category_id', db.Integer, db.ForeignKey('category.id')), db.Column('activitytype_id', db.Integer, db.ForeignKey('activitytype.id'))) class Category(db.Model): id = db.Column(db.Integer, primary_key=True) category = db.Column(db.String(80), unique=True) #activitytypes = db.relationship('ActivityType', backref='AT', lazy='dynamic') category_activitytype = db.relationship('ActivityType', secondary=category_activitytype, backref=db.backref('categories', lazy='dynamic')) def __init__(self, category): self.category = category
def create_app(test_config=None): # For automated tests # Setup Flask and read config from ConfigClass defined above app = Flask(__name__) app.config.from_object(__name__ + '.ConfigClass') # Load local_settings.py if file exists # For automated tests try: app.config.from_object('local_settings') except: pass # Load optional test_config # For automated tests if test_config: app.config.update(test_config) # Initialize Flask extensions db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy mail = Mail(app) # Initialize Flask-Mail # Define the User-Roles pivot table user_roles = db.Table( 'user_roles', db.Column('id', db.Integer(), primary_key=True), db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))) # Define Role model class Role(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(50), unique=True) # Define User model. Make sure to add flask.ext.user UserMixin!! class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) active = db.Column(db.Boolean(), nullable=False, default=False) username = db.Column(db.String(50), nullable=True, unique=True) email = db.Column(db.String(255), nullable=True, unique=True) confirmed_at = db.Column(db.DateTime()) password = db.Column(db.String(255), nullable=False, default='') reset_password_token = db.Column(db.String(100), nullable=False, default='') # Relationships roles = db.relationship('Role', secondary=user_roles, backref=db.backref('users', lazy='dynamic')) # Reset all the database tables db.create_all() # Setup Flask-User db_adapter = SQLAlchemyAdapter(db, User) user_manager = UserManager(db_adapter, app) # Create 'user007' user with 'secret' and 'agent' roles if not User.query.filter(User.username == 'user007').first(): user1 = User(username='******', email='*****@*****.**', active=True, password=user_manager.hash_password('Password1')) user1.roles.append(Role(name='secret')) user1.roles.append(Role(name='agent')) db.session.add(user1) db.session.commit() # The '/' page is accessible to anyone @app.route('/') def home_page(): # if current_user.is_authenticated(): # return profile_page() return render_template_string(""" {% extends "base.html" %} {% block content %} <h2>{%trans%}Home Page{%endtrans%}</h2> <p><a href="{{ url_for('user.login') }}">{%trans%}Sign in{%endtrans%}</a></p> {% endblock %} """) # The '/profile' page requires a logged-in user @app.route('/profile') @login_required # Use of @login_required decorator def profile_page(): return render_template_string(""" {% extends "base.html" %} {% block content %} <h2>{%trans%}Profile Page{%endtrans%}</h2> <p> {%trans%}Hello{%endtrans%} {{ current_user.username or current_user.email }},</p> <p> <a href="{{ url_for('user.change_username') }}"> {%trans%}Change username{%endtrans%}</a></p> <p> <a href="{{ url_for('user.change_password') }}"> {%trans%}Change password{%endtrans%}</a></p> <p> <a href="{{ url_for('user.logout') }}?next={{ url_for('user.login') }}"> {%trans%}Sign out{%endtrans%}</a></p> {% endblock %} """) # The '/special' page requires a user that has the 'special' AND ('sauce' OR 'agent') role. @app.route('/special') @roles_required('secret', ['sauce', 'agent']) # Use of @roles_required decorator def special_page(): return render_template_string(""" {% extends "base.html" %} {% block content %} <h2>{%trans%}Special Page{%endtrans%}</h2> {% endblock %} """) return app
# ---------------------------------------------------------------------- # Load the config # ---------------------------------------------------------------------- app = Flask(__name__) app.config.from_object(Settings) app.config.from_envvar('LUNCHO_CONFIG', True) app.json_encoder = DateEncoder # ---------------------------------------------------------------------- # Database # ---------------------------------------------------------------------- from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) user_groups = db.Table( 'user_groups', db.Column('username', db.String, db.ForeignKey('user.username')), db.Column('group_id', db.Integer, db.ForeignKey('group.id'))) group_places = db.Table( 'group_places', db.Column('group', db.Integer, db.ForeignKey('group.id')), db.Column('place', db.Integer, db.ForeignKey('place.id'))) class User(db.Model): username = db.Column(db.String, primary_key=True) fullname = db.Column(db.String, nullable=False) passhash = db.Column(db.String, nullable=False) token = db.Column(db.String) issued_date = db.Column(db.Date) validated = db.Column(db.Boolean, default=False) created_at = db.Column(db.DateTime, nullable=False)
self.name = name self.email = email self.pw_hash = pw_hash @classmethod def by_id(cls, uid): return cls.query.filter_by(id=uid).one() @classmethod def by_name(cls, name): u = cls.query.filter_by(name=name).first() return u post_tags = db.Table('post_tags', db.metadata, db.Column('post_id', db.Integer, db.ForeignKey('posts.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')) ) class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text, nullable=False) pub_date = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('User', backref=db.backref('posts')) page_id = db.Column(db.Integer, db.ForeignKey('pages.id')) page = db.relationship('Page', backref=db.backref('posts'))
from sqlalchemy import and_, or_ from sqlalchemy.ext.hybrid import hybrid_property def _date_to_datetime(date): '''Convert a date object to a datetime object The time is set to 00:00:00 ''' midnight = datetime.time(0, 0, 0) return datetime.datetime.combine(date, midnight) db = SQLAlchemy(app) roles_users = db.Table('members_roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('members.id')), db.Column('role_id', db.Integer(), db.ForeignKey('members_roles.id'))) class Role(db.Model, RoleMixin): """Define the Role database table""" __tablename__ = 'members_roles' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __repr__(self): return self.name class User(db.Model, UserMixin):
from jwt import DecodeError, ExpiredSignature from flask.ext.rbac import RBAC, RoleMixin, UserMixin # Configuration current_path = os.path.dirname(__file__) client_path = os.path.abspath(os.path.join(current_path, '..', '..', 'client')) app = Flask(__name__) app.config.from_object('config') rbac = RBAC(app) db = SQLAlchemy(app) roles_parents = db.Table('roles_parents', db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True), db.Column('parent_id', db.Integer, db.ForeignKey('role.id'), primary_key=True) ) @rbac.as_role_model class Role(db.Model, RoleMixin): __tablename__ = 'role' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime, default=db.func.current_timestamp()) modified_at = db.Column(db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp()) name = db.Column(db.String(80), nullable=False, unique=True) description = db.Column(db.String(255)) parents = db.relationship(
def init_db(uri=None): """Start up the DB connection. `uri` is the uri to use for the database. If it is None, the uri from the config file will be used. """ if uri is None: uri = cfg.get('database', 'uri') app.config.update(SQLALCHEMY_DATABASE_URI=uri) # A joining table for project's access to networks, which have a many to many # relationship: network_projects = db.Table( 'network_projects', db.Column('project_id', db.ForeignKey('project.id')), db.Column('network_id', db.ForeignKey('network.id'))) class Nic(db.Model): """a nic belonging to a Node""" id = db.Column(BigIntegerType, primary_key=True) label = db.Column(db.String, nullable=False) # The Node to which the nic belongs: owner_id = db.Column(db.ForeignKey('node.id'), nullable=False) owner = db.relationship("Node", backref=db.backref('nics')) # The mac address of the nic: mac_addr = db.Column(db.String)
@declared_attr def notes(cls): joinstr = '{0}.id == foreign(Note.table_id) and Note.type == "{1}"'.format( cls.__name__, cls.__tablename__) return db.relationship('Note', primaryjoin=joinstr) @declared_attr def attachments(cls): joinstr = '{0}.id == foreign(Attachment.table_id) and Attachment.type == "{1}"'.format( cls.__name__, cls.__tablename__) return db.relationship('Attachment', primaryjoin=joinstr) user_permission = db.Table( 'user_permission', db.metadata, Column('user_id', Integer, ForeignKey('user.id')), Column('permission_id', Integer, ForeignKey('permission.id'))) class EventMessage(object): pass class Event(MetadataMixin, db.Model): user = db.relationship('User', backref=db.backref('events', order_by='Event.date')) date = Column(DateTime, nullable=False, index=True) msg = Column(UnicodeText, nullable=False)
# Create models class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) # Required for administrative interface def __str__(self): return self.username # Create M2M table post_tags_table = db.Table( 'post_tags', db.Model.metadata, db.Column('post_id', db.Integer, db.ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))) class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120)) text = db.Column(db.Text, nullable=False) date = db.Column(db.DateTime) user_id = db.Column(db.Integer(), db.ForeignKey(User.id)) user = db.relationship(User, backref='posts') tags = db.relationship('Tag', secondary=post_tags_table) def __str__(self):
errors = {} for fn in ['name', 'email']: if getattr(self, fn) in ['', None]: errors[fn] = '%s must be set' return errors class UserRole(db.Model, RoleMixin): __tablename__ = "userroles" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(255), unique=True) description = db.Column(db.Unicode(255)) users_userroles = db.Table( 'users_userroles', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('userrole_id', db.Integer, db.ForeignKey('userroles.id'))) # Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, UserRole) class Server(db.Model, IterableModel, RestModel): __tablename__ = 'servers' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Unicode(255), nullable=False, unique=True) daemon_type = db.Column(db.Unicode(255)) stats_url = db.Column(db.Unicode(255)) manager_url = db.Column(db.Unicode(255)) api_key = db.Column(db.Unicode(255)) __public_fields__ = [
from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.security import UserMixin, RoleMixin from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy import distinct db = SQLAlchemy() ### Add models here roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def to_dict(self): return { 'id': self.id, 'type': 'user', 'attributes': { 'name': self.name, 'description': self.description } }
app.config['MAIL_USE_SSL'] = False app.config['MAIL_DEBUG'] = True app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' mail = Mail(app) # Create database connection object db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) # Define models roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) posts_users = db.Table( 'posts_users', db.Column('post_id', db.Integer(), db.ForeignKey('post.id')), db.Column('user_id', db.Integer(), db.ForeignKey('user.id'))) friends = db.Table( 'friends', db.Column('friend_id', db.Integer, db.ForeignKey('user.id')), db.Column('friended_id', db.Integer, db.ForeignKey('user.id'))) class ExtendedLoginForm(LoginForm): email = StringField('Username or Email Address', [InputRequired()])