コード例 #1
0
def send_mail(to: Union[List, AnyStr],
              template: AnyStr = "",
              data: Dict = None,
              pdf: ByteString = None,
              pdf_name="sample.pdf") -> None:
    """
    This function is used to send an email via Flask-Mail extension.
    :param to: recipients in form of string or list
    :param template: template name
    :param data: data used to render the template in form of dict
    :param pdf: pdf data in form of byte string
    :param pdf_name: name of pdf in form of string
    """

    if not template:
        raise ValueError(ErrorMessage.TEMPLATE_REQUIRED)

    subject = TEMPLATE_SUBJECTS.get(template)
    msg = Message(subject=subject,
                  recipients=[to] if isinstance(to, str) else to)

    try:
        template = render_template(f"email_templates/{template}.html",
                                   data=data)
        msg.html = template
    except TemplateNotFound as err:
        logger.error(ErrorMessage.TEMPLATE_404.format(err))
        raise ValueError(ErrorMessage.GENERIC_ERROR)

    if pdf:
        msg.attach(filename=pdf_name, content_type="application/pdf", data=pdf)

    mailer.send(msg)
    logger.info("Mail Send Successfully")
コード例 #2
0
def init_database():
    """
    This method will create
    the database.
    :return: None
    """
    from app.auth.models import User

    db.create_all()

    try:
        email = TestConstants.TEST_USER_EMAIL
        password = TestConstants.TEST_USER_PASSWORD
        hashed_password = get_hashed_password(password)

        user = User(name=TestConstants.TEST_USER_NAME,
                    email=email,
                    password=hashed_password)

        # Insert user data
        db.session.add(user)

        # Commit changes for user
        db.session.commit()

        yield db  # This is where testing happens

    except Exception as err:
        logger.info(err)
        raise Exception(err)

    finally:
        db.session.remove()
        db.drop_all()
コード例 #3
0
def init_database():
    """
    This method will create
    the database.
    :return: None
    """
    from app.auth.models import User

    db.create_all()

    try:
        email = "*****@*****.**"
        password = "******"
        hashed_password = get_hashed_password(password)

        user1 = User(name="TestUser", email=email, password=hashed_password)

        # Insert user data
        db.session.add(user1)

        # Commit changes for user
        db.session.commit()

        yield db  # This is where testing happens

    except Exception as err:
        logger.info(err)
        raise Exception(err)

    finally:
        db.session.remove()
        db.drop_all()
コード例 #4
0
def init_product() -> None:
    """
    This function will initialize the database for products using MongoDB
    :return: None
    """
    mongodb.test_connection(Item)  # to update in future
    logger.info(DisplayMessage.CONNECTION_SUCCESSFUL.format("MongoDB"))
    logger.info(DisplayMessage.WRITING_SEED_DATA.format(Item.__tablename__))
    items_to_insert = []

    # get data from seed file for products
    item_seed_path = \
        os.path.join(current_app.root_path, "product", "seed.json")
    with open(item_seed_path) as seed_data:
        item_seed_data = json.load(seed_data)
        current_items = item_seed_data.get(Item.__tablename__)

    item_count = Item.objects.count()
    # if seed_script is not running for the first time
    if item_count:
        logger.info(
            DisplayMessage.DATA_ALREADY_EXISTS.format(Item.__tablename__))
    else:
        # if seed script is running for the first time, insert records
        for item in current_items:
            item_instance = Item(**item)
            items_to_insert.append(item_instance)

        # Bulk Insert Records
        Item.objects.bulk_create(items_to_insert, full_clean=True)

        logger.info(
            DisplayMessage.WRITING_SUCCESSFUL.format(Item.__tablename__))
コード例 #5
0
def init_auth() -> None:
    """
    This function will insert seed data for auth_user table in PostgreSQL DB
    :return: None
    """
    # TODO: Move this to __init__ file
    try:
        # Connect to an existing postgreSQL database, otherwise create a new db
        db.engine.connect()
    except OperationalError:
        raise IOError(DisplayMessage.CONNECTION_REFUSED)
    logger.info(DisplayMessage.CONNECTION_SUCCESSFUL.format("PostgreSQL"))

    # create models in database if they doesn't exist
    db.create_all()

    logger.info(DisplayMessage.WRITING_SEED_DATA.format(User.__tablename__))
    auth_records_to_insert = []
    auth_seed_path = os.path.join(current_app.root_path, "auth", "seed.json")
    with open(auth_seed_path) as seed_data:
        auth_seed_data = json.load(seed_data)
        auth_records = auth_seed_data.get(User.__tablename__)
        auth_mails = [record['email'] for record in auth_records]

    # TODO: on increasing tables, make this more generic
    # to accept a list, a query object and return unique values
    query = db.session.query(User)
    existing_records_mail = \
        [*query.filter(User.email.in_(auth_mails)).values('email')]
    existing_records_mail = [email[0] for email in existing_records_mail]

    # iterate over records in JSON
    for record in auth_records:
        if record['email'] not in existing_records_mail:
            encrypted_password = generate_password_hash(record['password'])
            record.update({"password": encrypted_password})
            auth_records_to_insert.append(record)

    # bulk insert
    if auth_records_to_insert:
        db.engine.execute(User.__table__.insert(), auth_records_to_insert)
    logger.info(DisplayMessage.WRITING_SUCCESSFUL.format(User.__tablename__))
コード例 #6
0
def c_add(self, a, c):
    """Dummy task"""
    logger.info(a + c)
    return a + c
コード例 #7
0
def send_mail_async(self, *args):
    """
    Asynchronous task to send mail
    """
    send_mail(*args)
    logger.info("Celery task Send Mail done Successfully")