Example #1
0
 def create_db():
     """Create DB."""
     # from pmaapi.api.open_model.open_model_py.__main__ import db
     from flask_sqlalchemy import SQLAlchemy, declarative_base
     from pmaapi.api.open_model_py.__main__ import OpenModel
     from pmaapi.config import MODEL_FILE
     db = SQLAlchemy(FLASK_APP)
     db.Base = declarative_base()
     # TODO: Figure out how to get 'db' to know about this,
     #   if it doesn't automatically (reading from globals?).
     # models = OpenModel(MODEL_FILE)
     db.create_all()  # Run if it does not exist.
     db.session.commit()
#   following disclaimer in the documentation and/or other materials provided with the distribution.                  #
# * Neither the name of Qualcomm Technologies, Inc. nor the names of its contributors may be used to endorse or       #
#   promote products derived from this software without specific prior written permission.                            #
#                                                                                                                     #
# NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED  #
# BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED #
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT      #
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR   #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES LOSS OF USE,      #
# DATA, OR PROFITS OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,      #
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,   #
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                                                                  #
#                                                                                                                     #
#######################################################################################################################

__all__ = [
    "case", "casecomments", "caseincidentdetails", "casepersonaldetails",
    "devicedetails", "deviceimei", "devicemsisdn", "natureofincident",
    "status", "delta_list"
]
from ..models import *
from flask_sqlalchemy import declarative_base

# avoid circular imports, define both dependent tables in one go
Base = declarative_base(class_registry={
    "status": status.Status,
    "case": case.Case
})
user_base = declarative_base(
    class_registry={"casecomments": casecomments.CaseComments})
Example #3
0
import unittest
from flask import Flask
from flask_sqlalchemy import SQLAlchemy, DefaultMeta, declarative_base, Model

MyModel = declarative_base(cls=Model, name='MyModel', metaclass=DefaultMeta)


class Config:
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'sqlite://'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = False


app_a = Flask('app_a')
app_a.config.from_object(Config)
db_a = SQLAlchemy(app_a, model_class=MyModel)

app_b = Flask('app_b')
app_b.config.from_object(Config)
db_b = SQLAlchemy(app_b, model_class=MyModel)

print(db_a.session)


class A(db_a.Model):
    __tablename__ = 'a'
    id = db_a.Column(db_a.Integer, primary_key=True, autoincrement=True)
    content = db_a.Column(db_a.Text, nullable=False)

 This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable
 for any damages arising from the use of this software.

 Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter
 it and redistribute it freely, subject to the following restrictions:

 * The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If
   you use this software in a product, an acknowledgment is required by displaying the trademark/logo as per the details
   provided here: https://www.qualcomm.com/documents/dirbs-logo-and-brand-guidelines
 * Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
 * This notice may not be removed or altered from any source distribution.

 NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.                                                               #
