Ejemplo n.º 1
0
import email, imaplib
import zmq
import random
import datetime, time
import logging
import json
from models import Trade, Session

db = Session()

with open('config.json') as json_data_file:
    config = json.load(json_data_file)

volume = config['volume']
debug = config['debug']
LOG_FILENAME = config['LOG_FILENAME']
imap = config['imap']
user = config['user']
pwd = config['pwd']
folder = config['folder']
STOPLOSS = config['STOPLOSS']
TAKEPROFIT = config['TAKEPROFIT']
hedging = config['hedge']


def generate_nonce(length=8):
    return ''.join([str(random.randint(0, 9)) for i in range(length)])


def log(msg):
    if debug == "1":
Ejemplo n.º 2
0
def test_all_users(all_users):
    session = Session()
    users = session.query(User).all()
    assert len(users) >= 4
    session.close()
Ejemplo n.º 3
0
from models import User, engine, ModelBase, Session

session = Session()


def createUser(username, join_date, password):
    user = User(username=username, date_joined=join_date, password=password)
    session.add(user)
    session.commit()


def deleteUser(username):
    user = session.query(User).filter(User.username == username).first()
    session.delete(user)
    session.commit()


def getUser(username):
    user = session.query(User).filter_by(username=username).first()
    return user


def getAll():
    all_user = session.query(User).filter()
    return all_user


def editUser(username):
    user = session.query(User).filter_by(username=username).first()

    while True:
Ejemplo n.º 4
0
def doValidation(email):
    ses = Session()
    resultset = ses.query(User).filter(User.email==email).all()
    if len(resultset)> 0:
        user = resultset[0]
        return user.password
Ejemplo n.º 5
0
from rabbitmq import FibonacciConsumer

load_dotenv('.env')

consumer = FibonacciConsumer(host=os.environ.get('RABBITMQ_HOST', 'localhost'),
                             port=os.environ.get('RABBITMQ_PORT', '5672'),
                             username=os.environ.get('RABBITMQ_USER',
                                                     'fibonacci'),
                             password=os.environ.get('RABBITMQ_PASS',
                                                     'fibonacci'))


def add_fibonacci_to_db(fibonacci_dict):

    number = fibonacci_dict['number']
    fibonacci_number = str(fibonacci_dict['fibonacci_number'])

    fibonacci = Fibonacci(number=number, fibonacci_number=fibonacci_number)
    history = FibonacciHistory(date=datetime.datetime.now(), number=number)

    if not Fibonacci.exists(session=session, number=number):
        print(f'Fibonacci number {number} exists in db. Ommiting')
        session.add(fibonacci)
    session.add(history)
    session.commit()


with Session() as session:
    consumer.consume_fibonacci_messages(queue=os.environ.get(
        'RABBITMQ_QUEUE', 'fibonacci'),
                                        on_consume=add_fibonacci_to_db)
Ejemplo n.º 6
0
def delete_entry(model_class, uid, *, commit=True):
    session = Session()
    session.query(model_class).filter_by(uid=uid).delete()
    if commit:
        session.commit()
Ejemplo n.º 7
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']

        # get conference key
        conf = ndb.Key(urlsafe=data['websafeConferenceKey']).get()
        if not conf:
            raise endpoints.NotFoundException('No conference found with key: \
                %s' % request.websafeConferenceKey)

        del data['websafeConferenceKey']

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # add default values for those missing (both data model & outbound
        # Message)
        for df in SESS_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESS_DEFAULTS[df]
                setattr(request, df, SESS_DEFAULTS[df])

        # convert dates from strings to Date objects; set month based on
        # start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d"). \
                           date()
        if data['startTime']:
            try:
                data['startTime'] = datetime.strptime(data['startTime'],
                                                      "%I:%M%p").time()
            except:
                data['startTime'] = datetime.strptime(data['startTime'],
                                                      "%H:%M").time()

        # generate new session key
        s_id = Session.allocate_ids(size=1, parent=conf.key)[0]
        s_key = ndb.Key(Session, s_id, parent=conf.key)
        data['key'] = s_key

        # create Session, send email to organizer confirming
        # creation of session & return (modified) SessionForm
        Session(**data).put()

        # Check and see if this speaker is now the featured speaker
        # Use dictionary to count speaker sessions
        speakerCounts = {}
        # Track the most number of sessions for a speaker
        mostSessions = 0
        # The speaker with the most number of sessions will be featured speaker
        featuredSpeaker = ""
        # Get the sessions for the conference
        sessions = Session.query(ancestor=conf.key)

        # For each session, add to the session count for each speaker
        for sess in sessions:
            if sess.speaker in speakerCounts:
                speakerCounts[sess.speaker] += 1
            else:
                speakerCounts[sess.speaker] = 1

            # If the speaker for this session now has more sessions than
            # current featured speaker, make this speaker the featured. If
            # speakers have the same number of sessions, the most recent
            # speaker found with that number will be featured.
            if speakerCounts[sess.speaker] >= mostSessions:
                mostSessions = speakerCounts[sess.speaker]
                featuredSpeaker = sess.speaker

        taskqueue.add(params={
            'conference': conf.name,
            'featuredSpeaker': featuredSpeaker
        },
                      url='/tasks/set_featured_speaker')

        return request
