Esempio n. 1
0
def get_stock_code_list(market):

    t = Calendar.today()
    obj = BaseModel('daily_stocks')
    # obj.insert({'a':'a'})
    sql = {'date': t, 'market': market['id']}
    curror = obj.query(sql)
    if curror.count() == 0:
        stock_list = []
        flag = True
        while flag:
            err, stock_counts = data_client.GetSecurityCount(market['id'])
            loop_time = stock_counts // 1000
            for loop in range(loop_time + 1):
                err, stock_count, result = data_client.GetSecurityList(
                    market['id'], loop * 1000)
                r_list = result.split('\n')
                for r in r_list:
                    xcode = r.split('\t')[0]
                    rrrrr = market['filter'](xcode)
                    if rrrrr:
                        stock_list.append(xcode)
            flag = len(stock_list) == 0
        obj.insert({
            'date': t,
            'market': market['id'],
            'stock_list': stock_list
        })
        print(stock_list)
        return stock_list
    else:
        data = pd.DataFrame(list(curror))
        return data.stock_list.tolist()[0]
def upgrade() -> None:
    session = Session(bind=op.get_bind())
    BaseModel.set_session(session)
    # ### commands auto generated by Alembic - please adjust! ###
    provider = Provider.all()[0]
    collection = seed_initial_collection(provider.uuid)
    seed_initial_items(collection.uuid)
Esempio n. 3
0
def get_db() -> None:
    try:
        session = AsyncSessionLocal
        with session.no_autoflush as s:
            BaseModel.set_session(s)
    except Exception as e:
        print(e)
        raise e
Esempio n. 4
0
def override_get_db():
    try:
        session = test_db_session
        with session.no_autoflush as s:
            BaseModel.set_session(s)
    except Exception as e:
        print(e)
        raise e
Esempio n. 5
0
def db() -> Generator:
    print("db")
    if not database_exists(settings.SQLALCHEMY_DATABASE_URI):
        create_database(settings.SQLALCHEMY_DATABASE_URI)
    test_db_engine.execute("CREATE EXTENSION IF NOT EXISTS postgis")
    test_db_engine.execute("CREATE EXTENSION IF NOT EXISTS pgcrypto")
    BaseModel.metadata.drop_all(bind=test_db_engine)
    BaseModel.metadata.create_all(bind=test_db_engine)
    BaseModel.set_session(test_db_session)
    yield test_db_session
Esempio n. 6
0
 def shows(self, user, speaker_id):
     response = ResponseBuilder()
     speaker = db.session.query(Speaker).filter_by(id=speaker_id).first()
     if user['role_id'] is ROLE['user']:
         speaker_document = db.session.query(SpeakerDocument).filter_by(
             speaker_id=speaker_id,
             is_used=1).order_by(SpeakerDocument.created_at.desc()).all()
     elif user['role_id'] is ROLE['speaker']:
         speaker_document = db.session.query(SpeakerDocument).filter_by(
             speaker_id=speaker_id).order_by(
                 SpeakerDocument.created_at.desc()).all()
     _results = []
     if speaker_document is not None:
         speaker_document = BaseModel.as_list(speaker_document)
         for _speaker_document in speaker_document:
             _speaker_document['material'] = Helper().url_helper(
                 _speaker_document['material'],
                 app.config['GET_SPEAKER_DOC_DEST'])
             _speaker_document['user'] = speaker.user.include_photos(
             ).as_dict()
             _results.append(_speaker_document)
         return response.set_data(_results).build()
     else:
         data = 'data not found'
         return response.set_data(None).set_message(data).build()
Esempio n. 7
0
    def run():
        """
        Create 6 orders seeds
        """

        orders = BaseModel.as_list(db.session.query(Order).all())
        ticketid = [2, 3, 3, 4, 1, 5]

        ticketprice = [200000, 300000, 300000, 350000, 400000, 0]

        for i in range(0, 6):
            order_id = random.choice(orders)['id']
            ticket_id = ticketid[i]
            ticket_price = ticketprice[i]
            # ticket = random.choice(tickets)
            # tickets['id']
            # ticket_id = ticket['id']
            # ticket_price = ticket['price']
            new_orderdetails = OrderDetails()
            new_orderdetails.ticket_id = ticket_id
            new_orderdetails.order_id = order_id
            # Order one or two tickets per order per ticket_id
            new_orderdetails.count = random.randint(1, 2)
            new_orderdetails.price = ticket_price
            db.session.add(new_orderdetails)
            db.session.commit()
