|
| 1 | +import requests, os, uuid, json |
| 2 | +from dotenv import load_dotenv |
| 3 | +load_dotenv() |
| 4 | + |
1 | 5 | from datetime import datetime |
2 | 6 | from flask import Flask, render_template |
3 | 7 | from . import app |
|
6 | 10 | def home(): |
7 | 11 | return render_template("home.html") |
8 | 12 |
|
9 | | -@app.route("/translator/") |
| 13 | +@app.route("/translator/", methods=['GET']) |
10 | 14 | def translator(): |
11 | 15 | return render_template("translator.html") |
12 | 16 |
|
| 17 | +@app.route('/translator/', methods=['POST']) |
| 18 | +def translator_post(): |
| 19 | + # Read the values from the form |
| 20 | + original_text = request.form['text'] |
| 21 | + target_language = request.form['language'] |
| 22 | + |
| 23 | + # Load the values from .env |
| 24 | + key = os.environ['KEY'] |
| 25 | + endpoint = os.environ['ENDPOINT'] |
| 26 | + location = os.environ['LOCATION'] |
| 27 | + |
| 28 | + # Indicate that we want to translate and the API version (3.0) and the target language |
| 29 | + path = '/translate?api-version=3.0' |
| 30 | + # Add the target language parameter |
| 31 | + target_language_parameter = '&to=' + target_language |
| 32 | + # Create the full URL |
| 33 | + constructed_url = endpoint + path + target_language_parameter |
| 34 | + |
| 35 | + # Set up the header information, which includes our subscription key |
| 36 | + headers = { |
| 37 | + 'Ocp-Apim-Subscription-Key': key, |
| 38 | + 'Ocp-Apim-Subscription-Region': location, |
| 39 | + 'Content-type': 'application/json', |
| 40 | + 'X-ClientTraceId': str(uuid.uuid4()) |
| 41 | + } |
| 42 | + |
| 43 | + # Create the body of the request with the text to be translated |
| 44 | + body = [{ 'text': original_text }] |
| 45 | + |
| 46 | + # Make the call using post |
| 47 | + translator_request = requests.post(constructed_url, headers=headers, json=body) |
| 48 | + # Retrieve the JSON response |
| 49 | + translator_response = translator_request.json() |
| 50 | + # Retrieve the translation |
| 51 | + translated_text = translator_response[0]['translations'][0]['text'] |
| 52 | + |
| 53 | + # Call render template, passing the translated text, |
| 54 | + # original text, and target language to the template |
| 55 | + return render_template( |
| 56 | + 'translator_results.html', |
| 57 | + translated_text=translated_text, |
| 58 | + original_text=original_text, |
| 59 | + target_language=target_language |
| 60 | + ) |
| 61 | + |
13 | 62 | @app.route("/about/") |
14 | 63 | def about(): |
15 | 64 | return render_template("about.html") |
|
0 commit comments