-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
81 lines (73 loc) · 2.45 KB
/
Copy pathapp.py
File metadata and controls
81 lines (73 loc) · 2.45 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
"""
Flask API Application
"""
from flask import Flask, jsonify, request
from flasgger import Swagger, swag_from, LazyString, LazyJSONEncoder
from db import create_connection, insert_dictionary_to_db, insert_result_to_db, show_cleansing_result
from cleansing_function import text_cleansing
# Prevent sorting keys in JSON response
import flask
flask.json.provider.DefaultJSONProvider.sort_keys = False
# Set Up Database
db_connection = create_connection()
insert_dictionary_to_db(db_connection)
db_connection.close()
# Initialize flask application
app = Flask(__name__)
# Assign LazyJSONEncoder to app.json_encoder for swagger UI
app.json_encoder = LazyJSONEncoder
# Create Swagger Config & Swagger template
swagger_template = {
"info": {
"title": LazyString(lambda: "Text Cleansing API"),
"version": LazyString(lambda: "1.0.0"),
"description": LazyString(lambda: "Dokumentasi API untuk membersihkan text")
},
"host": LazyString(lambda: request.host)
}
swagger_config = {
"headers": [],
"specs": [
{
"endpoint": 'docs',
"route": '/docs.json',
}
],
"static_url_path": "/flasgger-static",
"swagger_ui": True,
"specs_route": "/docs/"
}
# Initialize Swagger from swagger template & config
swagger = Swagger(app, template=swagger_template, config=swagger_config)
#Homepage
@swag_from('docs/home.yml', methods=['GET'])
@app.route('/', methods=['GET'])
def home():
welcome_msg = {
"version": "1.0.0",
"message": "Welcome to Flask API",
"author": "Amanda Risfa"
}
return jsonify(welcome_msg)
# Show cleansing result
@swag_from('docs/show_cleansing_result.yml', methods=['GET'])
@app.route('/show_cleansing_result', methods=['GET'])
def show_cleansing_result_api():
db_connection = create_connection()
cleansing_result = show_cleansing_result(db_connection)
return jsonify(cleansing_result)
# Cleansing text using form
@swag_from('docs/cleansing_form.yml', methods=['POST'])
@app.route('/cleansing_form', methods=['POST'])
def cleansing_form():
# Get text from input user
raw_text = request.form["raw_text"]
# Cleansing text
clean_text = text_cleansing(raw_text)
result_response = {"raw_text": raw_text, "clean_text": clean_text}
# Insert result to database
db_connection = create_connection()
insert_result_to_db(db_connection, raw_text, clean_text)
return jsonify(result_response)
if __name__ == '__main__':
app.run()