Esempio n. 8
0
 def show(self, user_id):
     user_tickets = BaseModel.as_list(
         db.session.query(UserTicket).filter_by(user_id=user_id).all())
     if user_tickets is not None:
         return user_tickets
     else:
         data = 'data not found'
         return {'error': True, 'data': data}
def seed_initial_user():
    session = Session(bind=op.get_bind())
    BaseModel.set_session(session)
    provider = Provider.create(name="fpx")
    password = None
    try:
        password = os.environ["FIRST_SUPERUSER_PASSWORD"].encode("utf-8")
    except KeyError:
        print("You must set env variable USER_PASSWORD!!!")
        exit()

    user = User.create(
        email=os.environ.get("FIRST_SUPERUSER", "*****@*****.**"),
        provider_uuid=provider.uuid,
        password=bcrypt.hashpw(password, bcrypt.gensalt()).decode("utf-8"),
    )
    print("Your master user token: " + create_access_token(str(user.uuid)))
Esempio n. 10
0
 def transformTable(self, obj):
     transferslogs = BaseModel.as_list(obj)
     for entry in transferslogs:
         for key in entry.keys():
             if key in ['receiver', 'sender']:
                 temp_dict = entry[key].as_dict()
                 entry[key] = temp_dict
                 continue
     return transferslogs
Esempio n. 11
0
    def self_gallery(self, booth_id):
        response = ResponseBuilder()
        booth_galleries = BaseModel.as_list(db.session.query(BoothGallery).filter_by(booth_id=booth_id).all())
        if booth_galleries is not None:
            for booth_gallery in booth_galleries:
                booth_gallery = booth_gallery
                booth_gallery['url'] = Helper().url_helper(booth_gallery['url'], current_app.config['GET_DEST'])

            return response.set_data(booth_galleries).set_message('data retieved successfully').build()
        else:
            return response.set_error(True).set_data(None).set_message('data not found').build()
Esempio n. 12
0
 def index(self):
     response = ResponseBuilder()
     booth_galleries = BaseModel.as_list(db.session.query(BoothGallery).all())
     if booth_galleries is not None:
         for booth_gallery in booth_galleries:
             booth_gallery = booth_gallery
             booth_id = booth_gallery['booth_id']
             booth_gallery['url'] = Helper().url_helper(booth_gallery['url'], current_app.config['GET_DEST'])
     booth = db.session.query(Booth).filter_by(id=booth_id).first().as_dict()
     booth['logo_url'] = Helper().url_helper(booth['logo_url'], current_app.config['GET_DEST']) if booth['logo_url'] else "https://museum.wales/media/40374/thumb_480/empty-profile-grey.jpg"
     return response.set_data(booth_galleries).set_message('data retrieved successfully').set_included(booth).build()
    def transfer_point_log(request, user):
        if user['role_id'] == 1:
            # admin
            result = pointtransactionservice.get_admin_log()
        elif user['role_id'] == 7:
            # attendee
            result = pointtransactionservice.get_user_log(user['id'])
        elif user['role_id'] == 3:
            # booth
            result = pointtransactionservice.get_booth_log(user['id'])

        return BaseController.send_response_api(BaseModel.as_list(result),
                                                'logs retrieved succesfully')
Esempio n. 14
0
    def test_base_model_delete_method(self):

        with patch("app.models.base_model.db.session") as mock_db:
            mock_delete = MagicMock(return_value=None)
            mock_commit = MagicMock(return_value=None)

            mock_db.delete = mock_delete
            mock_db.commit = mock_commit

            BaseModel().delete()

            mock_delete.assert_called_once()
            mock_commit.assert_called_once()
