-
Notifications
You must be signed in to change notification settings - Fork 574
Expand file tree
/
Copy pathmain.py
More file actions
88 lines (67 loc) · 2.6 KB
/
main.py
File metadata and controls
88 lines (67 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# Copyright 2019 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" This web app shows translations that have been previously requested, and
provides a form to request a new translation.
"""
# [START getting_started_background_app_main]
import json
import os
from flask import Flask, redirect, render_template, request
from google.cloud import firestore, pubsub
from markupsafe import escape
app = Flask(__name__)
# Get client objects to reuse over multiple invocations
db = firestore.Client()
publisher = pubsub.PublisherClient()
# Keep this list of supported languages up to date
ACCEPTABLE_LANGUAGES = ("de", "en", "es", "fr", "ja", "sw")
# [END getting_started_background_app_main]
# [START getting_started_background_app_list]
@app.route("/", methods=["GET"])
def index():
"""The home page has a list of prior translations and a form to
ask for a new translation.
"""
doc_list = []
docs = db.collection("translations").stream()
for doc in docs:
doc_list.append(doc.to_dict())
return render_template("index.html", translations=doc_list)
# [END getting_started_background_app_list]
# [START getting_started_background_app_request]
@app.route("/request-translation", methods=["POST"])
def translate():
"""Handle a request to translate a string (form field 'v') to a given
language (form field 'lang'), by sending a PubSub message to a topic.
"""
source_string = request.form.get("v", "")
to_language = escape(request.form.get("lang", ""))
if source_string == "":
return "Invalid request, you must provide a value.", 400
if to_language not in ACCEPTABLE_LANGUAGES:
return f"Unsupported language: {to_language}", 400
message = {
"Original": source_string,
"Language": to_language,
"Translated": "",
"OriginalLanguage": "",
}
topic_name = (
f"projects/{os.getenv('GOOGLE_CLOUD_PROJECT')}/topics/translate"
)
publisher.publish(
topic=topic_name, data=json.dumps(message).encode("utf-8")
)
return redirect("/")
# [END getting_started_background_app_request]