Advertisement
Kostiggig

Server for TranslatorApp(https://github.com/KostyaGig/TranslatorApp). Written with python + Flask

Nov 3rd, 2021
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.77 KB | None | 0 0
  1. import json
  2. import string
  3. import random
  4.  
  5. from flask import Flask, jsonify, request
  6. from deep_translator import GoogleTranslator
  7. from flask_sqlalchemy import SQLAlchemy
  8.  
  9. app = Flask(__name__)
  10. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///employee.db'
  11. db = SQLAlchemy(app)
  12.  
  13. # region translate logic
  14. SUCCESS_MARK = "Success"
  15. FAILURE_MARK = "Failure"
  16.  
  17. RU_LANGUAGE = "ru"
  18. EN_LANGUAGE = "en"
  19.  
  20. @app.route('/translate/<string:src_word>')
  21. def translate(src_word):
  22. try:
  23. if isEmpty(src_word):
  24. return responseAsJson("Field not will be empty", FAILURE_MARK, "", "", "", "")
  25. else:
  26. translator_word = GoogleTranslator(source='auto', target='en').translate(src_word)
  27. return responseAsJson("", SUCCESS_MARK, RU_LANGUAGE, EN_LANGUAGE, src_word, translator_word)
  28. except Exception as e:
  29. if isEmpty(src_word):
  30. return responseAsJson("Field not will be empty", FAILURE_MARK, "", "", "", "")
  31. else:
  32. errorMessage = e.message
  33. return responseByErrorMessage(errorMessage)
  34.  
  35.  
  36. def isEmpty(src):
  37. if src == "\"\"":
  38. return True
  39. else:
  40. return False
  41.  
  42.  
  43. def responseAsJson(message, mark, fromLanguage, toLanguage, srcWord, translatorWord):
  44. return jsonify({
  45. "message": message,
  46. "mark": mark,
  47. "fromLanguage": fromLanguage,
  48. "toLanguage": toLanguage,
  49. "srcWord": srcWord,
  50. "translatorWord": translatorWord
  51. })
  52.  
  53.  
  54. def responseByErrorMessage(message):
  55. if message == "text must be a valid text with maximum 5000 character, otherwise it cannot be translated":
  56. return responseAsJson("Not correctly entered word", FAILURE_MARK, "", "", "", "")
  57. else:
  58. return responseAsJson("Cannot be translated", FAILURE_MARK, "", "", "", "")
  59. # endregion
  60.  
  61. # region db model
  62. class Employee(db.Model):
  63.  
  64. id = db.Column(db.Integer(), primary_key=True)
  65. user_unique_key = db.Column(db.String(100), unique=True)
  66. user_name = db.Column(db.String(20), unique=False)
  67. number_phone = db.Column(db.String(20), unique=True)
  68. words = db.relationship('Word', backref='owner', lazy=True)
  69.  
  70. def __init__(self, user_unique_key, user_name, number_phone):
  71. self.user_name = user_name
  72. self.user_unique_key = user_unique_key
  73. self.number_phone = number_phone
  74.  
  75. def __repr__(self):
  76. return '<User %r>' % self.username
  77.  
  78. class Word(db.Model):
  79. id = db.Column(db.Integer, primary_key=True)
  80. user_id = db.Column(db.Integer, db.ForeignKey('employee.id'))
  81. src = db.Column(db.String(100), unique=False)
  82. translated = db.Column(db.String(100), unique=False)
  83. # endregion
  84.  
  85. # region auth
  86. @app.route('/')
  87. def index():
  88. return "default page"
  89.  
  90. @app.route('/login/<string:unique_key>')
  91. def login_by_unique_key(unique_key):
  92. try:
  93. db.create_all()
  94. db.session.commit()
  95. if Employee.query.filter_by(user_unique_key=unique_key).count() >= 1:
  96. return "Success login to account!"
  97. else:
  98. return "You not registered in system yet!"
  99. except Exception as e:
  100. return "Login user happened error: " + str(e)
  101.  
  102.  
  103. USER_NAME_KEY = 'userName'
  104. NUMBER_PHONE_KEY = 'userNumberPhone'
  105.  
  106. @app.route('/login', methods=['POST'])
  107. def login_by_number_phone_and_password():
  108. try:
  109. db.create_all()
  110. db.session.commit()
  111. user_name = request.args.get(USER_NAME_KEY)
  112. user_number_phone = request.args.get(NUMBER_PHONE_KEY)
  113. if db.session.query(Employee).filter_by(number_phone=user_number_phone).count() < 1:
  114. return "User with number " + user_number_phone + " not found!"
  115. else:
  116. user = Employee.query.filter_by(number_phone=user_number_phone).one()
  117. if user.user_name != user_name or user.number_phone != user_number_phone:
  118. return "Incorrect number or name user unique key " + user.user_unique_key
  119. else:
  120. return "Success login by number and phone, your unique key " + user.user_unique_key
  121. except Exception as e:
  122. return "Login by number and phone happened error " + str(e)
  123.  
  124.  
  125. @app.route('/register', methods=['POST'])
  126. def register():
  127. try:
  128. db.create_all()
  129. db.session.commit()
  130. user_name = request.args.get(USER_NAME_KEY)
  131. user_number_phone = request.args.get(NUMBER_PHONE_KEY)
  132. if db.session.query(Employee).filter_by(number_phone=user_number_phone).count() < 1:
  133. unique_key = generate_unique_key()
  134. user = Employee(user_unique_key=unique_key, user_name=user_name, number_phone=user_number_phone)
  135. db.session.add(user)
  136. db.session.commit()
  137. return "Success register user in system!"
  138. else:
  139. return "User with number phone" + user_number_phone + ' already exist!'
  140. except Exception as e:
  141. db.session.rollback()
  142. return "Register user happened error " + str(e)
  143.  
  144. def generate_unique_key():
  145. return ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
  146. # endregion
  147.  
  148. # region user communication
  149.  
  150. @app.route('/addUser')
  151. def add_user():
  152. db.create_all()
  153. db.session.commit()
  154. user = Employee(user_unique_key="1234", user_name="Egor", number_phone="1234")
  155. db.session.add(user)
  156. db.session.commit()
  157. added_user = Employee.query.filter_by(number_phone='1234').one()
  158. return 'Read added user here name ' + added_user.user_name
  159.  
  160. @app.route('/addWordUser')
  161. def add_word_user():
  162. added_user = Employee.query.filter_by(number_phone='123').one()
  163. word = Word(src='Мышь', translated='Mouse', owner=added_user)
  164. db.session.add(word)
  165. db.session.commit()
  166. return "ok"
  167.  
  168. @app.route('/userWords')
  169. def read_user_words():
  170. added_user = Employee.query.filter_by(number_phone='123').one()
  171. print(added_user.words)
  172. return str(added_user.words[-1].translated)
  173.  
  174.  
  175. USER_UNIQUE_KEY = 'userUniqueKey'
  176. # translate word if use was logged
  177. @app.route('/translateUniqueKey/<string:src_word>', methods=['POST'])
  178. # todo rename
  179. def translateWithUniqueUserKey(src_word):
  180. try:
  181. user_unique_key = request.args.get(USER_UNIQUE_KEY)
  182. if db.session.query(Employee).filter_by(user_unique_key=user_unique_key).count() < 1:
  183. # translate without added word in db
  184. # reuse method for translate word
  185. return translate(src_word)
  186. else:
  187. user = Employee.query.filter_by(user_unique_key=user_unique_key).one()
  188. translated_word = GoogleTranslator(source='auto', target='en').translate(src_word)
  189.  
  190. user_words = user.words
  191. if len(user_words) <= 0:
  192. # add word to db
  193. word = Word(src=src_word,translated=translated_word,owner=user)
  194. insert_word(word)
  195. return "Word " + src_word + " was success inserted in this user"
  196. else:
  197. user_src_words = list()
  198. for user_word in user_words:
  199. print(user_word.src)
  200. # add only src word
  201. user_src_words.append(user_word.src)
  202.  
  203. # check on unique word
  204. if src_word in user_src_words:
  205. return "Word " + src_word + " already exist in this user"
  206. else:
  207. # add word to db
  208. word = Word(src=src_word, translated=translated_word, owner=user)
  209. insert_word(word)
  210. return "Word " + src_word + " while not exist in this user"
  211.  
  212. except Exception as e:
  213. return "TranslateWithUniqueUserKey: " + str(e)
  214.  
  215. def insert_word(word):
  216. db.session.add(word)
  217. db.session.commit()
  218.  
  219. @app.route('/users')
  220. def users():
  221. users = Employee.query.all()
  222. users_name = list()
  223. for user in users:
  224. users_name.append(user.user_name)
  225. return jsonify(names=users_name) # {"names":["Kostya","Egor"]}
  226.  
  227. class UserWord:
  228. def __init__(self, src, translated):
  229. self.src = src
  230. self.translated = translated
  231.  
  232. def serialize(self):
  233. return {
  234. 'src': self.src,
  235. 'translated': self.translated
  236. }
  237.  
  238.  
  239. @app.route('/users/<string:user_name>/words')
  240. def words_user(user_name):
  241. user = Employee.query.filter_by(user_name=user_name).one()
  242. words = user.words
  243. user_words = []
  244. for word in words:
  245. user_word = UserWord(word.src,word.translated)
  246. user_words.append(user_word.serialize())
  247. return jsonify(user_words=user_words) #{"user_words":[{"src":"\u041b\u0430\u043c\u043e\u0434\u0430","translated":"Lamoda"},{"src":"\u041b\u0430\u043c\u043e\u0434\u0430","translated":"Lamoda"},{"src":"\u041b\u0430\u043c\u043e\u0434\u0430","translated":"Lamoda"}]}
  248.  
  249. # for test
  250. @app.route('/addUserForTest')
  251. def addUserForTest():
  252. try:
  253. db.create_all()
  254. db.session.commit()
  255. user = Employee(user_unique_key="123", user_name="Kostya", number_phone="123")
  256. db.session.add(user)
  257. db.session.commit()
  258. return "Success add user for test"
  259. except Exception as e:
  260. return "Add user for test error: " + str(e)
  261.  
  262. # for test
  263. @app.route('/addWordByName')
  264. def add_words_by_user_name():
  265. try:
  266. user = Employee.query.filter_by(user_name='Kostya').one()
  267. word = Word(src='Ламода', translated='Lamoda', owner=user)
  268. insert_word(word)
  269. return ""
  270. except Exception as e:
  271. return "Add word by name error: " + str(e)
  272.  
  273.  
  274. @app.route('/delete')
  275. def clear_db():
  276. try:
  277. Employee.query.delete()
  278. db.session.commit()
  279. return "Db was cleared"
  280. except Exception as e:
  281. return "Delete db error " + str(e)
  282.  
  283. #endregion
  284.  
  285. if __name__ == "__main__":
  286. app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement