UCONN

UCONN
UCONN

Translation Emailer

 

Github deploy

git clone https://github.com/4m3r1c4nP13/translate-emailer-app.git

https://github.com/an-d-nguyen/translate-emailer-app















============================================================

main.py

=============================================================


import os

from datetime import date, datetime

 

# Import Sendgrid info

import sendgrid

from sendgrid import SendGridAPIClient

from sendgrid.helpers.mail import Mail, Email, To, Content

 

# Required Flask Libraries

from flask import Flask, request, render_template, redirect, send_from_directory

 

# Import Google Datastore API

from google.cloud import datastore

 

# Import Google Translate API

from google.cloud import translate_v2 as translate

 

# Initialize global variable

translate_client = translate.Client()

client = datastore.Client()

kind = 'Custinfo'

 

# Start Flask app

app = Flask(__name__)

 

# Static directory for css

@app.route('/static/<path:path>')

def send_js(path):

    return send_from_directory('static', path)

 

# Home Page (will show all the customers in the datastore)

@app.route('/', methods=['GET'])

def index():

    query1 = client.query(kind=kind)

    query1.add_filter("Class", "=", "z81")

    query2 = client.query(kind=kind)

    query2.add_filter("Class", "=", "z82")

    class1 = list(query1.fetch())

    class2 = list(query2.fetch())

    return render_template('index.html', class1=class1, class2=class2)

 

 

# Create

@app.route('/create', methods=['POST', 'GET'])

def create():

    if request.method == 'POST':

        data = request.form.to_dict(flat=True)

 

        # Put customer record

        complete_key = client.key(kind, data['Last'])

        customer = datastore.Entity(key=complete_key)

        customer.update({

            'Class': data['Class'],

            'First': data['First'],

            'Last': data['Last'],

            'email': data['email'],

            "lang": data['lang'],

        })

        client.put(customer)

 

        # Redirect to customer page

        return redirect("/read/" + data['Last'])

 

    else:

        # GET - Render customer creation form

        return render_template('create.html')

 

 

# Read

@app.route('/read/<name>', methods=['GET'])

def read(name):

    key = client.key(kind, name)

    customer = client.get(key)

    return render_template('customer.html', first=customer['First'], last=customer['Last'], email=customer['email'],

                           lang=customer['lang'], Class=customer['Class'])

 

 

# Update

@app.route('/update/<name>', methods=['GET', 'POST'])

def update(name):

    if request.method == 'POST':

        data = request.form.to_dict(flat=True)

 

        key = client.key(kind, name)

        customer = client.get(key)

 

        customer['Class'] = data['Class']

        customer['email'] = data['email']

        customer['lang'] = data['lang']

        client.put(customer)

 

        # Redirect to customer page

        return redirect("/read/" + name)

 

    else:

        # Get customer data

        key = client.key(kind, name)

        customer = client.get(key)

 

        # Renders update page with existing data

        return render_template('update.html', first=customer['First'], email=customer['email'], lang=customer['lang'],

                               last=customer['Last'], Class=customer['Class'])

 

 

# Delete

@app.route('/delete/<name>', methods=['GET'])

def delete(name):

    # Delete Customer Record

    key = client.key(kind, name)

    client.delete(key)

 

    # Redirect to index page

    return redirect('/')

 

 

#Compose Message - GET

@app.route('/compose', methods=['GET'])

def compose():

    return render_template('compose.html')

 

 

#Compose Message - POST

@app.route('/compose-message', methods=['POST'])

def compose_message():

    data = request.form.to_dict(flat=True)

    sendEmail(data)

    return redirect('/')

 