"""

__all__ = ["request", "summary"]

from ..models import *
from flask_sqlalchemy import declarative_base

# avoid circular imports, define both dependent tables in one go
Base = declarative_base(class_registry={"status": request.Request})
Example #5
0
from flask_sqlalchemy import declarative_base

Base = declarative_base()
Example #6
0
from flask_sqlalchemy import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import create_engine

# Create an engine that stores data in the local directory's
engine = create_engine('sqlite:///TransportForKlingons.db', convert_unicode=True, echo=True)

# Create session that can be used by the views to access the database
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()

# Create the db schema - called from init_db.py
def init_db():
    from models.service import Service
    from models.stop import Stop
    from models.vehicle import Vehicle
    from models.associations import StopService
    from models.associations import UserService
    from models.update import Update
    from models.User import User
    # Create all tables in the engine.
    Base.metadata.create_all(bind=engine)
Example #7
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import lib.SQLConnect
import flask_sqlalchemy
from sqlalchemy import Column, Integer, Sequence, String

Base = flask_sqlalchemy.declarative_base()


#class master(Base):
class master(Base):
    __tablename__ = 'Master'
    IDMASTER = Column(Integer, primary_key=True)
    SHOTNAMEMASTER = Column(String(200), index=True)
    FULLNAMEMASTER = Column(String(200), index=True)
    BIRTHDAY = Column(String(200), index=True)
    BIRTHPLACE = Column(String(200), index=True)
    ADRESSREGISTR = Column(String(200), index=True)
    DATARAB = Column(String(200), index=True)
    DATAUVOLN = Column(String(200), index=True)
    NOTES = Column(String(200), index=True)
    PRIZNUVOLN = Column(String(200), index=True)
    PRICHINAUV = Column(String(200), index=True)
    TELEFON = Column(String(200), index=True)
    FOTO = Column(String(200), index=True)
    login = Column(String(200), index=True)
    password = Column(String(200), index=True)
    hash = Column(String(200), index=True)

    def __init__(self,
Example #8
0
    def __flush_insert_event__(cls, target):
        target.__flush_event__(target)

    @classmethod
    def __flush_delete_event__(cls, target):
        target.__flush_event__(target)

    @classmethod
    def __flush_after_update_event__(cls, target):
        target.__flush_event__(target)

    @classmethod
    def __declare_last__(cls):
        event.listen(cls, 'after_insert', cls._flush_insert_event)
        event.listen(cls, 'after_delete', cls._flush_delete_event)
        event.listen(cls, 'after_update', cls._flush_after_update_event)


class BindDBPropertyMeta(DefaultMeta):
    def __init__(cls, name, bases, d):
        super().__init__(name, bases, d)
        db_columns = []
        for k, v in d.items():
            if isinstance(v, PropsItem):
                db_columns.append((k, v.default))
        cls._db_columns = db_columns


db = SQLAlchemy(model_class=declarative_base(
    cls=BaseModel, metaclass=BindDBPropertyMeta, name='Model'))
Example #9
0
from flask_sqlalchemy import declarative_base


BaseModel = declarative_base()
Example #10
0
import sqlalchemy as SA
import datetime
import os
import threading
import time

from personal_blog.config import setting
from flask_sqlalchemy import declarative_base
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.mysql import BIGINT


class tBase(object):
    created_date = SA.Column(SA.DateTime, default=datetime.datetime.now)
    modified_date = SA.Column(SA.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)

    def __repr__(self):
        m = self.__class__.__module__
        c = self.__class__.__name__
        return "<%s.%s id=%s>" % (m, c, self.id)




Base = declarative_base(cls=tBase)

db = SQLAlchemy(model_class=Base, session_options={"enable_baked_queries": True})
metadata = db.metadata


Example #11
0
class MySQLInterface:
    # Model of rows in our tables
    Base = declarative_base()

    # MySQL database readers / writers
    def __init__(self, app):
        self.db = SQLAlchemy(app)

        self.Base.metadata.create_all(self.db.engine)
        self.Base.metadata.bind = self.db

        self.db.init_app(app)

        Session = sessionmaker(bind=self.db.engine)
        self.session = Session()

    class Event(Base):
        __tablename__ = 'events'

        id = Column('id', Integer, primary_key = True)
        name = Column('name', String)
        description = Column('description', String)
        latitude = Column('latitude', String)
        longitude = Column('longitude', String)
        start_time = Column('start_time', String)
        duration = Column('duration', String)
        litness = Column('litness', Integer)
        address = Column('address', String)

    class OldEvent(Base):
        __tablename__ = 'old events'
 
        id = Column('id', Integer, primary_key = True)
        event_id = Column('event_id', Integer)
        name = Column('name', String)
        description = Column('description', String)
        latitude = Column('latitude', String)
        longitude = Column('longitude', String)
        address = Column('address', String)
        start_time = Column('start_time', String)
        duration = Column('duration', String)
        litness = Column('litness', Integer)

    class Vote(Base):
        __tablename__ = 'votes'

        id = Column('id', Integer, primary_key = True)
        event_id = Column('event_id', Integer)
        unique_id = Column('unique_id', String)
        upvote = Column('upvote', Integer)
        downvote = Column('downvote', Integer)

    # Fetch All Events
    def get_events(self):
        events = self.session.query(self.Event).all()
        self.session.close()
        
        event_list = list()

        for event in events:
            each_event = list()

            now = datetime.datetime.utcnow()
            current_time = int((now - datetime.datetime(1970, 1, 1)).total_seconds())
            start_time = int(event.start_time)

            # Only show events within 72 hours in advance
            if((start_time - current_time) < 259200):
                each_event.append(int(event.id))
                each_event.append(str(event.name))
                each_event.append(str(event.latitude).replace('\r', '') \
                                  .replace('\n', ''))
                each_event.append(str(event.longitude))
                each_event.append(int(event.litness))
                each_event.append(str(event.description))
                each_event.append(int(event.start_time))
                each_event.append(int(0))
                each_event.append(str(event.address))
            
                event_list.append(each_event)

        event_list.sort(reverse = True, key = lambda x: x[4])
        return event_list
    
    # Post New Event
    def add_event(self, name, description, latitude, longitude,
                  start_time, duration, address):
        new_event = self.Event(name = name,
                               description = description,
                               latitude = latitude,
                               longitude = longitude,
                               start_time = start_time,
                               duration = duration, 
                               litness = 0,  # Updated with Upvotes / Downvotes
                               address = address)

        self.session.add(new_event)
        self.session.commit()
        self.session.close()

        print "New event: " + str(name) + " added at " + str(address) + "."

    # Get Litscore of an Event
    def litScore(self, id):
        votes = self.session.query(self.Vote).filter(self.Vote.event_id == id)
        self.session.close()
        
        score = 0

        for vote in votes:
            score += int(vote.upvote)
            score -= int(vote.downvote)

        return score
    
    # Upvote & Downvote
    def voter(self, event_id, unique_id, ud):
        # Check if event has already been voted by user
        exists = self.session.query(self.Vote) \
                .filter_by(unique_id = unique_id, event_id = event_id).scalar()

        # Vote either up or down
        upvote = 0
        downvote = 0

        if ud == "Up":
            upvote = 1
            downvote = 0
        elif ud == "Down":
            downvote = 1
            upvote = 0
        else:
            return self.get_votes(event_id)

        if exists is not None:
            # Changes existing vote
            if(int(exists.upvote) != upvote):
                exists.upvote = upvote
                self.session.add(exists)
                self.session.commit()
                print str(unique_id) + " changed their vote for " + str(event_id) + "."
            else:
                print str(unique_id) + " already casted a " + str(ud) + " vote for " + str(event_id) + "."
                return self.get_votes(event_id)
        else:
            new_vote = self.Vote(event_id = event_id,
                                 unique_id = unique_id,
                                 upvote = upvote,
                                 downvote = downvote)

            self.session.add(new_vote)
            self.session.commit()
            print str(unique_id) + " casted a new " + str(ud) + " vote for " + str(event_id) + "."

        # Update Events table with new Litscore
        new_score = self.litScore(event_id)

        update = self.session.query(self.Event).filter(self.Event.id == event_id).first()
        update.litness = new_score
        self.session.add(update)
        self.session.commit()
        self.session.close()

        # Return Upvotes, Downvotes for voted events
        return new_score

    # Address -> LatLng
    def forward_geocode(self, address):
        # Westwood Boundaries
        topRightBoundary = [34.082001, -118.431416]
        bottomLeftBoundary = [34.045334, -118.454762]

        g = geocoder.google(str(address))
        latlng = g.latlng
        
        lat = latlng[0]
        lng = latlng[1]

        if((lat < topRightBoundary[0]) and (lat > bottomLeftBoundary[0]) \
           and (lng < topRightBoundary[1]) and (lng > bottomLeftBoundary[1])):
            return latlng
        else:
            print "Invalid location or address."
            return False                                     

    # LatLng -> Address
    def reverse_geocode(self, lat, lng):
        g = geocoder.google([lat, lng], method='reverse')
        return g.address
    
    # Filter Events Table
    def dbFilter(self):
        now = datetime.datetime.utcnow()
        current_time = int((now - datetime.datetime(1970, 1, 1)).total_seconds())
        
        events = self.session.query(self.Event).filter((current_time - self.Event.start_time) > 86400)

        for event in events:
            event_id = int(event.id)
            name = str(event.name)
            description = str(event.description)
            latitude = str(event.latitude)
            longitude = str(event.longitude)
            address = str(event.address)
            start_time = str(event.start_time)
            duration = str(event.duration)
            litness = int(event.litness)

            new_old = self.OldEvent(event_id = event_id,
                                      name = name,
                                      description = description,
                                      latitude = latitude,
                                      longitude = longitude,
                                      address = address,
                                      start_time = start_time,
                                      duration = duration,
                                      litness = litness)

            # Transfer Events to Old Events
            self.session.add(new_old)
            self.session.commit()

            # Delete Event from Table
            self.session.query(self.Event).filter(self.Event.id == event_id).delete()
            self.session.commit()

        self.session.close()
 def init_app(self, app):
     SQL.driver.Model = declarative_base()
     super(EveSQLAlchemy, self).init_app(app)