Ejemplo n.º 8
0
def _create_session(node):
    session = Session("test session")
    session.node_key = node.node_key
    session.client_updated_at = datetime.utcnow()
    return session
Ejemplo n.º 9
0
    def _createSessionObject(self, request):
        """Create or update a Session object"""
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # fetch and check conference
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        # convert date and time fields to the correct types
        if data['dateTime']:
            s_date = datetime.strptime(data['dateTime'], '%Y-%m-%d %H:%M')
            data['dateTime'] = s_date
            data['startTime'] = datetime.strftime(s_date, '%H:%M')
        # set type of session if it's not supplied set it to 'NOT_SPECIFIED'
        if data['typeOfSession']:
            data['typeOfSession'] = str(data['typeOfSession'])
        else:
            data['typeOfSession'] = 'NOT_SPECIFIED'

        # delete the websafeConferenceKey it will be the parent and does
        # not need to be saved as an entity
        del data['websafeConferenceKey']
        # delete speakerDisplayName it is not stored in te database
        del data['speakerDisplayName']

        # add default values for those missing (both data model & outbound Message)
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        s_id = Conference.allocate_ids(size=1, parent=conf.key)[0]
        s_key = ndb.Key(Session, s_id, parent=conf.key)

        data['key'] = s_key

        Session(**data).put()

        # - - - Task 4 - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        # after adding the data check if the speaker has mre than one session
        # at the conference. If they do add a Memcache entry for them

        # first get all sesiions for the conference then filter by speaker
        # if there is more than one session add to Memcache
        confSessions = Session.query(ancestor=conf.key)
        speakerSessions = confSessions.filter(
            Session.speaker == data['speaker'])
        # speakerSessions = confSessions
        sessionCount = speakerSessions.count()
        if sessionCount > 1:
            # get the speaker object from id
            speak = Speaker.get_by_id(data['speaker'])
            taskqueue.add(params={'speakerName': speak.name},
                          url='/tasks/add_featured_speaker')

        return request
Ejemplo n.º 10
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Get the current user.
        user = endpoints.get_current_user()
        # If there isn't one, raise an authorization exception.
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        # Set the user id using getUserId from utils.py
        user_id = getUserId(user)
        # Make sure a name is provided
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")
        # Make sure a websafeConferenceKey is provided (for testing)
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException(
                "Session 'websafeConferenceKey' field required")
        # Get the websafeConferenceKey
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
        # Check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)
        # Check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')
        # Copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        del data['websafeKey']
        del data['websafeConferenceKey']
        del data['conferenceName']

        # Add default values for those missing (both data model & outbound Message)
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        # Convert dates from strings to Date objects; set month based on date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        # Generate keys for Session.
        c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key

        # create Session, send email to organizer confirming
        # creation of Session & return (modified) SessionForm
        Session(**data).put()
        sessions = Session.query(Session.speaker == data['speaker']).count()
        if sessions > 1:
            taskqueue.add(params={'speaker': data['speaker']},
                          url='/tasks/set_featured_speaker')
        # send the request over to the form.
        return self._copySessionToForm(request)
Ejemplo n.º 11
0
    def save_session(user: User):
        session = Session(user.serialize())

        session.save()
Ejemplo n.º 12
0
 def version(self):
     try:
         session = Session()
         return session.query(FetchDataVersion).first()
     finally:
         session.close()
Ejemplo n.º 13
0
 def __init__(self, inventory = "my_inventory"):
     self.inventory = inventory
     self.session = Session()
Ejemplo n.º 14
0
    def get_sell_stocks_pool_thru_short_trend(self, date):
        '''
        获得明天需要卖掉的股票
        '''
        result = []

        leave_level = 0.06
        leave_level_1 = 0.10

        top_level = 0.20
        top_level_1 = 0.15

        stocks = self.current_stocks()
        session = Session()
        block_money = self.get_block_money(date, type='close')

        for stock in stocks:
            session.add(stock)
            max_price = stock.max_price or stock.price
            price = stock.price
            ts_code = stock.code
            today_price = self.get_price(ts_code, date)
            if today_price is None:
                continue

            # 当股价没有涨过0.05就直接跌,那么0.08的跌幅离开
            # 当股价涨过了0.05,那么0.10的跌幅离开
            l_level = leave_level if (
                (max_price - price) / price) <= 0.05 else leave_level_1

            # 止损卖出
            # 跌了移动平均线的10%,第二天全部卖出
            if today_price <= max_price * (1 - l_level):
                result.append({'ts_code': ts_code, 'count': stock.count})
            # 止盈卖出
            # 20%的时候,卖出至少3/4
            elif ((today_price - stock.price) / stock.price >= top_level
                  ) and stock.count * today_price > block_money * 1 / 4:
                if (stock.count * 1 / 2) >= 100:
                    result.append({
                        'ts_code': ts_code,
                        'count': self.stock_int(stock.count * 1 / 2)
                    })
                else:
                    result.append({'ts_code': ts_code, 'count': stock.count})

            # 15%的时候,卖出至少1/2
            elif ((today_price - stock.price) / stock.price >= top_level_1
                  ) and stock.count * today_price > block_money * 1 / 2:
                if stock.count * 1 / 2 >= 100:
                    result.append({
                        'ts_code': ts_code,
                        'count': self.stock_int(stock.count * 1 / 2)
                    })
                else:
                    result.append({'ts_code': ts_code, 'count': stock.count})

            # 设置移动最大值,目的移动止损点
            if today_price > max_price:
                stock.max_price = convert_to_py_type(today_price)

        session.commit()
        session.expunge_all()
        session.close()
        return result
Ejemplo n.º 15
0
def list_wallets():
    session = Session()
    return session.query(Wallets).all()
Ejemplo n.º 16
0
from models import Session, Playlist, User

session1 = Session()

user1 = User(user_id = 1, name = "Vasya", email = "*****@*****.**", password = "******")
playlist1 = Playlist(playlist_id = 12, name = "morgenshtern", owner_id = 1, songs = ['du','ca','la','bo','gu'])

session1.add(user1)
session1.add(playlist1)

session1.commit()

session1.close()

# psql -h localhost -d musiclist -U postgres -p 5432 -a -q -f create_tables.sql
# python add_models.py 
# alembic revision --autogenerate
# alembic upgrade head
Ejemplo n.º 17
0
def get_entry_by_uid(model_class, uid):
    session = Session()
    return session.query(model_class).filter_by(uid=uid).one()
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field is required")

        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        if not conf:
            raise endpoints.NotFoundException("no conference found")

        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                "Only the owner can update conference.")

        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        wsck = data['websafeConferenceKey']

        #generate session key based on Conf
        c_key = ndb.Key(Conference, request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)

        print data['duration']

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'],
                                                  '%H:%M').time()
        if data['date']:
            data['date'] = datetime.strptime(data['date'], '%Y-%m-%d').date()

        if data['typeOfSession'] == None:
            data['typeOfSession'] = str(TypeOfSession.NOT_SPECIFIED)

        speaker = data['speaker']

        sessions = Session.query(Session.speaker == speaker).fetch()

        if len(sessions) > 1:
            taskqueue.add(params={
                'websafeConferenceKey': request.websafeConferenceKey,
                'speaker': speaker
            },
                          url='/tasks/set_featured_speaker')

        data['websafeConferenceKey'] = request.websafeConferenceKey

        #speaker_name = data['speaker']

        Session(**data).put()
        return request