def sendEmail(data):

    sg = sendgrid.SendGridAPIClient('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')

    from_email = Email('jiacovacci@hotmail.com', 'John Iacovacci - john.iacovacci1@gmail.com')

    subject_input = data['subject']

    message_input = data['message']

    now = datetime.now().strftime("%m/%d/%Y, %I:%M %p")

    Class = data['Class']

 

    query1 = client.query(kind=kind)

    query1.add_filter("Class", "=", "z81")

    query2 = client.query(kind=kind)

    query2.add_filter("Class", "=", "z82")

    if Class == 'z81':

        results = list(query1.fetch())

    elif Class == 'z82':

        results = list(query2.fetch())

    else:

        results = list()

 

    for contact in results:

        lang = contact['lang']

        langw = "English"

        if lang == 'en':

            langw = 'English'

        elif lang == 'de':

            langw = "German"

        elif lang == 'fr':

            langw = "French"

        elif lang == 'es':

            langw = "Spanish"

        elif lang == 'it':

            langw = "Italian"

        elif lang == 'hi':

            langw = "Hindi"

        header1 = f"Your assigned language is: {langw}"

        header2 = "Classroom blog: http://uconnstamfordslp.blogspot.com/"

 

        subject = f"{subject_input}, {now}, {langw}"

 

        # Translate subject and message of email

        subject = translate_client.translate(subject, target_language=lang)['translatedText']

 

        header1 = translate_client.translate(header1, target_language=lang)['translatedText']

        header2 = translate_client.translate(header2, target_language=lang)['translatedText']

        now = translate_client.translate(now, target_language=lang)['translatedText']

        message_input = translate_client.translate(message_input, target_language=lang)['translatedText']

 

        message = f"{header1}\n" \

                  f"{header2}\n" \

                  f"\n{now}\n\n" \

                  f"{message_input}"

 

        to_email = contact['email']

        content = Content("text/plain", message)

 

        mail = Mail(from_email, to_email, subject, content)

        mail.reply_to = 'john.iacovacci1@gmail.com'

        mail_json = mail.get()

 

        # Send an HTTP POST request to /mail/send

        response = sg.client.mail.send.post(request_body=mail_json)

 

        # For debugging

        print(response.status_code)

 

#---------------------------------

 

# Server listening on port 8080

if __name__ == '__main__':

    app.run(host='127.0.0.1', port=8080, debug=True)

=====================================================================

Requirements.txt

=====================================================================

Flask>=1.1.1

google-cloud-datastore

Google-cloud-translate

PyYAML>=4.2b1

python-http-client>=3.2.1

six==1.11.0

pytest==3.8.2

starkbank-ecdsa>=1.0.0

sendgrid==v6.0.0

=============================================================================

App.yaml

=================================================================================

runtime: python37

==============================================================================

 

templates 

 

compose.html

=================================================================================

<!DOCTYPE html>

<html lang="en">


<head>

    <title>Compose</title>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="/static/style.css">


</head>