Esempio n. 15
0
 def show(self, speaker):
     response = ResponseBuilder()
     speaker_document = db.session.query(SpeakerDocument).filter_by(
         speaker_id=speaker['id']).order_by(
             SpeakerDocument.created_at.desc()).all()
     if speaker_document is not None:
         speaker_document = BaseModel.as_list(speaker_document)
         for _speaker_document in speaker_document:
             _speaker_document['material'] = Helper().url_helper(
                 _speaker_document['material'],
                 app.config['GET_SPEAKER_DOC_DEST'])
             user = db.session.query(User).filter_by(
                 id=speaker['user_id']).first().include_photos().as_dict()
             _speaker_document['user'] = user
         return response.set_data(speaker_document).build()
     else:
         data = 'data not found'
         return response.set_message(data).set_data(None).build()
Esempio n. 16
0
    def run():
        """
        Create 4 Payments seeds
        """

        transaction_statuses = ['capture', 'authorize', 'deny']
        statuses = ['accept', 'challenge', 'deny']
        payment_types = ['bank_transfer', 'credit_card']
        banks = ['bri', 'bni', 'permata', 'maybank', 'mandiri', 'bca', 'cimb']
        range_start = 10**(7 - 1)
        range_end = (10**7) - 1
        orders = BaseModel.as_list(db.session.query(Order).all())
        for i in range(0, 4):
            order_id = choice(orders)['id']
            saved_token_id = randint(range_start, range_end)
            transaction_id = randint(range_start, range_end)
            gross_amount = randint(range_start, range_end)
            transaction_time = datetime.datetime.now()

            transaction_status = transaction_statuses[randint(0, 2)]
            masked_card = randint(range_start, range_end)
            payment_type = payment_types[randint(0, 1)]
            bank = banks[randint(0, 6)]
            fraud_status = statuses[randint(0, 2)]

            new_payment = Payment()
            new_payment.order_id = order_id
            new_payment.saved_token_id = saved_token_id
            new_payment.transaction_id = transaction_id
            new_payment.gross_amount = gross_amount
            new_payment.transaction_time = transaction_time
            new_payment.transaction_status = transaction_status
            new_payment.masked_card = masked_card
            new_payment.payment_type = payment_type
            new_payment.bank = bank
            new_payment.fraud_status = fraud_status
            db.session.add(new_payment)
            db.session.commit()
Esempio n. 17
0
	def index():
		newsletters = newsletterservice.get()
		return BaseController.send_response_api(BaseModel.as_list(newsletters), 'newsletters retrieved successfully')
def downgrade() -> None:
    session = Session(bind=op.get_bind())
    BaseModel.set_session(session)
    Item.query.delete()
    Collection.query.delete()
Esempio n. 19
0
 def get(self):
     user_photos = BaseModel.as_list(db.session.query(UserPhoto).all())
     for user_photo in user_photos:
         user_photo['url'] = Helper().url_helper(user_photo['url'], current_app.config['GET_DEST'])
     return user_photos
Esempio n. 20
0
 def get_logs(self, id):
     response = ResponseBuilder()
     logs = db.session.query(SponsorInteractionLog).filter_by(
         sponsor_id=id).all()
     return response.set_data(BaseModel.as_list(logs)).build()
Esempio n. 21
0
from app.models.base_model import BaseModel
from app.query_str_analyzer import analyzer
import pandas as pd
sql = analyzer('date = {}'.format(20180620))
# sql['time']={'$lte':955}
# data=BaseModel('tmp_kline_min5').remove(sql)
data = BaseModel('kline_min5').query(sql)
data = pd.DataFrame(list(data))
d = data.to_dict(orient='records')
BaseModel('tmp_kline_min5').insert_batch(d)
Esempio n. 22
0
	def index():
		stages = stageservice.get()
		return BaseController.send_response_api(BaseModel.as_list(stages), 'stages retrieved successfully')
Esempio n. 23
0
 def get(self):
     response = ResponseBuilder()
     invoices = db.session.query(Invoice).all()
     return response.set_data(BaseModel.as_list(invoices)).set_message(
         'invoices retrieved successfully').build()