Ejemplo n.º 19
0
    def _createSessionObject(self, request):
        """Create Session object, returning SessionForm/request."""
        # Authenticate user.
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = _getUserId()

        # Check that the request has a session name.
        if not request.name:
            raise endpoints.BadRequestException("Session 'name' field required")

        # Check that the request has a valid websafeConferenceKey.
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException("Session 'websafeConferenceKey' field required")
        conference = _entityByKindAndUrlsafeKeyOrNone(Conference, request.websafeConferenceKey)
        if not conference:
            raise endpoints.BadRequestException("Session 'websafeConferenceKey' field invalid")

        # Make sure the user is the conference organizer.
        if conference.organizerUserId != user_id:
            raise endpoints.UnauthorizedException('The user is not the conference organizer')

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) for field in request.all_fields()}
        del data['websafeKey']
        del data['websafeConferenceKey']

        # convert the date and startTime into Date/Time properties
        if data['date']:
            data['date'] = datetime.strptime(data['date'], "%Y-%m-%d").date()
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time()

        # add default values for missing fields
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]

        # perform necessary type conversion
        data["typeOfSession"] = str(data["typeOfSession"])
        data["duration"] = int(data["duration"])

        # generate Session ID based on Conference key and get Session key from ID.
        sessionId = Session.allocate_ids(size=1, parent=conference.key)[0]
        sessionKey = ndb.Key(Session, sessionId, parent=conference.key)
        data['key'] = sessionKey

        # create Session
        session = Session(**data)
        session.put()

        # Check if the speaker should be featured. The current session has been put into Data Store by now.
        if data['speaker'] != SESSION_DEFAULTS['speaker']:
            taskqueue.add(
                params={
                    'speaker': data['speaker'],
                    'websafeConferenceKey': request.websafeConferenceKey,
                },
                url='/tasks/check_featured_speaker'
            )

        # send email to creater confirming creation of Session
        # TODO

        return self._copySessionToForm(session)
Ejemplo n.º 20
0
def connect_db():
    g.session = Session()
    g.age = age
Ejemplo n.º 21
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # Check if user is authorized
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        # Check if required Form fields have been filled
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # Retrieve the conference Key and check if it exists
        websck = request.websafeConferenceKey
        conf = ndb.Key(urlsafe=websck).get()
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % websck)

        # Check that user is owner of conference
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        # Copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }
        sess = self._copySessionToForm(request)
        del data['websafeConferenceKey']
        del data['websafeSessionKey']

        # Add default values for those missing (both data model & outbound Message)
        for df in SESSION_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESSION_DEFAULTS[df]
                setattr(request, df, SESSION_DEFAULTS[df])

        # Convert dates and times from strings to Date and Time objects; set month based on start_date
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        if data['duration']:
            data['duration'] = datetime.strptime(data['duration'][:5],
                                                 "%H:%M").time()

        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'][:5],
                                                  "%H:%M").time()

        # Generate Session Key from obtained Conference key
        s_id = Session.allocate_ids(
            size=1, parent=ndb.Key(urlsafe=request.websafeConferenceKey))[0]
        s_key = ndb.Key(Session,
                        s_id,
                        parent=ndb.Key(urlsafe=request.websafeConferenceKey))
        data['key'] = s_key

        # Create Session
        Session(**data).put()

        # Add to task queue parameters needed to determine featured speaker
        taskqueue.add(params={
            'speaker': data['speaker'],
            'websafeConferenceKey': websck
        },
                      url='/tasks/determine_featured_speaker')

        # Return (modified) SessionForm
        return sess