<body>

  

    {# NavBar #}

    <nav class="navbar">

    <a class="navbar-brand" href="/">Customers</a>

    <a href="/create">Add Customer</a>

    <a href="/compose">Compose</a>

    </nav>


    <form action="/compose-message" method="POST">

        <div>

            <label for="Class">Class</label>

            <select class="form-control" id="Class" name="Class">

                <option value="z81" selected>z81</option>

                <option value="z82">z82</option>

            </select>

        </div>

        <div>

            <label for="subject">Subject: </label>

            <input type="text" name="subject" id="subject" value="{{subject}}">

        </div>

        <br>

        <div>

            <label for="message">Message: </label>

            <textarea id="message" name="message" width="30">{{message}}</textarea>

        </div>

        <br>

        <button type="submit">Send Email!</button>

    </form>


</body>

</html>

========================================================================

create.html

========================================================================

<!DOCTYPE html>

<html lang="en" dir="ltr">

<head>

    <title>Translate Application</title>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="/static/style.css">

</head>

<body>



{# NavBar #}


<nav class="navbar">

    <a class="navbar-brand" href="/">Customers</a>

</nav>



{# Create user form #}

<section>

    <form method="post" action="/create">

        <div>

            <label for="First">First Name</label>

            <input type="text" class="form-control" id="First" name="First" required>

        </div>

        <br>

        <div>

            <label for="Last">Last Name</label>

            <input type="text" class="form-control" id="Last" name="Last" required>

            <br>

            <small class="form-text text-muted">This is the primary key for the customer. It must be unique.</small>

        </div>

        <br>

        <div>

            <label for="email">Email</label>

            <input type="email" class="form-control" id="email" name="email" required>

        </div>

        <br>

        <div>

            <label for="Class">Class</label>

            <select class="form-control" id="Class" name="Class">

                <option value="z81" selected>z81</option>

                <option value="z82">z82</option>

            </select>

        </div>

        <br>

        <div>

            <label for="lang">Translation Language</label>

            <select class="form-control" id="lang" name="lang">

                <option value="en" selected>English</option>

                <option value="es">Spanish</option>

                <option value="fr">French</option>

                <option value="de">German</option>

                <option value="it">Italian</option>

                <option value="hi">Hindi</option>

            </select>

        </div>

        <br>

        <button type="submit" class="btn btn-primary">Submit</button>


    </form>


</section>


</body>


</html>

============================================================================

customer.html

============================================================================

 

<!DOCTYPE html>


<html lang="en">


<head>


    <title>CRUD Example - Customer</title>


    <meta charset="utf-8">


    <meta name="viewport" content="width=device-width, initial-scale=1">


    <link rel="stylesheet" href="/static/style.css">


    <script src="/static/main.js"></script>


</head>


<body>


 


 


{# NavBar #}


<nav class="navbar">


    <a class="navbar-brand" href="/">Customers</a>


    <a href="/create">Add Customer</a>


</nav>


 


{# Customer Options #}


<section>


    <div class="container">


        <ul>

            <div>

                <li><a href="/update/{{ last }}">Update</a></li>

            </div>

            <div>

                <li><a href="/delete/{{ last }}">Delete</a></li>

            </div>

        </ul>


    </div>


</section>


 


{# Customer info #}


<section>

    First Name: {{ first }} <br>

    Last Name: {{ last }} <br>

    Email: {{ email }} <br>

    Lang: {{ lang }} <br>

    Class: {{ Class }} <br>

</section>



</body>


</html>


 

==============================================================================

index.html

=============================================================================

<!DOCTYPE html>

<html lang="en">

<head>


    <title>Email Translation</title>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="/static/style.css">


</head>


<body>




{# NavBar #}


<nav class="navbar">


    <a class="navbar-brand" href="/">Customers</a>


    <a href="/create">Add Customer</a>


    <a href="/compose">Compose</a>


</nav>




{# Customer List #}


<section>

    <h2>Section Z81</h2>

    <ul>

    {# Customer.name is the item in list we display for selection #}

    {% for student in class1 %}

        <li><a href="/read/{{ student.Last }}">{{ student.First }} {{ student.Last }}</a></li>

    {% else %}

        <li>You have no customers yet. Click <a href="/create">here</a> or "Add Customer" in the navbar to create one.</li>

    {% endfor %}

    </ul>

    <br>

    <h2>Section Z82</h2>

    <ul>

        {# Customer.name is the item in list we display for selection #}

        {% for student in class2 %}

            <li><a href="/read/{{ student.Last }}">{{ student.First }} {{ student.Last }}</a></li>

        {% else %}

            <li>You have no customers yet. Click <a href="/create">here</a> or "Add Customer" in the navbar to create one.</li>

        {% endfor %}

    </ul>

</section>




</body>



</html>


========================================================================

update.html

=======================================================================

<!DOCTYPE html>


<html lang="en">


<head>


    <title>CRUD Example - Update Customer</title>


    <meta charset="utf-8">


    <meta name="viewport" content="width=device-width, initial-scale=1">


    <link rel="stylesheet" href="/static/style.css">


</head>


<body>




{# NavBar #}


<nav class="navbar">


    <a class="navbar-brand" href="/">Customers</a>


    <a href="/create">Add Customer</a>


</nav>



{# Update user form #}


<section>


    <form method="post" action="/update/{{ last }}">

        <div>

            <label for="First">First Name</label>

            <input type="text" class="form-control" id="First" name="First" disabled value="{{ first }}">

        </div>

        <br>

        <div>

            <label for="Last">Last Name</label>

            <input type="text" class="form-control" id="Last" name="Last" disabled value="{{ last }}">

            <br>

            <small class="form-text text-muted">This is the primary key for the customer. It should not be changed.</small>

        </div>

        <br>

        <div>

            <label for="email">Email</label>

            <input type="email" class="form-control" id="email" name="email" value="{{ email }}">

        </div>

        <br>

        <div>

            <label for="Class">Class</label>

            <select class="form-control" id="Class" name="Class">

                <option value="z81" {% if Class == "z81" %}selected{% endif %}>z81</option>

                <option value="z82" {% if Class == "z82" %}selected{% endif %}>z82</option>

            </select>

        </div>

        <br>

        <div>

            <label for="lang">Language</label>

            <select class="form-control" id="lang" name="lang">

                <option value="en" {% if lang == "en" %}selected{% endif %}>English</option>

                <option value="es" {% if lang == "es" %}selected{% endif %}>Spanish</option>

                <option value="fr" {% if lang == "fr" %}selected{% endif %}>French</option>

                <option value="de" {% if lang == "de" %}selected{% endif %}>German</option>

                <option value="it" {% if lang == "it" %}selected{% endif %}>Italian</option>

                <option value="hi" {% if lang == "hi" %}selected{% endif %}>Hindi</option>

            </select>

        </div>

        <br>

        <button type="submit" class="btn btn-primary">Submit</button>

    </form>


</section>




</body>


</html>

========================================================================


static


style.css


======================================================================


html {

    color: red;

}


.none {

    display: none;

}


li {

    font-size: 20px;

}


No comments:

Post a Comment

Disable Billing

Search for Billing Manage billing accounts Go to MYPROJECTS CLICK ON THE 3 BUTTON Actions Then hit disable