Ejemplo n.º 22
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""

        # Fetch current user
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException(
                'Authorization required')
        user_id = getUserId(user)

        # test for Session name in request
        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # Test for websafeConferenceKey in request
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException(
                "Session 'websafeConferenceKey' field required")

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) \
            for field in request.all_fields()}

        # Fetch conference from request
        conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # Check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: \
                %s' % request.websafeConferenceKey)

        # Check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can add sessions.')

        # Convert dates from strings to Date objects
        if data['date']:
            data['date'] = datetime.strptime(
                data['date'][:10], "%Y-%m-%d").date()

        # convert time from strings to Time object
        if data['startTime']:
            data['startTime'] = datetime.strptime(
                data['startTime'][:5], "%H:%M").time()

        # Add speaker to memcache
        speaker =data['speaker']
        websafeConferenceKey =data['websafeConferenceKey']
        taskqueue.add(
            params={
            "speaker": speaker,
            "websafeConferenceKey": websafeConferenceKey}, 
            url="/tasks/set_featured_speaker")


        # Make Session Key from Conference ID as p_key
        p_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        
        # Allocate new Session ID with p_key as parent
        s_id = Session.allocate_ids(size=1, parent=p_key)[0]

        # Make Session key from ID uses p_key 
        # to define parent and s_id as unique id
        s_key = ndb.Key(Session, s_id, parent=p_key)
        data['key'] = s_key
        del data['websafeConferenceKey']

        # Create Session
        Session(**data).put()

        # Send email to organizer confirming creation of Session
        taskqueue.add(
            params={
            'email': user.email(), 
            'sessionInfo': repr(request)}, 
            url='/tasks/send_confirmation_email2')

        # Return request
        return request
Ejemplo n.º 23
0
    def _createSessionObject(self, request):
        """Create a new session object, and if necessary, a new speaker object"""

        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')
        user_id = getUserId(user)

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # get key of the conference where the session will be held
        conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        conf = conf_key.get()

        # check that conference exists
        if not conf:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)

        # check that user is owner
        if user_id != conf.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only the owner can update the conference.')

        # copy SessionForm/ProtoRPC Message into dict
        data = {
            field.name: getattr(request, field.name)
            for field in request.all_fields()
        }

        # If session creator has provided a speaker key, check that it is valid and retrieve
        # his/her name if possible
        # Otherwise create a new speaker (if a speaker name is provided) and assign a a key otherwise continue
        # building the session without a speaker
        if data['websafeSpeakerKey'] is not None:
            try:
                speaker_key = ndb.Key(urlsafe=request.websafeSpeakerKey)
                speaker = speaker_key.get()
                data['speakerName'] = speaker.name
                data['speakerEmail'] = speaker.mainEmail

            except ProtocolBufferDecodeError:
                raise endpoints.NotFoundException(
                    'No speaker found with websafeSpeakerKey: %s. Create a new speaker or enter the key again'
                    % data['websafeSpeakerKey'])

        else:
            # Create a new speaker object if a name is provided in the SessionForm
            if data['speakerName'] is not None:
                speaker = Speaker(name=data['speakerName'],
                                  mainEmail=data['speakerEmail'])
                speaker.put()
                data['websafeSpeakerKey'] = speaker.key.urlsafe()
                speaker.websafeKey = speaker.key.urlsafe()

        # add default values for those missing (both data model & outbound Message)
        for df in SESS_DEFAULTS:
            if data[df] in (None, []):
                data[df] = SESS_DEFAULTS[df]
                setattr(request, df, SESS_DEFAULTS[df])

        # convert Date from string to Date object
        if data['date'] is not None:
            data['date'] = datetime.datetime.strptime(data['date'][:10],
                                                      "%Y-%m-%d").date()

        # convert startTime from string to Time object
        if data['startTime'] is not None:
            data['startTime'] = datetime.datetime.strptime(
                data['startTime'][:], "%H:%M").time()

        # websafeKey only used for return messages
        del data['websafeKey']
        # Assign the new session a conference parent
        data['parent'] = conf_key
        # Create the sesion and put to the database
        sess = Session(**data)
        sess_key = sess.put()

        # update speaker (if necessary) so that this session key will be added to his list of session keys
        if speaker is not None:
            speaker.sessionKeys.append(sess_key)
            speaker.put()

            # Check the speaker's sessions to see if he/she already has a session at the same conference
            # If so, set a featured speaker memcache entry to list all of his or her sessions
            parent_keys = [
                sess_key.parent() for sess_key in speaker.sessionKeys
            ]

            if sess_key.parent() in parent_keys:
                featured_sessions = [
                    sess_key.get() for sess_key in speaker.sessionKeys
                ]
                featured_speaker_string = FEATURED_SPEAKER_TPL % (
                    speaker.name, ', '.join(sess.name
                                            for sess in featured_sessions))
                memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY,
                             featured_speaker_string)

        return self._copySessionToForm(sess)
Ejemplo n.º 24
0
    def _createSessionObject(self, request):
        """Create or update Session object, returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()

        # make sure user is authenticated
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        user_id = getUserId(user)

        # make sure session name is entered
        if not request.name:
            raise endpoints.BadRequestException(
                "Session name field required")

        # make sure websafeConferenceKey is entered
        if not request.websafeConferenceKey:
            raise endpoints.BadRequestException(
                "Session 'websafeConferenceKey' field required")

        conf_key = ndb.Key(urlsafe=request.websafeConferenceKey).get()

        # check if conference exists given websafeConferenceKey
        if not conf_key:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' % request.websafeConferenceKey)

        # Check if user is organizer
        if user_id != conf_key.organizerUserId:
            raise endpoints.ForbiddenException(
                'Only conference organizer can add sessions.')

        # since we use SES_POST_REQUEST, which is a container (combination message)
        # we need to initiate and return SessionForm, as the request and
        # response are of different type
        session = self._copySessionToForm(request)

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name)
                for field in request.all_fields()}

        del data['websafeConferenceKey']

        # convert dates from strings to Date objects
        if data['date']:
            data['date'] = datetime.strptime(
                data['date'][:10], "%Y-%m-%d").date()

        # convert time from strings to time object
        if data['startTime']:
            data['startTime'] = datetime.strptime(
                data['startTime'], "%H:%M").time()

        # generate Conference Key based on Conference ID and
        # websafeConferenceKey key
        c_key = ndb.Key(Conference, request.websafeConferenceKey)
        s_id = Session.allocate_ids(size=1, parent=c_key)[0]
        s_key = ndb.Key(Session, s_id, parent=c_key)
        data['key'] = s_key
        data['organizerUserId'] = user_id
        # set typeOfSession to lowser case
        if data['typeOfSession']:
            data['typeOfSession'] = data['typeOfSession'].lower()

        # save form data to datastore
        Session(**data).put()

        # add a task queue to check if there are multiple sessions by
        # by this speaker in a conference
        taskqueue.add(
            params={'websafeConferenceKey': request.websafeConferenceKey,
                    'speaker': data['speaker']},
            url='/tasks/get_featured_speaker',
            method='GET',
        )

        # create Session & return (modified) SessionForm
        return session
Ejemplo n.º 25
0
 def get_current_stocks(self):
     session = Session()
     stocks = session.query(self.get_stock_class()).filter_by(status=1).all()
     session.expunge_all()
     session.close()
     return stocks
Ejemplo n.º 26
0
    def _createSessionObject(self, request):
        """Create or update Session object, 
        returning SessionForm/request."""
        # preload necessary data items
        user = endpoints.get_current_user()
        if not user:
            raise endpoints.UnauthorizedException('Authorization required')

        if not request.name:
            raise endpoints.BadRequestException(
                "Session 'name' field required")

        # copy SessionForm/ProtoRPC Message into dict
        data = {field.name: getattr(request, field.name) \
            for field in request.all_fields()}
        del data['websafeKey']
        del data['websafeConferenceKey']

        # add default values for those missing (both data model & outbound Message)
        for default in SESSION_DEFAULTS:
            if data[default] in (None, []):
                data[default] = SESSION_DEFAULTS[default]
                setattr(request, default, SESSION_DEFAULTS[default])

        # convert dates from strings to Date objects; set month based on start_date
        if data['startTime']:
            data['startTime'] = datetime.strptime(data['startTime'],
                                                  "%H:%M").time()
        if data['date']:
            data['date'] = datetime.strptime(data['date'][:10],
                                             "%Y-%m-%d").date()

        if data['typeOfSession']:
            # Only take string form of type of session enum
            data['typeOfSession'] = data['typeOfSession'].name

        if not request.speaker:
            q = Speaker.query().filter(Speaker.name == 'Undetermined').get()
            if not q:
                speaker = Speaker(name='Undetermined').put()
                data['speaker'] = speaker
            else:
                data['speaker'] = q.key
        else:
            q = Speaker.query().filter(Speaker.name == request.speaker).get()
            if not q:
                speaker = Speaker(name=request.speaker).put()
                data['speaker'] = speaker
            else:
                data['speaker'] = q.key

        # generate Session Key based on Conference ID
        conference_key = ndb.Key(urlsafe=request.websafeConferenceKey)
        # check that conference exists
        if not conference_key:
            raise endpoints.NotFoundException(
                'No conference found with key: %s' %
                request.websafeConferenceKey)
        session_id = Session.allocate_ids(size=1, parent=conference_key)[0]
        session_key = ndb.Key(Session, session_id, parent=conference_key)
        data['key'] = session_key
        request.conferenceId = request.websafeConferenceKey
        data['conferenceId'] = conference_key

        # create Session, send email to organizer confirming
        # creation of Session & return (modified) SessionForm
        session = Session(**data)
        session.put()

        taskqueue.add(params={
            'urlsafeSpeakerKey': data['speaker'].urlsafe(),
            'urlsafeConferenceKey': conference_key.urlsafe()
        },
                      url='/tasks/feature_speaker')
        return self._copySessionToForm(session)
Ejemplo n.º 27
0
import sys, os

loc = None
try:
    loc, fn = os.path.split(__file__)
except NameError:
    loc = os.getcwd()


sys.path.insert(0, os.path.abspath(os.path.join(loc +"/../artifice")))

from models import usage, resources, tenants, Session, Base
# string = 'postgresql://%(username)s:%(password)s@%(host)s:%(port)s/%(database)s'
# conn_string = string % {'username':'******', 'host':'localhost', 'port':5433, 'password':'******', 'database':'artifice'}

from sqlalchemy import MetaData, create_engine

import os

engine = create_engine( os.environ["DATABASE_URL"] )
Session.configure(bind=engine)

s = Session()

Base.metadata.create_all(engine)
 def __init__(self):
     self.session = Session()
     self.start_date = datetime.datetime.now() - datetime.timedelta(days=80)
Ejemplo n.º 29
0
class TestSQLiteMemory(unittest.TestCase):
    # Database definition (in memory sqlite)
    engine = create_engine('sqlite:///:memory:')
    Session.configure(bind=engine)
    session = Session()

    def setUp(self):
        Base.metadata.create_all(self.engine)

    def tearDown(self):
        self.session.rollback()
        Base.metadata.drop_all(self.engine)

    def testCRUD(self):
        # Insert user
        user1 = User(name='user1', fullname='USER1', password='******')
        self.session.add(user1)
        self.session.commit()

        # Check if inserted
        user = self.session.query(User).filter_by(name='user1').first()
        self.assertEquals(user.name, user1.name)

        # Check for non insertion
        user = self.session.query(User).filter_by(name='userFake').first()
        self.assertTrue(user is None)

        # Check Update
        user = self.session.query(User).filter_by(name='user1').first()
        user.password = '******'
        self.session.commit()
        userTst = self.session.query(User).filter_by(name='user1').first()
        self.assertEquals(userTst.password, 'pwdChg')

        # Check printout (to see this you have to run nosetest --nocapture
        user = self.session.query(User).filter_by(name='user1').first()
        print('User = %s' % user)

        # Insert a second record and check insertion
        user2 = User(name='user2', fullname='USER2', password='******')
        self.session.add(user2)
        self.session.commit()
        user = self.session.query(User).filter_by(name='user2').first()
        self.assertEquals(user.name, user2.name)

        # Rollback test
        user3 = User(name='user3', fullname='USER3', password='******')
        self.session.add(user3)
        self.session.rollback()
        user = self.session.query(User).filter_by(name='user3').first()
        self.assertTrue(user is None)

        # Delete record
        user = self.session.query(User).filter_by(name='user2').first()
        self.session.delete(user)
        self.session.commit()
        self.assertTrue(
            self.session.query(User).filter_by(name='user2').count() == 0)

        # Json format of Data (not working)
        user = self.session.query(User).filter_by(name='user1').first()
Ejemplo n.º 30
0
 def save_current_user(self, user):
     session = Session(self.application.session_store)
     session.data = user.fields()
     session.save()
     self.set_secure_cookie("sid", session.session_id)